vtkReebGraphToJoinSplitTreeFilter.cxx 15.6 KB
Newer Older
1 2 3
/*=========================================================================

  Program:   Visualization Toolkit
4
  Module:    vtkReebGraphToJoinSplitTreeFilter.cxx
5 6 7 8 9 10 11 12 13 14

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
Jason Shepherd's avatar
Jason Shepherd committed
15 16 17 18 19 20 21 22 23 24 25 26
#include "vtkReebGraphToJoinSplitTreeFilter.h"

#include "vtkDataSetAttributes.h"
#include "vtkEdgeListIterator.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkReebGraph.h"
#include "vtkVariantArray.h"
27

Jason Shepherd's avatar
Jason Shepherd committed
28 29
#include <algorithm>
#include <boost/pending/disjoint_sets.hpp>
30

31 32 33 34 35 36 37 38 39 40 41
namespace
{
//----------------------------------------------------------------------------
inline static bool vtkReebGraphVertexSoS(const std::pair<int, double> v0,
  const std::pair<int, double> v1)
{
  return ((v0.second < v1.second)
    || ((v0.second == v1.second)&&(v0.first < v1.first)));
}
}

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
vtkStandardNewMacro(vtkReebGraphToJoinSplitTreeFilter);

//----------------------------------------------------------------------------
vtkReebGraphToJoinSplitTreeFilter::vtkReebGraphToJoinSplitTreeFilter()
{
  this->SetNumberOfInputPorts(2);
  this->IsSplitTree = false;
  this->FieldId = 0;
}

//----------------------------------------------------------------------------
vtkReebGraphToJoinSplitTreeFilter::~vtkReebGraphToJoinSplitTreeFilter()
{
}

//----------------------------------------------------------------------------
int vtkReebGraphToJoinSplitTreeFilter::FillInputPortInformation(
  int portNumber, vtkInformation *info)
{

  switch(portNumber)
    {
    case 0:
      info->Remove(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE());
      info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPointSet");
      break;
    case 1:
      info->Remove(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE());
      info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkReebGraph");
      break;
    }
  return 1;
}

//----------------------------------------------------------------------------
int vtkReebGraphToJoinSplitTreeFilter::FillOutputPortInformation(
  int, vtkInformation *info)
{
  info->Set(vtkDirectedGraph::DATA_TYPE_NAME(), "vtkReebGraph");
  return 1;
}

//----------------------------------------------------------------------------
void vtkReebGraphToJoinSplitTreeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
Jason Shepherd's avatar
Jason Shepherd committed
88 89
  os << indent << "Is Split Tree: " << this->IsSplitTree << "\n";
  os << indent << "Field Id: " << this->FieldId << "\n";
90 91 92 93 94 95 96 97 98
}

//----------------------------------------------------------------------------
vtkReebGraph* vtkReebGraphToJoinSplitTreeFilter::GetOutput()
{
  return vtkReebGraph::SafeDownCast(this->GetOutputDataObject(0));
}

//----------------------------------------------------------------------------
Jason Shepherd's avatar
Jason Shepherd committed
99
int vtkReebGraphToJoinSplitTreeFilter::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector)
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
{

  vtkInformation  *inInfoMesh = inputVector[0]->GetInformationObject(0),
                  *inInfoGraph = inputVector[1]->GetInformationObject(0);

  if((!inInfoMesh)||(!inInfoGraph))
    return 0;

  vtkPointSet   *inputMesh = vtkPointSet::SafeDownCast(
    inInfoMesh->Get(vtkPointSet::DATA_OBJECT()));

  vtkReebGraph  *inputGraph = vtkReebGraph::SafeDownCast(
    inInfoGraph->Get(vtkReebGraph::DATA_OBJECT()));

  if((inputMesh)&&(inputGraph))
    {
    vtkInformation  *outInfo = outputVector->GetInformationObject(0);
    vtkReebGraph    *output = vtkReebGraph::SafeDownCast(
      outInfo->Get(vtkReebGraph::DATA_OBJECT()));


    if(output)
      {
      output->DeepCopy(inputGraph);

      // Retrieve the information regarding the critical nodes
      vtkDataArray  *vertexInfo = vtkDataArray::SafeDownCast(
        inputGraph->GetVertexData()->GetAbstractArray("Vertex Ids"));
      if(!vertexInfo)
        // invalid Reeb graph (no information associated to the vertices)
        return 0;

      vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast(
        inputGraph->GetEdgeData()->GetAbstractArray("Vertex Ids"));
      if(!edgeInfo)
        // invalid Reeb graph (no information associated to the edges)
        return 0;

      vtkDataArray  *scalarField = inputMesh->GetPointData()->GetArray(FieldId);
      if(!scalarField)
        // invalid input mesh (no scalar field associated to it)
        return 0;

      // first, uncompress the input Reeb graph.
144
      vtkMutableDirectedGraph *unCompressedGraph = vtkMutableDirectedGraph::New();
145 146 147
      std::vector<std::pair<int, double> > vertexList;
      for(int i = 0; i < vertexInfo->GetNumberOfTuples(); i++)
        {
148 149
        int vertexId = (int) *(vertexInfo->GetTuple(i));
        double scalarValue = scalarField->GetComponent(vertexId, 0);
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
        vertexList.push_back(std::pair<int, double>(vertexId, scalarValue));
        }

      vtkEdgeListIterator *eIt = vtkEdgeListIterator::New();
      inputGraph->GetEdges(eIt);
      do{
        vtkEdgeType e = eIt->Next();
        vtkAbstractArray *deg2NodeList = edgeInfo->GetPointer(e.Id)->ToArray();
        for(int i = 0; i < deg2NodeList->GetNumberOfTuples(); i++)
          {
          int vertexId = deg2NodeList->GetVariantValue(i).ToInt();
          double scalarValue = scalarField->GetComponent(vertexId, 0);
          vertexList.push_back(std::pair<int, double>(vertexId, scalarValue));
          }
      }while(eIt->HasNext());
      eIt->Delete();

      std::vector<int> vertexToNodeMap(vertexList.size());
      // create the nodes
      vtkVariantArray *vertexProperties = vtkVariantArray::New();
      vertexProperties->SetNumberOfValues(1);

      vtkIdTypeArray *vertexIds = vtkIdTypeArray::New();
      vertexIds->SetName("Vertex Ids");
      unCompressedGraph->GetVertexData()->AddArray(vertexIds);
Jason Shepherd's avatar
Jason Shepherd committed
175
      for(unsigned int i = 0; i < vertexList.size(); i++)
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
        {
        vertexProperties->SetValue(0, vertexList[i].first);
        unCompressedGraph->AddVertex(vertexProperties);
        vertexToNodeMap[vertexList[i].first] = i;
        }
      vertexIds->Delete();
      vertexProperties->Delete();

      eIt = vtkEdgeListIterator::New();
      inputGraph->GetEdges(eIt);
      do{
        vtkEdgeType e = eIt->Next();
        int sourceVertexId = (int) *(vertexInfo->GetTuple(e.Source)),
            targetVertexId = (int) *(vertexInfo->GetTuple(e.Target));
        vtkAbstractArray *deg2NodeList = edgeInfo->GetPointer(e.Id)->ToArray();

        if(!deg2NodeList->GetNumberOfTuples())
          {
          // empty arc
          unCompressedGraph->AddEdge(vertexToNodeMap[sourceVertexId],
            vertexToNodeMap[targetVertexId]);
          }
        else
          {
          unCompressedGraph->AddEdge(vertexToNodeMap[sourceVertexId],
            vertexToNodeMap[deg2NodeList->GetVariantValue(0).ToInt()]);

          for(int i = 1; i < deg2NodeList->GetNumberOfTuples(); i++)
            {
            unCompressedGraph->AddEdge(
              vertexToNodeMap[deg2NodeList->GetVariantValue(i - 1).ToInt()],
              vertexToNodeMap[deg2NodeList->GetVariantValue(i).ToInt()]);
            }

          unCompressedGraph->AddEdge(
            vertexToNodeMap[deg2NodeList->GetVariantValue(
              deg2NodeList->GetNumberOfTuples() - 1).ToInt()],
            vertexToNodeMap[targetVertexId]);
          }
      }while(eIt->HasNext());
      eIt->Delete();
      // input graph uncompressed.

      // now the actual join/split tree algorithm.

      // sort the vertices, by increasing order for join trees and
      // decreasing order for split trees.
      std::sort(vertexList.begin(), vertexList.end(), vtkReebGraphVertexSoS);

      if(IsSplitTree)
        {
          // reverse the list of vertices
          std::vector<std::pair<int, double> > tmpVector(vertexList);
229
          for(int i = static_cast<int>(tmpVector.size()) - 1; i >= 0; i--)
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
            {
            vertexList[vertexList.size() - i - 1] = tmpVector[i];
            }
        }

      // then, prepare the necessary adjacency information
      std::vector<std::vector<int> >
        halfStars(vertexList.size());

      vertexInfo = vtkDataArray::SafeDownCast(
        unCompressedGraph->GetVertexData()->GetAbstractArray("Vertex Ids"));
      eIt = vtkEdgeListIterator::New();
      unCompressedGraph->GetEdges(eIt);

      do
        {
        vtkEdgeType e = eIt->Next();
        int sourceId = (vtkIdType) *(vertexInfo->GetTuple(e.Source)),
            targetId = (vtkIdType) *(vertexInfo->GetTuple(e.Target));

        if(!IsSplitTree)
          halfStars[targetId].push_back(sourceId);
        else halfStars[sourceId].push_back(targetId);

        }while(eIt->HasNext());
      eIt->Delete();
      // at this point, we don't need the unCompressedGraph anymore now that we
      // have the halfStars correctly built.
      unCompressedGraph->Delete();

      // prepare the intermediate data-structure
      std::vector<std::pair<std::pair<int, int>, std::vector<int> > >
        edgeList(vertexList.size());
Jason Shepherd's avatar
Jason Shepherd committed
263
      for(unsigned int i = 0; i < edgeList.size(); i++)
264 265 266 267 268 269 270 271 272 273 274 275 276
        {
        edgeList[i].first.first = -1;
        edgeList[i].first.second = -1;
        }

      // prepare the unionFind
      std::vector<int>  rank(vertexList.size());
      std::vector<int>  parent(vertexList.size());
      boost::disjoint_sets<int *, int *> unionFind(&rank[0], &parent[0]);

      // enables a compressed usage of the UF
      std::vector<int> vertexToUFQueryMap(vertexList.size());

277
      int representative=0;
278 279 280

      // we don't parse the last vertex, for sure it's gonna be the
      // global "max".
Jason Shepherd's avatar
Jason Shepherd committed
281
      for(unsigned int i = 0; i < vertexList.size() - 1; i++)
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        {

        if(halfStars[vertexList[i].first].empty())
          {
          // this is leaf (either a min or a max)
          unionFind.make_set(vertexList[i].first);
          vertexToUFQueryMap[vertexList[i].first] = vertexList[i].first;
          representative = unionFind.find_set(vertexList[i].first);
          edgeList[representative].first.first = vertexList[i].first;
          }

        else
          {
          std::vector<int> representatives;
          // this is not a leaf node.
          // let's collect the unionFind representatives

Jason Shepherd's avatar
Jason Shepherd committed
299
          for(unsigned int j = 0; j < halfStars[vertexList[i].first].size(); j++)
300 301 302 303 304 305
            {
            representative = unionFind.find_set(
              vertexToUFQueryMap[halfStars[vertexList[i].first][j]]);

            // add it to the representative list
            bool isAlreadyStored = false;
Jason Shepherd's avatar
Jason Shepherd committed
306
            for(unsigned int k = 0;
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
              ((k < representatives.size())&&(!isAlreadyStored)); k++)
              {
              // 95% of time this will loop only once (depending on the field
              // complexity).
              //
              // if there is a non-degenerate (index 3) merge. it will loop
              // twice.
              //
              // High-index degenerate merge have a very very low probability of
              // appearance which is roughly inversely proportionnal to way more
              // than its index.
              if(representatives[k] == representative)
                {
                isAlreadyStored = true;
                }
              }
            if(!isAlreadyStored) representatives.push_back(representative);
            }


          if(representatives.size() == 1)
            {
            // add a deg2 node
330
            edgeList[representative].second.push_back(vertexList[i].first);
331 332 333 334 335 336 337 338
            // propagate the vertexId to be used to query the UF.
            vertexToUFQueryMap[vertexList[i].first] =
              vertexToUFQueryMap[halfStars[vertexList[i].first][
                halfStars[vertexList[i].first].size() - 1]];
            }
          else
            {
            // close the incoming edges
Jason Shepherd's avatar
Jason Shepherd committed
339
            for(unsigned int j = 0; j < representatives.size(); j++)
340 341 342 343 344 345
              {
              edgeList[representatives[j]].first.second = vertexList[i].first;
              }
            // now open a new edge
            unionFind.make_set(vertexList[i].first);
            representative = unionFind.find_set(vertexList[i].first);
Jason Shepherd's avatar
Jason Shepherd committed
346
            for(unsigned int j = 0; j < representatives.size(); j++)
347 348 349 350 351 352 353 354 355
              unionFind.link(representatives[j], representative);

            vertexToUFQueryMap[vertexList[i].first] = vertexList[i].first;
            edgeList[representative].first.first = vertexList[i].first;
            }
          }
        }

      // put the global "max"
356
      representative = unionFind.find_set(vertexToUFQueryMap[halfStars[vertexList[vertexList.size() - 1].first][0]]);
357 358 359 360 361 362 363 364 365 366

      edgeList[representative].first.second =
        vertexList[vertexList.size() - 1].first;
      // join/split tree completed.

      // now format the output
      vtkMutableDirectedGraph *outputGraph = vtkMutableDirectedGraph::New();

      std::vector<int>  criticalVertices;
      std::vector<bool> processedVertices(vertexList.size());
Jason Shepherd's avatar
Jason Shepherd committed
367
      for(unsigned int i = 0; i < processedVertices.size(); i++)
368 369 370
        processedVertices[i] = false;

      // first, create the list of nodes.
Jason Shepherd's avatar
Jason Shepherd committed
371
      for(unsigned int i = 0; i < edgeList.size(); i++)
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
        {
        if(edgeList[i].first.first != -1)
          {
          // valid edge
          if(!processedVertices[edgeList[i].first.first])
            {
            criticalVertices.push_back(edgeList[i].first.first);
            processedVertices[edgeList[i].first.first] = true;
            }
          if(!processedVertices[edgeList[i].first.second])
            {
            criticalVertices.push_back(edgeList[i].first.second);
            processedVertices[edgeList[i].first.second] = true;
            }
          }
        }


      vertexToNodeMap.resize(criticalVertices.size());

      vertexProperties = vtkVariantArray::New();
      vertexProperties->SetNumberOfValues(1);
      vertexIds = vtkIdTypeArray::New();
      vertexIds->SetName("Vertex Ids");
      outputGraph->GetVertexData()->AddArray(vertexIds);
Jason Shepherd's avatar
Jason Shepherd committed
397
      for(unsigned int i = 0; i < criticalVertices.size(); i++)
398 399 400 401 402 403 404 405 406 407 408 409 410
        {
        vertexProperties->SetValue(0, criticalVertices[i]);
        vertexToNodeMap[criticalVertices[i]] = i;
        outputGraph->AddVertex(vertexProperties);
        }
      vertexIds->Delete();
      vertexProperties->Delete();


      vtkVariantArray *deg2NodeIds = vtkVariantArray::New();
      deg2NodeIds->SetName("Vertex Ids");
      outputGraph->GetEdgeData()->AddArray(deg2NodeIds);

Jason Shepherd's avatar
Jason Shepherd committed
411
      for(unsigned int i = 0; i < edgeList.size(); i++)
412 413 414 415 416 417 418 419 420
        {
        if(edgeList[i].first.first != -1)
          {
          // valid edge
          int sourceNode = vertexToNodeMap[edgeList[i].first.first],
              targetNode = vertexToNodeMap[edgeList[i].first.second];
          vtkVariantArray *edgeProperties = vtkVariantArray::New();
          vtkIdTypeArray  *vertexIdList = vtkIdTypeArray::New();
          vertexIdList->SetNumberOfValues(edgeList[i].second.size());
Jason Shepherd's avatar
Jason Shepherd committed
421
          for(unsigned int j = 0; j < edgeList[i].second.size(); j++)
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
            vertexIdList->SetValue(j, edgeList[i].second[j]);
          edgeProperties->SetNumberOfValues(1);
          edgeProperties->SetValue(0, vertexIdList);
          outputGraph->AddEdge(sourceNode, targetNode, edgeProperties);
          vertexIdList->Delete();
          edgeProperties->Delete();
          }
        }
      deg2NodeIds->Delete();

      output->Set(outputGraph);

      outputGraph->Delete();

      return 1;
      }
    }
  return 0;
}