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
|
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: $RCSfile: itkDijkstrasAlgorithm.h,v $ Language: C++
Date: $Date: 2008/06/05 18:39:14 $
Version: $Revision: 1.8 $
Copyright (c) 2001 Insight Consortium
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the Insight Consortium, nor the names of any consortium members,
nor of any contributors, may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#ifndef _itkDijkstrasAlgorithm_h_
#define _itkDijkstrasAlgorithm_h_
#include <string>
#include <iostream>
#include <stack>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include "vnl/vnl_math.h"
// #include "vnl/vnl_matrix_fixed.h"
// #include "vnl/vnl_vector_fixed.h"
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkNeighborhoodIterator.h"
#include "itkVector.h"
using namespace std;
namespace itk
{
/** The GraphSearchNode class defines a general shortest path graph node.
* The algorithm requires
* the node to have a pointer to itself and entry for the cumulative cost.
* We also define an index to its location and a couple of booleans
* for keeping track of the graph node's state.
* We assume the connectivity between nodes is defined externally.
* The class will also be useful for minimum spanning trees and
* other graph search algorithms. Connectivity is defined externally.
* May be worthwhile to implement arbitrary connectivity e.g. for random graphs.
* One way to do this is to include a list of pointers which define
* the neighbors of this node, similar to how the predecessor is defined.
*/
template <class TPixelType, typename TCoordRep = unsigned int,
unsigned int NGraphDimension = 2>
class GraphSearchNode : public itk::LightObject
{
public:
/* Standard typedefs.*/
typedef GraphSearchNode Self;
typedef LightObject Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
itkTypeMacro(GraphSearchNode, LightObject);
itkNewMacro(Self); /** Method for creation through the object factory. */
enum StateType { UnVisitedState, VisitedState, DeliveredState, UnVisitableState };
enum { GraphDimension = NGraphDimension };
typedef TPixelType PixelType; /** defines the cost data type */
typedef TCoordRep CoordRep; /** defines the location data type */
typedef itk::Vector<CoordRep, GraphDimension> NodeLocationType;
// typedef typename itk::Image<float,GraphDimension>::IndexType NodeLocationType;
typedef vector<Pointer> NodeListType;
// typedef itk::Image<CoordRep,GraphDimension>::IndexType NodeLocationType;
inline void SetLocation(NodeLocationType loc)
{
m_Location = loc;
}
inline NodeLocationType GetLocation()
{
return m_Location;
}
inline void SetTotalCost(TPixelType cost)
{
m_TotalCost = cost;
}
inline void SetValue(TPixelType cost, int which = 0)
{
if( which <= 0 )
{
m_Value1 = cost;
}
if( which == 1 )
{
m_Value2 = cost;
}
if( which == 2 )
{
m_Value3 = cost;
}
if( which >= 3 )
{
m_Value4 = cost;
}
}
inline TPixelType GetValue(int which = 0)
{
if( which <= 0 )
{
return m_Value1;
}
if( which == 1 )
{
return m_Value2;
}
if( which == 2 )
{
return m_Value3;
}
if( which >= 3 )
{
return m_Value4;
}
return m_Value1;
}
inline void SetUnVisited()
{
m_State = UnVisitedState;
}
inline void SetUnVisitable()
{
m_State = UnVisitableState;
}
inline void SetVisited()
{
m_State = VisitedState;
}
inline void SetDelivered()
{
m_State = DeliveredState;
}
inline bool IsInQueue()
{
if( m_State == VisitedState )
{
return true;
}
else
{
return false;
}
}
inline bool WasVisited()
{
if( m_State == VisitedState )
{
return true;
}
else if( m_State == DeliveredState )
{
return true;
}
else
{
return false;
}
}
inline TPixelType GetTotalCost()
{
return m_TotalCost;
}
inline void SetPredecessor(Pointer address)
{
m_PredecessorAddress = address;
}
inline Pointer GetPredecessor()
{
return m_PredecessorAddress;
}
inline void SetAncestor(Pointer address)
{
m_AncestorAddress = address;
}
inline Pointer GetAncestor()
{
return m_AncestorAddress;
}
inline bool GetUnVisited()
{
if( m_State == UnVisitedState )
{
return true;
}
else
{
return false;
}
}
inline bool GetUnVisitable()
{
if( m_State == UnVisitableState )
{
return true;
}
else
{
return false;
}
}
inline bool GetVisited()
{
if( m_State == VisitedState )
{
return true;
}
else
{
return false;
}
}
inline bool GetDelivered()
{
if( m_State == DeliveredState )
{
return true;
}
else
{
return false;
}
}
inline void SetState(StateType S)
{
m_State = S;
}
inline StateType GetState()
{
return m_State;
}
inline void SetIdentity(unsigned int i)
{
m_Identity = i;
}
inline unsigned int GetIdentity()
{
return m_Identity;
}
inline int GetNumberOfNeighbors()
{
return m_Neighbors.size();
}
inline Pointer GetNeighbor(int i)
{
return m_Neighbors[i];
}
void SetNeighborSize(int i)
{
m_Neighbors.resize(i);
}
NodeListType m_Neighbors;
unsigned short m_NumberOfNeighbors;
unsigned int m_Identity;
protected:
GraphSearchNode()
{
m_TotalCost = 0.0;
m_Value1 = 0.0;
m_Value2 = 0.0;
m_Value3 = 0.0;
m_Value4 = 0.0;
m_PredecessorAddress = NULL;
m_AncestorAddress = NULL;
m_State = UnVisitedState;
m_NumberOfNeighbors = 0;
m_Identity = 0;
}
~GraphSearchNode()
{
}
private:
TPixelType m_TotalCost; /** keeps track of the minimum accumulated cost. */
TPixelType m_Value1; /** keeps track of the minimum accumulated cost. */
TPixelType m_Value2; /** keeps track of the minimum accumulated cost. */
TPixelType m_Value3; /** keeps track of the minimum accumulated cost. */
TPixelType m_Value4; /** keeps track of the minimum accumulated cost. */
StateType m_State;
NodeLocationType m_Location; /** provides the location in the graph. */
Pointer m_PredecessorAddress; /** provides the best predecessor address */
Pointer m_AncestorAddress; /** provides the best predecessor address */
GraphSearchNode(const Self &); // purposely not implemented
void operator=(const Self &); // purposely not implemented
};
// Forward declaration of DijkstrasAlgorithm so it can be declared a friend
template <class TGraphSearchNode>
class DijkstrasAlgorithm;
template <class TGraphSearchNode>
class DijkstrasAlgorithmQueue : public itk::LightObject
/** \class DijkstrasAlgorithmQueue
the class containing the priority queue and associated data.
*/
{
private:
template <class G>
class GraphSearchNodePriority /* defines the comparison operator for the prioritiy queue */
{
public:
bool operator()( typename G::Pointer N1,
typename G::Pointer N2)
{
return N1->GetTotalCost() > N2->GetTotalCost();
}
};
public: /* Standard typedefs.*/
typedef DijkstrasAlgorithmQueue Self;
typedef LightObject Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
itkTypeMacro(DijkstrasAlgorithmQueue, LightObject);
itkNewMacro(Self); /** Method for creation through the object factory. */
typedef typename TGraphSearchNode::Pointer TGraphSearchNodePointer;
typedef typename TGraphSearchNode::PixelType PixelType; /** pixel type for the cost */
typedef typename TGraphSearchNode::CoordRep CoordRep; /** type for coordinates */
typedef typename std::priority_queue<typename TGraphSearchNode::Pointer,
std::vector<typename TGraphSearchNode::Pointer>,
GraphSearchNodePriority<TGraphSearchNode> > QType; /** the queue we are using */
typedef vector<typename TGraphSearchNode::Pointer> NodeListType;
inline QType GetQ()
{
return m_Q;
}
void AddToPath(TGraphSearchNodePointer G)
{
this->m_Path.push_back(G);
}
inline NodeListType GetPath()
{
return m_Path;
}
void EmptyPath()
{
m_Path.clear();
}
inline NodeListType GetSourceNodes()
{
return m_SourceNodes;
}
inline NodeListType GetSinkNodes()
{
return m_SinkNodes;
}
inline void IncrementTimer()
{
m_timer++;
}
inline long GetTimer()
{
return m_timer;
}
inline void EmptyQ()
{
while( !m_Q.empty() )
{
m_Q.pop();
}
m_timer = 0; m_SourceNodes.clear(); m_SinkNodes.clear();
}
NodeListType m_SinkNodes;
NodeListType m_SourceNodes;
QType m_Q;
NodeListType m_Path;
protected:
friend class DijkstrasAlgorithm<TGraphSearchNode>; // so it can access this data easily
DijkstrasAlgorithmQueue()
{
m_timer = 0;
}
~DijkstrasAlgorithmQueue()
{
}
private:
unsigned long m_timer;
DijkstrasAlgorithmQueue(const Self &); // purposely not implemented
void operator=(const Self &); // purposely not implemented
};
/**
* \class DijkstrasAlgorithm
* \brief General shortest path / greedy dynamic programming solver.
*
* This class uses Dijkstra's algorithm to solve the shortest path problem.
* We use the stl priority queue which is not optimal for this problem, but which
* works o.k. It's implemented to be used for general regularly connected
* graphs with fixed costs, or for the variational solution of an integral
* curve matching energy.
* Note: we assume all edge weights are positive.
* The class is implemented as a an abstract base class, with virtual functions for
* LocalCost, SearchEdgeSet and FindPath. LocalCost must be implemented by derived classes.
* The connectivity of the graph defined
* here is always regular and is controlled by a set of neighborhood indices.
* the default is a radius 1 neighborhood with all entries used. However, the
* user may also supply her own regular connectivity by selecting the size of
* the neighborhood and a subset of the indices which define the edges. If
* the GraphSearchNode contains its edges, they may be used with minor modification
* to the function SearchEdgeSet.
* Another improvement would be to make the LocalCost function a pointer
* to a function which could be set.
*/
template <class TGraphSearchNode>
class DijkstrasAlgorithm : public itk::LightObject
{
public:
typedef DijkstrasAlgorithm Self;
typedef LightObject Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
itkTypeMacro(DijkstrasAlgorithm, LightObject);
itkNewMacro(Self);
// Computation Data
typedef TGraphSearchNode SearchNode; /** dimension of the graph */
typedef typename SearchNode::Pointer SearchNodePointer;
enum { GraphDimension = SearchNode::GraphDimension }; /** dimension of the graph */
typedef typename SearchNode::PixelType PixelType; /** pixel type for the cost */
typedef typename SearchNode::CoordRep CoordRep; /** coordinate type */
typedef Image<SearchNodePointer, GraphDimension> GraphType;
typedef typename GraphType::SizeType GraphSizeType;
typedef ImageRegionIteratorWithIndex<GraphType> GraphIteratorType;
typedef typename GraphType::RegionType GraphRegionType;
typedef typename DijkstrasAlgorithmQueue<TGraphSearchNode>::Pointer QType;
typedef typename DijkstrasAlgorithmQueue<TGraphSearchNode>::NodeListType
NodeListType;
typedef itk::NeighborhoodIterator<GraphType>
GraphNeighborhoodIteratorType;
typedef typename GraphNeighborhoodIteratorType::IndexType
GraphNeighborhoodIndexType;
typedef typename GraphNeighborhoodIteratorType::RadiusType
RadiusType;
typedef typename TGraphSearchNode::NodeLocationType NodeLocationType;
typedef typename GraphType::IndexType IndexType;
// FUNCTIONS
void InitializeGraph(); /** initializes all graph values appropriately */
void InitializeQueue(); /** initializes all queue values appropriately
call AFTER source and sink are set*/
void InitializeEdgeTemplate(); /** helper function initializes edge set appropriately */
void InitializeEdgeTemplate(vector<unsigned int>, unsigned int); /** user supplied edge template */
void SetGraphSize(typename GraphType::SizeType Sz); /** the rectangular size of the graph */
inline void EmptyQ()
{
m_QS->EmptyQ(); this->m_TotalCost = 0;
}
/* adds a source to the source set */
void SetSource(typename TGraphSearchNode::Pointer G)
{
m_QS->m_SourceNodes.push_back(G);
for( int i = 0; i < GraphDimension; i++ )
{
m_GraphIndex[i] = (long int)(G->GetLocation()[i] + 0.5);
// ::std::cout << " mgi " << m_GraphIndex[i];
}
m_Graph->SetPixel(m_GraphIndex, G);
};
typename TGraphSearchNode::Pointer GetGraphNode( IndexType index)
{
// ::std::cout << " get node " << index << std::endl;
return m_Graph->GetPixel(index);
};
// adds a sink to the sink set
void SetSink(typename TGraphSearchNode::Pointer G)
{
m_QS->m_SinkNodes.push_back(G);
}
// Backtracks from the given node to its source node;
void BackTrack(typename TGraphSearchNode::Pointer SinkNode)
{
m_QS->m_Path.clear();
typename TGraphSearchNode::Pointer G = SinkNode;
typename TGraphSearchNode::Pointer P = SinkNode->GetPredecessor();
if( !P || !G )
{
return;
}
float highcost = G->GetValue();
if( G->GetTotalCost() > P->GetValue() )
{
P->SetAncestor(G);
P->SetValue(G->GetTotalCost() );
highcost = G->GetTotalCost();
}
while( P && G != P )
{
m_QS->m_Path.push_back(G);
G = P;
P = G->GetPredecessor();
if( P->GetValue() < highcost )
{
P->SetValue(highcost);
P->SetAncestor(G);
}
}
if( !P )
{
cout << " null pred "; // else cout << " pred == self \n";
}
return;
}
// Inverse of backtrack - from the given node to its sink node;
void ForwardTrack(typename TGraphSearchNode::Pointer SinkNode)
{
typename TGraphSearchNode::Pointer G = SinkNode;
typename TGraphSearchNode::Pointer P = SinkNode->GetAncestor();
while( P && G != P && G )
{
if( P->GetValue() > G->GetValue() )
{
G->SetValue(P->GetValue() );
}
if( G->GetValue() > P->GetValue() )
{
P->SetValue(G->GetValue() );
}
G = P;
P = G->GetAncestor();
}
return;
}
virtual bool TerminationCondition(); /** decides when the algorithm stops */
virtual void SearchEdgeSet(); /** loops over the neighbors in the graph */
void CheckNodeStatus(); /** checks if the node has been explored already, its cost, etc. */
virtual PixelType LocalCost(); /* computes the local cost */
/* alternatively, we could pass the function as a template parameter
or set a function pointer. the latter method is used in dijkstrasegment. */
virtual void FindPath(); /* runs the algorithm */
inline unsigned int GetPathSize()
{
return m_QS->m_Path.size();
}
inline typename TGraphSearchNode::Pointer GetPathAtIndex(unsigned int i)
{
return m_QS->m_Path[i];
}
inline typename TGraphSearchNode::Pointer GetNeighborNode()
{
return m_NeighborNode;
}
inline typename TGraphSearchNode::Pointer GetCurrentNode()
{
return m_CurrentNode;
}
void SetMaxCost(PixelType m)
{
m_MaxCost = m;
}
double GetTotalCost()
{
return m_TotalCost;
}
void SetSearchFinished(bool m)
{
m_SearchFinished = m;
}
/** sets the boolean that indicates if the algorithm is done */
protected:
QType m_QS;
vector<unsigned int> m_EdgeTemplate; /** defines neighborhood connectivity */
RadiusType m_Radius; /** used by the neighborhood iterator */
typename TGraphSearchNode::Pointer m_PredecessorNode; /** holds the predecessor node */
typename TGraphSearchNode::Pointer m_CurrentNode; /** holds the current node */
typename TGraphSearchNode::Pointer m_NeighborNode; /** holds the current neighbor node */
typename GraphType::Pointer m_Graph; /** holds all the graph information */
GraphRegionType m_GraphRegion;
GraphSizeType m_GraphSize; /** rectangular size of graph */
typename GraphType::IndexType m_GraphIndex;
bool m_SearchFinished;
PixelType m_NewCost;
PixelType m_CurrentCost;
PixelType m_MaxCost; // This creates an insurmountable barrier unless all costs are max
double m_TotalCost;
unsigned long m_NumberSearched;
DijkstrasAlgorithm();
~DijkstrasAlgorithm()
{
};
private:
DijkstrasAlgorithm(const Self &); // purposely not implemented
void operator=(const Self &); // purposely not implemented
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkDijkstrasAlgorithm.cxx"
#endif
#endif
|