]> Creatis software - FrontAlgorithms.git/blob - appli/TempAirwaysAppli/TempAirwaysAppli.cxx
...
[FrontAlgorithms.git] / appli / TempAirwaysAppli / TempAirwaysAppli.cxx
1 #include <iostream>
2 #include <cstdlib>
3 #include <sstream>
4
5 #include <boost/filesystem.hpp>
6 #include <boost/program_options.hpp>
7
8 #include "vec3.h"
9 #include "airwaysTree.h"
10
11 #include <cpPlugins/Interface.h>
12 #include <cpPlugins/Workspace.h>
13
14 using namespace airways;
15 namespace po = boost::program_options;
16
17 namespace
18 {
19   const size_t ERROR_IN_COMMAND_LINE = 1;
20   const size_t SUCCESS = 0;
21   const size_t ERROR_UNHANDLED_EXCEPTION = 2;
22 } // namespace
23
24 typedef std::vector< AirwaysTree > AirwaysVector;
25
26 #include <itkCastImageFilter.h>
27
28 // Auxiliar struct to save info for execution.
29 typedef void* TImagePointer;
30 struct TreeInfo{
31
32   TreeInfo( )
33     {
34       this->myWorkspace = new cpPlugins::Workspace( );
35     }
36   ~TreeInfo( )
37     {
38       /*
39         if( this->IsMyWorkspace )
40         delete this->myWorkspace;
41       */
42     }
43
44   void CastImage( )
45     {
46       auto image = this->myWorkspace->GetFilter( "reader" )->GetOutputData( "Output" )->GetITK< itk::Image< unsigned char, 3 > >( );
47       typedef itk::CastImageFilter< itk::Image< unsigned char, 3 >, TInputImage > _TCast;
48       _TCast::Pointer cast = _TCast::New( );
49       cast->SetInput( image );
50       cast->Update( );
51       this->Image = cast->GetOutput( );
52       this->Image->DisconnectPipeline( );
53     }
54
55   TInputImage::Pointer Image;
56   cpPlugins::Workspace* myWorkspace;
57   bool IsMyWorkspace;
58   Vec3 seed;
59   std::string folderpath_pigResults;
60   std::string pig_name;
61   std::string image_name;
62
63 };
64 // Constants
65 unsigned char red[3]   = { 255, 0, 0 };
66 unsigned char green[3] = { 0, 255, 0 };
67 unsigned char blue[3]  = { 0, 0, 255 };
68 unsigned char yellow[3]= { 255, 255, 0 };
69 unsigned char purple[3]= { 255, 0, 255 };
70 unsigned char cyan[3]= { 0, 255, 255 };
71
72 cpPlugins::Interface myPlugins;
73
74 // -------------------------------------------------------------------------
75 void Load_cpPlugins( const std::string& plugins );
76 void CreateResultDirectory(AirwaysTree tree);
77 void DrawVTKLinesFromTree(AirwaysTree& tree, const std::string filename, bool common);
78 AirwaysTree& CreateAirwaysTreeFromSegmentation(Vec3 seed, TInputImage* input_image, cpPlugins::Workspace& ws );
79 vector<TreeInfo> ReadInputFile(const char* filename);
80 void printCommonTreeBetweenTwoTrees(AirwaysTree tree_A, AirwaysTree tree_B, std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B, unsigned int Q, unsigned int F);
81 void printMatchingResultToFile(AirwaysTree tree_A, AirwaysTree tree_B, std::map< unsigned int, std::vector<Node*> > map_A_to_B, std::map< unsigned int, std::vector<Node*> > map_B_to_A, unsigned int Q, unsigned int F);
82 void createLinesAndPointsForVTK(const Node* node, vtkSmartPointer<vtkPoints>& pts,vtkSmartPointer<vtkCellArray>& lines, vtkSmartPointer<vtkUnsignedCharArray>& colors, bool common, bool isRoot);
83
84 // -------------------------------------------------------------------------
85 int main( int argc, char* argv[] )
86 {
87   Load_cpPlugins( "./plugins.cfg" );
88
89   try
90   {
91     // Define and parse the program options
92     po::options_description desc("Options");
93     desc.add_options()("use_file", po::value<std::string>(), "Adds the filepath containing the file to be used in creaAirwaysTree -- Mandatory")
94       ("build_trees","Creates trees from a given filepath (arg) and stores it in a .vtk file")
95       ("subtree_levels", po::value<int>(),"Get a subtree(s) by levels - result: a vtk and reconstructed img .mhd")
96       ("subtree_length", po::value<float>(),"Get a subtree(s) by length - result: a vtk and reconstructed img .mhd")
97       ("subtree_diameter", po::value<float>(),"Get a subtree(s) by diameter - result: a vtk and reconstructed img .mhd")
98       ("compare_trees", "Compare the trees given in the input file or the subtrees using an option - result: a vtk and reconstructed img .mhd");
99     //TODO: Fix image segmentation. ("segment_images",  "Creates a binary image corresponding to the segmentation of of a given original image (arg) and seed (arg), saves it to a .mhd file and uses it for subsequent operations")
100     po::variables_map vm;
101     try
102     {
103       std::string fileName;
104       vector<TreeInfo> treeInfoVector;
105       AirwaysVector aVector;
106       TImagePointer segmentationImage;
107       Vec3 seed;
108       po::store(po::parse_command_line(argc, argv, desc), vm); // can throw
109       if (vm.count("use_file"))
110       {
111         fileName = vm["use_file"].as<std::string>();
112         treeInfoVector = ReadInputFile(fileName.c_str());
113       }
114
115       if(vm.count("segment_images"))
116       {
117       }
118
119       // Build trees option
120       if (vm.count("build_trees"))
121       {
122         for(unsigned int i = 0; i < treeInfoVector.size(); ++ i){
123           TreeInfo info = treeInfoVector[i];
124           try
125           {
126             info.myWorkspace->Execute( "eb" );
127           }
128           catch( itk::ExceptionObject& err )
129           {
130             std::cerr << "Error: " << err << std::endl;
131             std::exit( 1 );
132
133           } // fi
134           info.CastImage( );
135           AirwaysTree tree = CreateAirwaysTreeFromSegmentation( info.seed, info.Image, *(info.myWorkspace ));
136           tree.SetResultPath(info.folderpath_pigResults);
137           tree.SetImageName(info.image_name);
138           aVector.push_back(tree);
139         }
140         for (unsigned int i = 0; i < aVector.size(); ++i)
141         {
142           CreateResultDirectory(aVector[i]);
143           std::string fullPath = aVector[i].GetResultPath() + "/" + aVector[i].GetImageName() + ".vtk";
144           DrawVTKLinesFromTree(aVector[i], fullPath, false);
145
146         } //for
147       } //if
148
149       // Subtree levels option
150       if (vm.count("subtree_levels"))
151       {
152       } //if
153       else if (vm.count("subtree_length"))
154       {
155       } //if
156       else if (vm.count("subtree_diameter"))
157       {
158       } //if
159
160       if (vm.count("compare_trees"))
161       {
162         std::cout << "Option: Compare trees" << std::endl;
163         /**
164          * this piece of code only test in the case of two trees, so it can be replaced
165          * to a code which does a cascade
166          */
167
168         //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
169         //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
170         //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
171         //CODIGO DE COMPARACIÓN DE ARBOLES
172         //std::cout << "Comparing trees ..." << std::endl;
173         //aVector[0].CompareTrees(aVector[1]);
174         //std::cout << "Comparing trees ... OK" << std::endl;
175
176         std::cout << "Tree A ... " << std::endl;
177         //aVector[0].printNodeAndChildrenIds();
178         std::cout << "Tree A ... OK" << std::endl;
179
180         std::cout << "Tree B ... " << std::endl;
181         //aVector[1].printNodeAndChildrenIds();
182         std::cout << "Tree B ... OK" << std::endl;
183
184         std::cout << "Comparing trees Orkisz-Morales..." << std::endl;
185         // Vectors to save the common and uncommon nodes
186         vec_nodes commonA;
187         vec_nodes commonB;
188         vec_nodes nonCommonA;
189         vec_nodes nonCommonB;
190         std::map< unsigned int, std::vector<Node*> > map_A_to_B;
191         std::map< unsigned int, std::vector<Node*> > map_B_to_A;
192         std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B;
193
194         // Input parameter for comparison
195         unsigned int Q = 1; // Corresponds to the depth to select "fathers" nodes
196         unsigned int F = 1; // Correspond to the depth to select "family" nodes
197         std::cout << "Q = " << Q << std::endl;
198         std::cout << "F = " << F << std::endl;
199
200         clock_t before_compare = clock();
201         aVector[0].CompareTreesOrkiszMorales(aVector[1], Q, F, commonA, commonB, nonCommonA, nonCommonB, map_A_to_B, map_B_to_A, vector_pair_edges_A_to_B);
202         clock_t after_compare = clock();
203         double compare_time = double(after_compare - before_compare) / CLOCKS_PER_SEC;
204         std::cout << "Matching time: " << compare_time << std::endl;
205
206         // Print the common tree with common edges
207         printCommonTreeBetweenTwoTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
208         printMatchingResultToFile(aVector[0], aVector[1], map_A_to_B, map_B_to_A, Q, F);
209         //printSeparatedCommonTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
210         //reconstructAndSaveCommonTrees(aVector[0], aVector[1], vector_pair_edges_A_to_B, Q, F);
211
212         // Print all the maps that have more that two connections
213         std::cout << "Printing multiple relation A to B. Total relations: " << map_A_to_B.size() << std::endl;
214         for(std::map< unsigned int, std::vector<Node*> >::iterator it_map_A_to_B = map_A_to_B.begin(); it_map_A_to_B != map_A_to_B.end(); ++it_map_A_to_B)
215         {
216           if((*it_map_A_to_B).second.size() > 1)
217           {
218             std::cout << "Multiple relation A to B with size:" << (*it_map_A_to_B).second.size() << ", from Id:" << (*it_map_A_to_B).first << std::endl;
219             for(std::vector<Node*>::iterator it_node = (*it_map_A_to_B).second.begin(); it_node != (*it_map_A_to_B).second.end(); ++it_node)
220             {
221               std::cout << "Id: " << (*it_node)->GetId() << std::endl;
222             }
223           }
224         }
225         std::cout << "Printing multiple relation A to B ... OK" << std::endl;
226
227         std::cout << "Printing multiple relation B to A. Total relations: " << map_B_to_A.size() << std::endl;
228         for(std::map< unsigned int, std::vector<Node*> >::iterator it_map_B_to_A = map_B_to_A.begin(); it_map_B_to_A != map_B_to_A.end(); ++it_map_B_to_A)
229         {
230           if((*it_map_B_to_A).second.size() > 1)
231           {
232             std::cout << "Multiple relation B to A with size:" << (*it_map_B_to_A).second.size() << ", from Id:" << (*it_map_B_to_A).first << std::endl;
233             for(std::vector<Node*>::iterator it_node = (*it_map_B_to_A).second.begin(); it_node != (*it_map_B_to_A).second.end(); ++it_node)
234             {
235               std::cout << "Id: " << (*it_node)->GetId() << std::endl;
236             }
237           }
238         }
239         std::cout << "Printing multiple relation B to A  ... OK" << std::endl;
240
241         // Mark only the common nodes
242         aVector[0].UnMarkAll();
243         aVector[1].UnMarkAll();
244
245         // --------------------------------------
246         // ------ Get common paths marked -------
247         // --------------------------------------
248
249         /*
250           std::string path_folder = "/run/media/alfredo/Data/Pulmones/results/airwaysGraphs/comparisonResutls/probes/";
251           std::string suffix_vtk = ".vtk";
252           std::string name_tree = "TreeA_dP2P";
253           int iteration = 1;
254           for(vec_nodes::iterator it_A = commonA.begin(); it_A != commonA.end(); ++it_A)
255           {
256           aVector[0].MarkPathFromNodeToNode(aVector[0].GetRoot(), (*it_A));
257
258           std::stringstream filepath_actualIteration;
259           filepath_actualIteration << path_folder << name_tree << "__" << iteration << "_idA_" << (*it_A)->GetId() << suffix_vtk;
260
261           DrawVTKLinesFromTree(aVector[0], filepath_actualIteration.str(), true);
262           ++iteration;
263           }
264
265           iteration = 1;
266           name_tree = "TreeB_dP2P";
267           for(vec_nodes::iterator it_B = commonB.begin(); it_B != commonB.end(); ++it_B)
268           {
269           aVector[1].MarkPathFromNodeToNode(aVector[1].GetRoot(), (*it_B));
270
271           std::stringstream filepath_actualIteration;
272           filepath_actualIteration << path_folder << name_tree << "__" << iteration << "_idB_" << (*it_B)->GetId() << suffix_vtk;
273
274           DrawVTKLinesFromTree(aVector[1], filepath_actualIteration.str(), true);
275           ++iteration;
276           }
277         */
278
279         // --------------------------------------
280         // --------------------------------------
281
282         /*
283         //XXXXXXXXXXXXXXXXXXXXXXXXXXXX
284         //1. PRINT EACH NODE OF EACH TREE AND SAVE IT USING AS NAME ITS ID
285
286         // Tree A
287         for(int i = 2; i < aVector[0].GetWeight(); ++i)
288         {
289         //std::cout << "Writing idA: " << i << std::endl;
290         AirwaysTree* tree_id = aVector[0].GetSingleDetachedTreeNodeById(i);
291         //std::cout << "Got id: " << i << ", numberOfNodes: " << tree_id->GetWeight() <<  std::endl;
292         if(tree_id)
293         {
294         std::stringstream filepath_actualIteration;
295         filepath_actualIteration << aVector[0].GetResultPath() << "/" << aVector[0].GetImageName() << "_id_" << i << suffix_vtk;
296         DrawVTKLinesFromTree(*tree_id, filepath_actualIteration.str(), false);
297         delete(tree_id);
298         }
299         else
300         std::cout << "Tree NULL" << std::endl;
301         }
302
303         // Tree B
304         for(int i = 2; i < aVector[1].GetWeight(); ++i)
305         {
306         //std::cout << "Writing idA: " << i << std::endl;
307         AirwaysTree* tree_id = aVector[1].GetSingleDetachedTreeNodeById(i);
308         //std::cout << "Got id: " << i << ", numberOfNodes: " << tree_id->GetWeight() <<  std::endl;
309         if(tree_id)
310         {
311         std::stringstream filepath_actualIteration;
312         filepath_actualIteration << aVector[1].GetResultPath() << "/" << aVector[1].GetImageName() << "_id_" << i << suffix_vtk;
313         DrawVTKLinesFromTree(*tree_id, filepath_actualIteration.str(), false);
314         delete(tree_id);
315         }
316         else
317         std::cout << "Tree NULL" << std::endl;
318         }
319
320         std::cout << "Comparing trees Orkisz-Morales... OK" << std::endl;
321
322         */
323
324         //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
325         //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
326         //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
327
328         /*// AMP
329           aVector[0].SubIsomorphism(aVector[1]);
330
331           std::cout << "Flag after SubIsomorphism" << std::endl;
332           std::string fullPathA = aVector[0].GetResultPath() + "/" + aVector[0].GetImageName() + "_CMP.vtk";
333           std::string fullPathB = aVector[1].GetResultPath() + "/" + aVector[1].GetImageName() + "_CMP.vtk";
334           DrawVTKLinesFromTree(aVector[0], fullPathA, true);
335           DrawVTKLinesFromTree(aVector[1], fullPathB, true);
336
337           std::cout << "Flag after write vtk" << std::endl;
338           TInputImage::Pointer imgA, imgB;
339           aVector[0].ImageReconstruction(imgA);
340           std::cout << "Flag after Reconstruction A" << std::endl;
341
342           aVector[1].ImageReconstruction(imgB);
343           std::cout << "Flag after Reconstruction B" << std::endl;
344
345           std::string fullPathA_mhd = aVector[0].GetResultPath() + "/" + aVector[0].GetImageName() + "_CMP.vtk";
346           std::string fullPathB_mhd = aVector[1].GetResultPath() + "/" + aVector[1].GetImageName() + "_CMP.vtk";
347           WriteImage(imgA, fullPathA_mhd);
348           WriteImage(imgB, fullPathB_mhd);
349
350           //AMP*/
351       }
352       po::notify(vm); // throws on error, so do after help in case
353     }
354     catch (std::exception& e)
355     {
356       std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl;
357       return ERROR_UNHANDLED_EXCEPTION;
358     } // yrt
359   }
360   catch (std::exception& e)
361   {
362     std::cerr << "Unhandled Exception reached the top of main: " << e.what() << ", application will now exit" << std::endl;
363     return ERROR_UNHANDLED_EXCEPTION;
364   } // yrt
365   return( 0 );
366 }
367
368 // -------------------------------------------------------------------------
369 void Load_cpPlugins( const std::string& plugins )
370 {
371   myPlugins.LoadConfiguration( plugins );
372 }
373
374 // -------------------------------------------------------------------------
375 void CreateResultDirectory(AirwaysTree tree)
376 {
377   boost::filesystem::path dir(tree.GetResultPath());
378   if (boost::filesystem::create_directories(dir))
379   {
380     std::cout << "FolderName = " << tree.GetResultPath() << " has been created" << std::endl;
381   } //if
382   else
383     std::cout << "FolderName = " << tree.GetResultPath() << " already exists" << std::endl;
384 }
385
386 // -------------------------------------------------------------------------
387 void DrawVTKLinesFromTree(AirwaysTree& tree, const std::string filepath, bool common)
388 {
389   // Create the array of points, lines, and colors
390   vtkSmartPointer<vtkPoints> pts = vtkSmartPointer<vtkPoints>::New();
391   vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
392   vtkSmartPointer<vtkUnsignedCharArray> colors = vtkSmartPointer<vtkUnsignedCharArray>::New();
393   colors->SetNumberOfComponents(3);
394   colors->SetName("Colors");
395
396   //vtk sphere for sources
397   //vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
398   //Vec3 root = tree.GetRoot()->GetCoords();
399   //sphereSource->SetCenter(root[0], root[1], root[2]);
400   //sphereSource->SetRadius(1);
401   //UndirectedGraph
402
403   srand(time(NULL));
404   unsigned int id = 1;
405
406   // Create and fill the points, lines, and color vectors
407   //CalculateVTKLinesFromEdges(tree.GetRoot(), 0, id, pts, lines, colors, common);
408   pts->SetNumberOfPoints(tree.GetWeight()+1);
409   createLinesAndPointsForVTK(tree.GetRoot(), pts, lines, colors, common, true);
410
411   // Create the polydata
412   vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
413
414   // Set the points, lines, and colors
415   linesPolyData->SetPoints(pts);
416   linesPolyData->SetLines(lines);
417   linesPolyData->GetCellData()->SetScalars(colors);
418
419   // Write the file
420   vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
421   writer->SetFileName(filepath.c_str());
422
423 #if VTK_MAJOR_VERSION <= 5
424   writer->SetInput(linesPolyData);
425 #else
426   writer->SetInputData(linesPolyData);
427 #endif
428   writer->Write();
429
430   //The following code is to test the vtk polydata and visualize it
431   /*    // Visualize
432         vtkSmartPointer<vtkPolyDataMapper> mapper =
433         vtkSmartPointer<vtkPolyDataMapper>::New();
434         #if VTK_MAJOR_VERSION <= 5
435         mapper->SetInput(linesPolyData);
436         #else
437         mapper->SetInputData(linesPolyData);
438         #endif
439         vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
440         actor->SetMapper(mapper);
441
442         //sphere
443         vtkSmartPointer<vtkPolyDataMapper> mapperSphere = vtkSmartPointer<
444         vtkPolyDataMapper>::New();
445         mapperSphere->SetInputConnection(sphereSource->GetOutputPort());
446
447         vtkSmartPointer<vtkActor> actorSphere = vtkSmartPointer<vtkActor>::New();
448         actorSphere->SetMapper(mapperSphere);
449         //end sphere
450
451         vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
452         vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<
453         vtkRenderWindow>::New();
454         renderWindow->AddRenderer(renderer);
455         vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
456         vtkSmartPointer<vtkRenderWindowInteractor>::New();
457         renderWindowInteractor->SetRenderWindow(renderWindow);
458         renderer->AddActor(actorSphere);
459         renderer->AddActor(actor);
460
461         renderWindow->Render();
462         renderWindowInteractor->Start();*/
463 }
464
465 // -------------------------------------------------------------------------
466 #include <fpa/Base/ImageSkeleton.h>
467 #include <fpa/Image/MinimumSpanningTree.h>
468 #include <cpExtensions/DataStructures/ImageIndexesContainer.h>
469 #include <itkImage.h>
470 #include <queue>
471
472 template< class TImage, class TVertex >
473 Node* FAVertexToNode( TVertex vertex, TImage* image )
474 {
475   //The FrontAlgorithms Vertex is an TImageType::IndexType
476   typename TImage::PointType point;
477   image->TransformIndexToPhysicalPoint( vertex, point );
478   Vec3 alfPoint(point[0],point[1],point[2]);
479   return new Node(alfPoint);
480 }
481
482 AirwaysTree& ConvertFilterToAirwaysTree( TInputImage* input_image, cpPlugins::Workspace& ws )
483 {
484   typedef
485     fpa::Base::ImageSkeleton< fpa::Image::MinimumSpanningTree< 3 > >
486     TFASkeleton;
487   typedef TFASkeleton::TVertex    TVertexFA;
488   typedef TFASkeleton::TVertexCmp TVertexCompareFA;
489   typedef cpExtensions::DataStructures::ImageIndexesContainer< 3 > TVerticesFA;
490
491   typedef Node TVertexAirways;
492   typedef Edge TEdgeAirways;
493   typedef pair_posVox_rad TSkelePoint;
494   typedef vec_pair_posVox_rad TSkelePoints;
495   typedef std::map< TVertexFA, TVertexAirways*, TVertexCompareFA > VertexMap;
496   VertexMap vertexMap;
497   std::time_t start,end;
498   std::time(&start);
499   std::cout << "Starting conversion " << std::endl;
500
501   auto w_filter = ws.GetFilter( "eb" );
502   auto distance_map =
503     ws.GetFilter( "dmap" )->GetOutputData( "Output" )->
504     GetITK< itk::Image< float, 3 > >( );
505   auto sk =
506     w_filter->GetOutputData( "Skeleton" )->GetITK< TFASkeleton >( );
507   const auto& branches = sk->Get( );
508   auto seed0 =
509     ws.GetFilter( "seed" )->GetOutputData( "Output" )->
510     GetITK< TVerticesFA >( )->Get( )[ 0 ];
511
512   std::queue< TVertexFA > q;
513   // TODO: std::set< TVertexFA, TVertexCompareFA > marks;
514   q.push( seed0 );
515   while( !q.empty( ) )
516   {
517     auto sVertex = q.front( );
518     q.pop( );
519     auto sIt = branches.find( sVertex );
520     /* TODO
521        if( marks.find( sVertex ) != marks.end( ) )
522        {
523        std::cout << "MARK!!!!! : " << sVertex << std::endl;
524        }
525        marks.insert( sVertex );
526     */
527
528     // End node... do nothing
529     if( sIt == branches.end( ) )
530       continue;
531
532     // Create source node
533     auto srcIt = vertexMap.find( sVertex );
534     if( srcIt == vertexMap.end( ) )
535       srcIt = vertexMap.insert(
536         VertexMap::value_type(
537           sVertex, FAVertexToNode( sVertex, input_image )
538           )
539         ).first;
540
541     // TODO: std::cout << sVertex << " " << " " << sLevel << " " << seed0 << std::endl;
542     // Create destination nodes
543     for( auto eIt = sIt->second.begin( ); eIt != sIt->second.end( ); ++eIt )
544     {
545       auto dstIt = vertexMap.find( eIt->first );
546       if( dstIt == vertexMap.end( ) )
547         dstIt = vertexMap.insert(
548           VertexMap::value_type(
549             eIt->first, FAVertexToNode( eIt->first, input_image )
550             )
551           ).first;
552
553       // Connect in the acyclic graph
554       dstIt->second->SetFather( srcIt->second );
555       srcIt->second->AddChild( dstIt->second );
556
557       // Create detailed edge
558       TEdgeAirways* edge = new Edge( );
559       edge->SetSource( srcIt->second );
560       edge->SetTarget( dstIt->second );
561       auto path = eIt->second->GetVertexList( );
562       for( unsigned int pIt = 0; pIt < path->Size( ); ++pIt )
563       {
564         itk::ImageBase< 3 >::PointType pnt;
565         auto cidx = path->GetElement( pIt );
566         input_image->TransformContinuousIndexToPhysicalPoint( cidx, pnt );
567         TVertexFA idx;
568         input_image->TransformPhysicalPointToIndex( pnt, idx );
569         Vec3 coords = FAVertexToNode( idx, input_image )->GetCoords( );
570         pair_posVox_rad skPair( coords, distance_map->GetPixel( idx ) );
571         edge->AddSkeletonPairInfo( skPair );
572
573       } // rof
574
575       // Finish association
576       dstIt->second->SetEdge( edge );
577
578       // Put it as next candidate
579       q.push( eIt->first );
580
581     } // rof
582
583   } // elihw
584
585   AirwaysTree* tree =
586     new AirwaysTree( input_image, NULL, vertexMap[ seed0 ], false );
587   std::time(&end);
588   std::cout << "Finished conversion. New AlfTree has weight: "<<tree->GetWeight()<<". Takes "<<(end-start)<<" s." << std::endl;
589   return *tree;
590 }
591
592 // -------------------------------------------------------------------------
593 AirwaysTree& CreateAirwaysTreeFromSegmentation(Vec3 seed, TInputImage* input_image, cpPlugins::Workspace& ws )
594 {
595   return( ConvertFilterToAirwaysTree( input_image, ws ) );
596 }
597
598 // -------------------------------------------------------------------------
599 vector<TreeInfo> ReadInputFile(const char* filename)
600 {
601   // Variables
602   std::ifstream infile(filename);
603   std::string line;
604   std::string folderpath_allResults;
605   vector<TreeInfo> vectorInfo;
606   // Parse the file
607   bool firstLine = false;
608
609   while (std::getline(infile, line))
610   {
611     // First line contains the output folder
612     std::istringstream iss(line);
613     if (!firstLine)
614     {
615       if (!(iss >> folderpath_allResults))
616       {
617         std::cout << "no file" << std::endl;
618         return vectorInfo;
619       } //if
620       firstLine = true;
621     } //if
622     // Other lines, not the first one, contain the information for the airways to be created
623     else
624     {
625       TreeInfo treeInfo;
626       float point_trachea[3];
627       std::string filepath_airwayImage, name_pig, name_image;
628       if (!(iss >> point_trachea[0] >> point_trachea[1] >> point_trachea[2] >> filepath_airwayImage >> name_pig >> name_image))
629       {
630         std::cout << "There is no tree information in the file." << std::endl;
631         break;
632       } //if
633       else
634       {
635         // Print information
636         std::cout << "Point trachea:[" << point_trachea[0] << "," << point_trachea[1] << "," << point_trachea[2] << "]" << std::endl;
637       }
638
639       //Save info.
640
641       //Save seed info.
642       Vec3 seed(point_trachea[0], point_trachea[1], point_trachea[2]); //real coords seed
643       treeInfo.seed = seed;
644       // Create the outputs
645       treeInfo.folderpath_pigResults = folderpath_allResults + "/" + name_pig + "/";
646       treeInfo.pig_name = name_pig;
647       treeInfo.image_name = name_image;
648       // Read the image
649       /*
650         treeInfo.image = ReadImage<TInputImage>(filepath_airwayImage);
651       */
652       // Execute first pipeline's part
653       std::stringstream seed_stream;
654       seed_stream
655         << point_trachea[0] << " "
656         << point_trachea[1] << " "
657         << point_trachea[2];
658
659       treeInfo.myWorkspace->SetInterface( &myPlugins );
660       std::string err = treeInfo.myWorkspace->LoadWorkspace( "./workspace_airwaysappli.wxml" );
661       if( err != "" )
662       {
663         std::cerr << "Error: " << err << std::endl;
664         std::exit( 1 );
665
666       } // fi
667       treeInfo.myWorkspace->SetParameter( "FileNames@reader", filepath_airwayImage );
668       treeInfo.myWorkspace->SetParameter( "Text@seed", seed_stream.str( ) );
669       vectorInfo.push_back(treeInfo);
670
671     } //else
672   } //while
673   return vectorInfo;
674 }
675
676 // -------------------------------------------------------------------------
677 void printCommonTreeBetweenTwoTrees(AirwaysTree tree_A, AirwaysTree tree_B, std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > > vector_pair_edges_A_to_B, unsigned int Q, unsigned int F)
678 {
679   std::cout << "printCommonTreeBetweenTwoTrees, edges:" << vector_pair_edges_A_to_B.size() << std::endl;
680
681   // Vtk points, cell array, and colors
682   vtkSmartPointer<vtkPoints> points_common = vtkSmartPointer<vtkPoints>::New();
683   vtkSmartPointer<vtkCellArray> lines_common = vtkSmartPointer<vtkCellArray>::New();
684   vtkSmartPointer<vtkUnsignedCharArray> colors_common = vtkSmartPointer<vtkUnsignedCharArray>::New();
685   colors_common->SetNumberOfComponents(3);
686   colors_common->SetName("Colors");
687
688   // Add all the points
689   // 0 - 1000 points for tree A and from 1001 for tree B
690   points_common->SetNumberOfPoints(1000 + tree_B.GetWeight() + 100);
691
692   // Add points for tree A
693   vec_nodes vector_nodesA = tree_A.GetNodes();
694   for(vec_nodes::iterator it_nodesA = vector_nodesA.begin(); it_nodesA != vector_nodesA.end(); ++it_nodesA)
695   {
696     points_common->SetPoint((*it_nodesA)->GetId(),(*it_nodesA)->GetCoords().GetVec3());
697   }
698
699   // Add points for tree B
700   vec_nodes vector_nodesB = tree_B.GetNodes();
701   for(vec_nodes::iterator it_nodesB = vector_nodesB.begin(); it_nodesB != vector_nodesB.end(); ++it_nodesB)
702   {
703     points_common->SetPoint((*it_nodesB)->GetId()+1000,(*it_nodesB)->GetCoords().GetVec3());
704   }
705
706   // Add the edges for both trees
707   std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
708   int number_pairs = 0;
709   for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
710   {
711     std::cout << "Pair:" << number_pairs << std::endl;
712     std::pair<Node*, Node*> edge_A = (*it_edges).first;
713     std::pair<Node*, Node*> edge_B = (*it_edges).second;
714
715     vec_nodes path_A;
716     edge_A.first->GetPathToNode(edge_A.second, path_A);
717
718     vec_nodes path_B;
719     edge_B.first->GetPathToNode(edge_B.second, path_B);
720
721     // Set color to be used
722     int numColor = number_pairs % 6;
723     unsigned char color[3];
724     color[0] = green[0];
725     color[1] = green[1];
726     color[2] = green[2];
727     if(numColor == 1)
728     {
729       color[0] = red[0];
730       color[1] = red[1];
731       color[2] = red[2];
732     }
733     else if(numColor == 2)
734     {
735       color[0] = blue[0];
736       color[1] = blue[1];
737       color[2] = blue[2];
738     }
739     else if(numColor == 3)
740     {
741       color[0] = yellow[0];
742       color[1] = yellow[1];
743       color[2] = yellow[2];
744     }
745     else if(numColor == 4)
746     {
747       color[0] = purple[0];
748       color[1] = purple[1];
749       color[2] = purple[2];
750     }
751     else if(numColor == 5)
752     {
753       color[0] = cyan[0];
754       color[1] = cyan[1];
755       color[2] = cyan[2];
756     }
757
758     number_pairs++;
759
760     // Trace line A
761     //if(path_A.size() > 0 && number_pairs < 50)
762     if( path_A.size() )
763     {
764       vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
765       lines_common->InsertNextCell(path_A.size());
766       int id_point = 0;
767       for(vec_nodes::iterator it_pathA = path_A.begin(); it_pathA != path_A.end(); ++it_pathA)
768       {
769         lines_common->InsertCellPoint((*it_pathA)->GetId());
770         //line->GetPointIds()->SetId( id_point, (*it_pathA)->GetId() );
771         //id_point++;
772       }
773       //lines_common->InsertNextCell(line);
774       colors_common->InsertNextTupleValue(color);
775     }
776     else
777     {
778       std::cout << "No path A" << std::endl;
779     }
780
781
782     // Trace line B
783     //if(path_B.size() > 0 && number_pairs < 50)
784     if( path_B.size() )
785     {
786       vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
787       lines_common->InsertNextCell(path_B.size());
788       int id_point = 0;
789       for(vec_nodes::iterator it_pathB = path_B.begin(); it_pathB != path_B.end(); ++it_pathB)
790       {
791         lines_common->InsertCellPoint((*it_pathB)->GetId()+1000);
792         //line->GetPointIds()->SetId( id_point, (*it_pathB)->GetId()+1000 );
793         id_point++;
794       }
795       //lines_common->InsertNextCell(line);
796       colors_common->InsertNextTupleValue(color);
797     }
798     else
799     {
800       std::cout << "No path B" << std::endl;
801     }
802   }
803
804   // Save the polydata
805   // Create the polydata
806   vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New();
807
808   // Set the points, lines, and colors
809   linesPolyData->SetPoints(points_common);
810   linesPolyData->SetLines(lines_common);
811   linesPolyData->GetCellData()->SetScalars(colors_common);
812
813   // ------------------------------------------------
814   // Write the vtk file
815
816   // Create the pathfile to save
817   std::stringstream filepath_actualIteration;
818   filepath_actualIteration << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".vtk";
819   std::cout << "File to save:" << filepath_actualIteration.str() << std::endl;
820
821   // Create the writer
822   vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
823   writer->SetFileName(filepath_actualIteration.str().c_str());
824
825   // Set input and write
826 #if VTK_MAJOR_VERSION <= 5
827   writer->SetInput(linesPolyData);
828 #else
829   writer->SetInputData(linesPolyData);
830 #endif
831   writer->Write();
832
833
834
835   // ***************************************
836   // Save the links in a file
837   // *******
838
839   // Create the outputfile
840   std::stringstream filepath_evaluation;
841   filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << ".csv";
842
843   std::ofstream file(filepath_evaluation.str().c_str());
844   if(file.is_open())
845   {
846     // Save the header
847     //file << "Node_" << tree_A.GetImageName() << " " << "Node_" << tree_B.GetImageName()<< "\n";
848     file << "TreeName "
849       "idLocalN1 idLocalN2 "
850       "Node1x Node1y Node1z "
851       "Node2x Node2y Node2z "
852       "idGlobalN1 "
853       "idMatch" << std::endl;
854
855
856     std::vector< std::pair< std::pair<Node*, Node*>, std::pair<Node*, Node*> > >::iterator it_edges = vector_pair_edges_A_to_B.begin();
857     for(; it_edges != vector_pair_edges_A_to_B.end(); ++it_edges)
858     {
859
860       std::pair<Node*, Node*> edge_A = (*it_edges).first;
861       std::pair<Node*, Node*> edge_B = (*it_edges).second;
862
863       //file << edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << "\n";
864       Vec3 coord_EndNodeA = edge_A.second->GetCoords();
865       Vec3 coord_EndNodeB = edge_B.second->GetCoords();
866       file << tree_A.GetImageName() << " " <<
867         edge_A.second->GetId() << " " << edge_B.second->GetId()+1000 << " " <<
868         coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
869         coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
870         tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << " " <<
871         tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] <<"\n";
872
873       file << tree_B.GetImageName() << " " <<
874         edge_B.second->GetId()+1000 << " " << edge_A.second->GetId() << " " <<
875         coord_EndNodeB[0] << " " << coord_EndNodeB[1] << " " << coord_EndNodeB[2] << " " <<
876         coord_EndNodeA[0] << " " << coord_EndNodeA[1] << " " << coord_EndNodeA[2] << " " <<
877         tree_B.GetImageName() << coord_EndNodeB[0] << coord_EndNodeB[1] << coord_EndNodeB[2] << " " <<
878         tree_A.GetImageName() << coord_EndNodeA[0] << coord_EndNodeA[1] << coord_EndNodeA[2] << "\n";
879     }
880   }
881
882   file.close();
883   // *******
884   // ***************************************
885
886
887
888
889   std::cout << "printCommonTreeBetweenTwoTrees ... OK" << std::endl;
890 }
891
892 // -------------------------------------------------------------------------
893 void printMatchingResultToFile(AirwaysTree tree_A, AirwaysTree tree_B, std::map< unsigned int, std::vector<Node*> > map_A_to_B, std::map< unsigned int, std::vector<Node*> > map_B_to_A, unsigned int Q, unsigned int F)
894 {
895   std::cout << "Printing matching result ... " << std::endl;
896
897   // Variables and types
898   typedef std::map< unsigned int, vec_nodes > map_id_node;
899
900   // Create the outputfile
901   std::stringstream filepath_evaluation;
902   filepath_evaluation << tree_A.GetResultPath() << "/" << tree_A.GetImageName() << "_" << tree_B.GetImageName() << "_Q_" << Q << "_F_" << F << "_matching.csv";
903
904   std::ofstream file(filepath_evaluation.str().c_str());
905   if(file.is_open())
906   {
907     // Save the header
908     file << "TreeName idLocalN1 idLocalN2 "
909       "Node1x Node1y Node1z "
910       "Node2x Node2y Node2z "
911       "idGlobalN1 "
912       "idMatch "
913       "typeMatch_match_1_nonmatch_0 "
914       "depth "
915       "leaf"<< std::endl;
916
917     // ---------------
918     // From A to B
919
920     // Save the match or non-match for each node from A to B
921     for(int id_a=1; id_a <= tree_A.GetWeight( ); ++id_a)
922     {
923       // Get the actual node in tree A
924       Node* node_a = tree_A.GetNodeById( id_a );
925       Vec3 coords_a = node_a->GetCoords();
926       unsigned int depth_a = tree_A.GetDepthById(id_a);
927       bool leaf_a = node_a->IsLeaf();
928
929       // Check if the node was matched
930       map_id_node::iterator it_a2b = map_A_to_B.find( id_a );
931       if( it_a2b != map_A_to_B.end( ) )
932       {
933         // Get the correspoding matching nodes and print them
934         vec_nodes nodes_B = (*it_a2b).second;
935
936         vec_nodes::iterator it_nodes_b = nodes_B.begin( );
937         for( ; it_nodes_b != nodes_B.end( ); ++it_nodes_b)
938         {
939           Vec3 coords_b = (*it_nodes_b)->GetCoords();
940
941           file << tree_A.GetImageName() << " " << id_a << " " << (*it_nodes_b)->GetId()+1000 << " "
942                << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
943                << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
944                << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
945                << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << coords_b[0] << coords_b[1] << coords_b[2] << " "
946                << "1" << " "
947                << depth_a << " "
948                << leaf_a << "\n";
949         }
950       }
951       else
952       {
953         file << tree_A.GetImageName() << " " << id_a << " " << "0" << " "
954              << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
955              << "0" << " " << "0" << " " << "0" << " "
956              << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << " "
957              << tree_A.GetImageName() << coords_a[0] << coords_a[1] << coords_a[2] << "0" << "0" << "0" << " "
958              << "0" << " "
959              << depth_a << " "
960              << leaf_a  << "\n";
961       }
962     }
963
964     // ---------------
965     // From B to A
966
967     // Save the match or non-match for each node from A to B
968     for(int id_b=1; id_b <= tree_B.GetWeight( ); ++id_b)
969     {
970       // Get the actual node in tree B
971       Node* node_b = tree_B.GetNodeById( id_b );
972       Vec3 coords_b = node_b->GetCoords();
973       unsigned int depth_b = tree_B.GetDepthById(id_b);
974       bool leaf_b = node_b->IsLeaf();
975
976       // Check if the node was matched
977       map_id_node::iterator it_b2a = map_B_to_A.find( id_b );
978       if( it_b2a != map_B_to_A.end( ) )
979       {
980         // Get the correspoding matching nodes and print them
981         vec_nodes nodes_A = (*it_b2a).second;
982
983         vec_nodes::iterator it_nodes_a = nodes_A.begin( );
984         for( ; it_nodes_a != nodes_A.end( ); ++it_nodes_a)
985         {
986           Vec3 coords_a = (*it_nodes_a)->GetCoords();
987
988           file << tree_B.GetImageName() << " " << id_b+1000 << " " << (*it_nodes_a)->GetId() << " "
989                << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
990                << coords_a[0] << " " << coords_a[1] << " " << coords_a[2] << " "
991                << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
992                << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << coords_a[0] << coords_a[1] << coords_a[2] << " "
993                << "1" << " "
994                << depth_b << " "
995                << leaf_b  << "\n";
996         }
997       }
998       else
999       {
1000         file << tree_B.GetImageName() << " " << id_b+1000 << " " << "0" << " "
1001              << coords_b[0] << " " << coords_b[1] << " " << coords_b[2] << " "
1002              << "0" << " " << "0" << " " << "0" << " "
1003              << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << " "
1004              << tree_B.GetImageName() << coords_b[0] << coords_b[1] << coords_b[2] << "0" << "0" << "0" << " "
1005              << "0" << " "
1006              << depth_b << " "
1007              << leaf_b  << "\n";
1008       }//esle
1009     }//rof
1010   }//fi
1011
1012   file.close(); // Close the file
1013
1014   std::cout << "Printing matching result DONE" << std::endl;
1015 }
1016
1017 // -------------------------------------------------------------------------
1018 void createLinesAndPointsForVTK(const Node* node, vtkSmartPointer<vtkPoints>& pts,vtkSmartPointer<vtkCellArray>& lines, vtkSmartPointer<vtkUnsignedCharArray>& colors, bool common, bool isRoot)
1019 {
1020   // Insert the actual point/node
1021   //vtkIdType id_father = idNonRoot;
1022   //if(isRoot)
1023   //id_father = pts->InsertNextPoint(node->GetCoords().GetVec3());
1024   vtkIdType id_father = node->GetId();
1025   if(isRoot)
1026     pts->SetPoint(id_father,node->GetCoords().GetVec3());
1027
1028   // Iterate over the children
1029   const vec_nodes children = node->GetChildren();
1030   for (vec_nodes::const_iterator it_child = children.begin(); it_child != children.end(); ++it_child)
1031   {
1032     if (!(*it_child)->IsMarked() && common)
1033       continue;
1034
1035     //vtkIdType id_son = pts->InsertNextPoint((*it_child)->GetCoords().GetVec3());
1036     vtkIdType id_son = (*it_child)->GetId();
1037     pts->SetPoint(id_son,(*it_child)->GetCoords().GetVec3());
1038
1039     // Set color to be used
1040     int numColor = (*it_child)->GetLevel() % 4;
1041     if(numColor == 0)
1042       colors->InsertNextTupleValue(green);
1043     else if(numColor == 1)
1044       colors->InsertNextTupleValue(red);
1045     else if(numColor == 2)
1046       colors->InsertNextTupleValue(red);
1047     else
1048       colors->InsertNextTupleValue(red);
1049
1050     // Add the line
1051     vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
1052     line->GetPointIds()->SetId(0, id_father);
1053     line->GetPointIds()->SetId(1, id_son);
1054     lines->InsertNextCell(line);
1055
1056     createLinesAndPointsForVTK(*it_child, pts, lines, colors, common, false);
1057   } //for
1058 }
1059
1060 // eof - $RCSfile$