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