lsgrmController.txx 15.4 KB
Newer Older
1 2
#ifndef __LSGRM_CONTROLLER_TXX
#define __LSGRM_CONTROLLER_TXX
remicres's avatar
remicres committed
3
#include "lsgrmController.h"
4 5 6 7

namespace lsgrm
{

remicres's avatar
remicres committed
8 9 10
template<class TSegmenter>
Controller<TSegmenter>::Controller()
{
11
  m_TilingMode = LSGRM_TILING_AUTO;
12 13 14 15 16 17 18 19 20
  m_Margin = 0;
  m_NumberOfIterations = 0;
  m_NumberOfFirstIterations = 0;
  m_TileHeight = 0;
  m_TileWidth = 0;
  m_NbTilesX = 0;
  m_NbTilesY = 0;
  m_Threshold = 75;
  m_Memory = 0;
21

remicres's avatar
remicres committed
22 23 24 25 26 27 28
}

template<class TSegmenter>
Controller<TSegmenter>::~Controller()
{
}

29 30 31 32 33 34 35
template<class TSegmenter>
void Controller<TSegmenter>::Modified()
{
  Superclass::Modified();
  m_Tiles.clear();
}

36 37 38 39
/*
 * Run the segmentation
 * TODO: compute the correct number of iterations !
 */
remicres's avatar
remicres committed
40 41 42
template<class TSegmenter>
void Controller<TSegmenter>::RunSegmentation()
{
remicres's avatar
remicres committed
43
  itkDebugMacro(<< "Entering RunSegmentation()");
remicres's avatar
remicres committed
44

45 46
  CheckMemorySize();

47
  if (m_TilingMode == LSGRM_TILING_AUTO || m_TilingMode == LSGRM_TILING_USER)
remicres's avatar
remicres committed
48
    {
49 50 51 52
    if(m_TilingMode == LSGRM_TILING_AUTO)
      {
      this->GetAutomaticConfiguration();
      }
53
    else // m_TilingMode is LSGRM_TILING_USER
54
      {
remicres's avatar
remicres committed
55 56
      m_NbTilesX = std::floor(m_InputImage->GetLargestPossibleRegion().GetSize()[0] / m_TileWidth);
      m_NbTilesY = std::floor(m_InputImage->GetLargestPossibleRegion().GetSize()[1] / m_TileHeight);
57 58 59 60
      m_Margin = static_cast<unsigned int>(pow(2, m_NumberOfFirstIterations + 1) - 2);
      }

    std::cout <<
61 62 63 64 65 66 67
        "--- Configuration: " <<
        "\n\tAvailable RAM: " << m_Memory <<
        "\n\tInput image dimensions: " << m_InputImage->GetLargestPossibleRegion().GetSize() <<
        "\n\tNumber of first iterations: " << m_NumberOfFirstIterations <<
        "\n\tStability margin: " << m_Margin <<
        "\n\tRegular tile size: " << m_TileWidth << " x " << m_TileHeight <<
        "\n\tTiling layout: " << m_NbTilesX << " x " << m_NbTilesY << std::endl;
remicres's avatar
remicres committed
68 69

    // Compute the splitting scheme
70 71
    m_Tiles = SplitOTBImage<ImageType>(m_InputImage, m_TileWidth, m_TileHeight, m_Margin,
        m_NbTilesX, m_NbTilesY, m_TemporaryFilesPrefix);
remicres's avatar
remicres committed
72

73
    // If there is only one tile, then fallback to LSGRM_TILING_NONE case
74 75 76 77 78
    if (m_Tiles.size() == 1)
      {
      std::cout << "Only one tile is needed. Fallback to tiling=none." << std::endl;
      SetTilingModeNone();
      }
79 80 81 82
    }

  if (m_TilingMode == LSGRM_TILING_AUTO || m_TilingMode == LSGRM_TILING_USER)
    {
83
    const unsigned int numberOfIterationsForPartialSegmentations = 3; // TODO: find a smart value
84 85
    unsigned int numberOfIterationsRemaining = m_NumberOfIterations;

remicres's avatar
remicres committed
86 87 88 89 90
    // Boolean indicating if there are remaining fusions
    bool isFusion = false;

    // Run first partial segmentation
    boost::timer t; t.restart();
91
	
remicres's avatar
remicres committed
92 93 94 95 96
    auto accumulatedMemory = RunFirstPartialSegmentation<TSegmenter>(
        m_InputImage,
        m_SpecificParameters,
        m_Threshold,
        m_NumberOfFirstIterations,
97
        numberOfIterationsForPartialSegmentations,
remicres's avatar
remicres committed
98 99 100 101 102 103 104
        m_Tiles,
        m_NbTilesX,
        m_NbTilesY,
        m_TileWidth,
        m_TileHeight,
        isFusion);

105
#ifdef OTB_USE_MPI
remicres's avatar
remicres committed
106
    GatherUsefulVariables(accumulatedMemory, isFusion);
107
#endif
remicres's avatar
remicres committed
108 109 110 111 112

    // Time monitoring
    ShowTime(t);

    while(accumulatedMemory > m_Memory && isFusion)
remicres's avatar
remicres committed
113
      {
remicres's avatar
remicres committed
114 115
      isFusion = false;
      accumulatedMemory = RunPartialSegmentation<TSegmenter>(
remicres's avatar
remicres committed
116 117
          m_SpecificParameters,
          m_Threshold,
118
          numberOfIterationsForPartialSegmentations,
remicres's avatar
remicres committed
119 120 121 122 123 124
          m_Tiles,
          m_NbTilesX,
          m_NbTilesY,
          m_InputImage->GetLargestPossibleRegion().GetSize()[0],
          m_InputImage->GetLargestPossibleRegion().GetSize()[1],
          m_InputImage->GetNumberOfComponentsPerPixel(),
remicres's avatar
remicres committed
125 126
          isFusion);

127
#ifdef OTB_USE_MPI
remicres's avatar
remicres committed
128
      GatherUsefulVariables(accumulatedMemory, isFusion);
129
#endif
130

remicres's avatar
remicres committed
131 132
      // Time monitoring
      ShowTime(t);
133

134 135 136
      // Update number of remaining iterations
      if (numberOfIterationsRemaining < numberOfIterationsForPartialSegmentations)
        {
137
        break;
138 139 140 141 142
        }
      else
        {
        numberOfIterationsRemaining -= numberOfIterationsForPartialSegmentations;
        }
remicres's avatar
remicres committed
143
      }
144
	
remicres's avatar
remicres committed
145
#ifdef OTB_USE_MPI
146
    // Only the master process is doing the next part
remicres's avatar
remicres committed
147
    // TODO: Use the MPI process wich has the largest amount of memory
remicres's avatar
remicres committed
148 149 150 151 152 153 154
    if (otb::MPIConfig::Instance()->GetMyRank() != 0)
      return;
#endif

    if(accumulatedMemory <= m_Memory)
      {
      // Merge all the graphs
155
        m_OutputGraph = MergeAllGraphsAndAchieveSegmentation<TSegmenter>(
remicres's avatar
remicres committed
156 157 158 159 160 161 162
          m_SpecificParameters,
          m_Threshold,
          m_Tiles,
          m_NbTilesX,
          m_NbTilesY,
          m_InputImage->GetLargestPossibleRegion().GetSize()[0],
          m_InputImage->GetLargestPossibleRegion().GetSize()[1],
163
          m_InputImage->GetNumberOfComponentsPerPixel(),
164
          numberOfIterationsRemaining);
remicres's avatar
remicres committed
165

166
      ShowTime(t);
remicres's avatar
remicres committed
167 168

      }
169
    else // accumulatedMemory > m_Memory
remicres's avatar
remicres committed
170
      {
remicres's avatar
remicres committed
171
      // That means there are no more possible fusions but we can not store the output graph
remicres's avatar
remicres committed
172 173
      // Todo do not clean up temporary directory before copying resulting graph to the output directory
      // In the output directory add an info file to give the number of tiles.
174
      itkExceptionMacro(<< "No more possible fusions, but can not store the output graph");
remicres's avatar
remicres committed
175 176
      }
    }
remicres's avatar
remicres committed
177
  else if (m_TilingMode == LSGRM_TILING_NONE)// tiling_mode is none
remicres's avatar
remicres committed
178
    {
remicres's avatar
remicres committed
179 180 181 182 183 184 185 186 187
#ifdef OTB_USE_MPI
    // Only the master process is doing the next part
    if (otb::MPIConfig::Instance()->GetMyRank() > 0)
      return;
    else
      // Warn that there is some unused MPI processes
      if (otb::MPIConfig::Instance()->GetNbProcs() > 1)
        itkWarningMacro(<< "Only 1 MPI process will be used");
#endif
188 189 190
    // Update input image
    m_InputImage->Update();

remicres's avatar
remicres committed
191 192 193 194
    // Use classic grm
    TSegmenter segmenter;
    segmenter.SetParam(m_SpecificParameters);
    segmenter.SetThreshold(m_Threshold);
195
    segmenter.SetDoFastSegmentation(false);
remicres's avatar
remicres committed
196 197 198
    segmenter.SetNumberOfIterations(m_NumberOfIterations);
    segmenter.SetInput(m_InputImage);
    segmenter.Update();
199

200
    m_OutputGraph = segmenter.m_Graph;
remicres's avatar
remicres committed
201 202 203 204
    }
  else
    {
    itkExceptionMacro(<<"Unknow tiling mode!");
remicres's avatar
remicres committed
205 206
    }

207 208
  // TODO: [MPI] broadcast the graph to other nodes

remicres's avatar
remicres committed
209 210
}

211 212
/*
 * Compute the memory occupied by one node
remicres's avatar
remicres committed
213 214
 * TODO: compute the exact value, e.g. on a given UNIX system,
 * experimental measures shows that
215
 * for one Baatz node (+pixel) memory is about 700-730 bytes...
remicres's avatar
remicres committed
216
 * And our estimation is about 600
217 218 219 220
 */
template<class TSegmenter>
unsigned int Controller<TSegmenter>::GetNodeMemory()
{
221
  // Create a n*n image
222
  const unsigned int n = 100;
223 224 225 226
  typename ImageType::Pointer onePixelImage = ImageType::New();
  typename ImageType::IndexType start;
  start.Fill(0);
  typename ImageType::SizeType size;
227
  size.Fill(n);
228 229 230 231
  typename ImageType::RegionType region(start, size);
  onePixelImage->SetRegions(region);
  onePixelImage->SetNumberOfComponentsPerPixel(m_InputImage->GetNumberOfComponentsPerPixel());
  onePixelImage->Allocate();
232 233

  // Instanciate and initialize a segmenter
234 235
  TSegmenter segmenter;
  segmenter.SetInput(onePixelImage);
236
  grm::GraphOperations<TSegmenter>::InitNodes(onePixelImage,segmenter,FOUR);
237

238
  // Get the memory occupied by the graph, normalize it by n*n
239
  unsigned int memory = segmenter.GetGraphMemory() / (n*n);
240

241
  itkDebugMacro(<<"Size of a node is " << memory);
242 243

  // Get the memory occupied by one pixel of the image
244 245
  unsigned int pixelMemory =  sizeof(m_InputImage->GetBufferPointer())
      * m_InputImage->GetNumberOfComponentsPerPixel();
246

247
  itkDebugMacro(<<"Size of an image pixel is " << pixelMemory);
248 249 250

  memory += pixelMemory;

251
  itkDebugMacro(<<"Size of a node+pixel is " << memory);
252

253
  return memory;
254
}
remicres's avatar
remicres committed
255

remicres's avatar
remicres committed
256
template<class TSegmenter>
257
void Controller<TSegmenter>::CheckMemorySize()
remicres's avatar
remicres committed
258
{
259 260 261 262 263
  if (m_Memory == 0)
    {
    m_Memory = getMemorySize();
    assert(m_Memory > 0);
    }
remicres's avatar
remicres committed
264
  m_Memory /= 2; // For safety and can prevent out of memory troubles
265 266 267 268 269
}
/*
 * Compute the maximum number of nodes which can fit in the memory
 */
template<class TSegmenter>
270
std::size_t Controller<TSegmenter>::GetMaximumNumberOfNodesInMemory()
271 272
{
  itkDebugMacro(<< "Computing maximum number of nodes in memory");
remicres's avatar
remicres committed
273

274
  return std::ceil(((float) m_Memory) / ((float) GetNodeMemory()));
275 276 277
}

template<class TSegmenter>
278
void Controller<TSegmenter>::ComputeMaximumStabilityMargin(unsigned int width,
279
    unsigned int height, unsigned int &niter, unsigned int &margin)
280
    {
281 282 283 284
  itkDebugMacro(<< "Computing maximum stability margin");

  // Compute the stability margin. The naive strategy consider a margin value and a stable size equal.
  niter = 1;
285 286 287
  unsigned int maxMargin = std::min(width, height)/2;
  unsigned int currMargin = static_cast<unsigned int>(pow(2, niter + 1) - 2);
  margin = currMargin;
remicres's avatar
remicres committed
288

289
  while(currMargin < maxMargin)
290
    {
291
    margin = currMargin;
292
    niter++;
293
    currMargin = static_cast<unsigned int>(pow(2, niter + 1) - 2);
294 295 296 297
    }
  niter--;

  itkDebugMacro(<< "Number of iterations=" << niter << " margin=" << margin);
remicres's avatar
remicres committed
298

299
    }
remicres's avatar
remicres committed
300

301
/*
302
 * Compute a tiling layout which minimizes a criterion based on tile compactness
303
 * and memory usage
304 305
 *
 * TODO: use the lsgrmSplitter to truly compute the largest tile of a given layout
306
 */
remicres's avatar
remicres committed
307 308 309 310
template<class TSegmenter>
void Controller<TSegmenter>::GetAutomaticConfiguration()
{

311 312
  itkDebugMacro(<<"Get automatic configuration");

remicres's avatar
remicres committed
313
  // Compute the maximum number of nodes that can fit the memory
remicres's avatar
remicres committed
314
  // TODO: Use the smallest number amongst MPI processes
remicres's avatar
remicres committed
315
  unsigned long int maximumNumberOfNodesInMemory = GetMaximumNumberOfNodesInMemory();
316
  itkDebugMacro(<<"Maximum number of nodes in memory is " << maximumNumberOfNodesInMemory);
remicres's avatar
remicres committed
317

318
  // Number of nodes in the entire image
319 320 321
  const std::size_t imageWidth = m_InputImage->GetLargestPossibleRegion().GetSize()[0];
  const std::size_t imageHeight = m_InputImage->GetLargestPossibleRegion().GetSize()[1];
  const std::size_t nbOfNodesInImage = imageWidth*imageHeight;
322

323
  // Default layout: 1x1
remicres's avatar
remicres committed
324 325
  m_NbTilesX = 1;
  m_NbTilesY = 1;
326

327 328 329 330 331
  // Without margins, the number of tiles maximizing memory use
  // is equal to: nbOfNodesInImage / maximumNumberOfNodesInMemory.
  // Actually, there is tile margins. And the best scenario is to have
  // square tiles with margin = width/2, that is tiles 4x larger.
  // Hence the number of tiles maximizing memory use is 4x larger.
332
  unsigned int minimumNumberOfTiles = std::ceil(4.0 * ((float) nbOfNodesInImage) / ((float) maximumNumberOfNodesInMemory));
333 334 335 336
  itkDebugMacro(<<"Minimum number of tiles is " << minimumNumberOfTiles);

  // In the following steps, we will optimize tiling layout, starting from a number
  // of tiles equal to "minimumNumberOfTiles", up to a number of tiles equal to
337
  // 4 times the number of tiles (that is double rows/cols)
338 339 340 341 342 343 344 345
  unsigned int maximumNumberOfTiles = minimumNumberOfTiles * 4;

  // Search for layout which minimizes the criterion
  // The criterion is the ratio between compactness and memory usage
  // (i.e. tileWidth * tileHeight / maximumNumberOfNodesInMemory)
  itkDebugMacro(<<"Computing layouts properties:");
  float lowestCriterionValue = itk::NumericTraits<float>::max();
  for (unsigned int nbOfTiles = minimumNumberOfTiles ; nbOfTiles <= maximumNumberOfTiles ; nbOfTiles++)
346
    {
347 348
    // Get the multiples of k. For each one, compute the criterion of the tiling
    for (unsigned int layoutNCol = 1; layoutNCol<=nbOfTiles; layoutNCol++)
remicres's avatar
remicres committed
349
      {
350 351
#ifdef OTB_USE_MPI
      // We want number of tiles which is a multiple of the number of MPI processes
352 353
      if (nbOfTiles % layoutNCol == 0 && // Is it a multiple of the nb of Tiles and nProcs?
          nbOfTiles % otb::MPIConfig::Instance()->GetNbProcs() == 0)
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
#else
        if (nbOfTiles % layoutNCol == 0) // Is it a multiple of the nb of Tiles?
#endif
          {
          // Tiling layout
          unsigned int layoutNRow = nbOfTiles / layoutNCol;
          unsigned int tileWidth = imageWidth / layoutNCol;
          unsigned int tileHeight = imageHeight / layoutNRow;

          // Compute margin for regular tiles of this layout
          unsigned int maxMargin, maxIter;
          ComputeMaximumStabilityMargin(tileWidth, tileHeight, maxIter, maxMargin);
          tileWidth += 2*maxMargin;
          tileHeight += 2*maxMargin;

          // Memory use efficiency
370
          float percentMemory = tileWidth * tileHeight / (float) maximumNumberOfNodesInMemory; // is > 0. Could be greater than 1 in some cases!
371 372 373 374

          // Compactness
          float perimeter = tileWidth + tileHeight;
          float surface = tileWidth * tileHeight;
375
          float compactness = perimeter / surface * (float) std::max(tileWidth,tileHeight); // [1,+inf]
376 377 378 379

          // Update minimum criterion
          float criterion = compactness / percentMemory; // ]0, +inf]

380
          itkDebugMacro(//<< std::setprecision (2) << std::fixed
381 382 383 384 385 386 387 388 389
              << "Nb. tiles=" << nbOfTiles
              << " Layout: " << layoutNRow << "x" << layoutNCol
              << " Mem. use=" << percentMemory
              << " Compactness=" << compactness
              << " Criterion=" << criterion
              << " Size (no margin): " << (tileWidth-2*maxMargin)<< "x"<< (tileHeight-2*maxMargin)
              << " Size (with margin): " << tileWidth << "x" << tileHeight
              << " (margin=" << maxMargin << "/nb. iter=" << maxIter << ")" );

390
          if (criterion < lowestCriterionValue && percentMemory <= 1.0)
391 392 393 394 395 396 397 398
            {
            lowestCriterionValue = criterion;
            m_NbTilesX = layoutNCol;
            m_NbTilesY = layoutNRow;
            }
          }
      } // for each multiple of k
    }
remicres's avatar
remicres committed
399 400 401 402

  // Compute the tile size
  m_TileWidth = static_cast<unsigned int>(imageWidth/m_NbTilesX);
  m_TileHeight = static_cast<unsigned int>(imageHeight/m_NbTilesY);
403 404 405 406 407 408
  itkDebugMacro(<<"Selected layout: " << m_NbTilesX << "x" << m_NbTilesY
      << " (criterion=" << lowestCriterionValue << ")");

  // Compute the stability margin
  ComputeMaximumStabilityMargin(m_TileWidth, m_TileHeight,m_NumberOfFirstIterations, m_Margin);

409 410 411
  long long unsigned int memoryUsed = GetNodeMemory();
  memoryUsed *= static_cast<long long unsigned int>(m_TileHeight + 2*m_Margin);
  memoryUsed *= static_cast<long long unsigned int>(m_TileWidth + 2*m_Margin);
412
  itkDebugMacro(<< "An amount of " << memoryUsed/(1024.0*1024.0) << " Mbytes of RAM will be used for regular tiles of size "
413
      << (m_TileWidth + 2*m_Margin) << "x" << (m_TileHeight + 2*m_Margin) );
remicres's avatar
remicres committed
414

remicres's avatar
remicres committed
415 416
}

remicres's avatar
remicres committed
417 418 419
template <class TSegmenter>
void Controller<TSegmenter>::SetInternalMemoryAvailable(long long unsigned int v) // expecting a value in Mbytes.
{
420 421 422 423
  if (v<=0)
    {
    itkExceptionMacro(<<"Memory value is not valid (value=" << v << ")");
    }
remicres's avatar
remicres committed
424 425 426 427
  m_Memory = v * 1024ul * 1024ul;
}

template<class TSegmenter>
remicres's avatar
remicres committed
428
void Controller<TSegmenter>::SetInputImage(ImageType * inputImage)
remicres's avatar
remicres committed
429
{
remicres's avatar
remicres committed
430
  m_InputImage = inputImage;
remicres's avatar
remicres committed
431 432 433 434 435 436 437 438
}

template<class TSegmenter>
void Controller<TSegmenter>::SetSpecificParameters(const SegmentationParameterType& params)
{
  m_SpecificParameters = params;
}

439 440 441 442 443 444 445 446 447 448
//template<class TSegmenter>
//typename Controller<TSegmenter>::LabelImageType::Pointer
//Controller<TSegmenter>::GetLabeledClusteredOutput()
//{
//#ifdef OTB_USE_MPI
//  // Get the label image from the master process (the one which achieves segmentation)
//  BroadcastImage<typename TSegmenter::LabelImageType>(m_LabelImage);
//#endif
//  return m_LabelImage;
//}
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

template <class TSegmenter>
std::vector<std::string> Controller<TSegmenter>::GetTemporaryFilesList()
{
  std::vector<std::string> list;
  for (unsigned int i = 0; i < m_Tiles.size(); i++)
    {
    list.push_back(m_Tiles[i].edgeFileName);
    list.push_back(m_Tiles[i].edgeMarginFileName);
    list.push_back(m_Tiles[i].nodeFileName);
    list.push_back(m_Tiles[i].nodeMarginFileName);
    }
  return list;
}

remicres's avatar
remicres committed
464
} // end of namespace lsgrm
465
#endif