]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
ENH: Adding feature for user to refine the search of dicom file within a directory...
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/05/27 21:19:03 $
7   Version:   $Revision: 1.8 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmSerieHelper.h"
20 #include "gdcmDirList.h"
21 #include "gdcmFile.h"
22 #include "gdcmDebug.h"
23 #include "gdcmUtil.h"
24
25 #include <math.h>
26 #include <vector>
27 #include <algorithm>
28
29 namespace gdcm 
30 {
31
32 //-----------------------------------------------------------------------------
33 // Constructor / Destructor
34 /**
35  * \brief   Constructor from a given SerieHelper
36  */
37 SerieHelper::SerieHelper()
38 {
39    // For all the File lists of the gdcm::Serie
40    FileList *l = GetFirstCoherentFileList();
41    while (l)
42    { 
43       // For all the files of a File list
44       for (FileList::iterator it  = l->begin();
45                               it != l->end(); 
46                             ++it)
47       {
48          delete *it;
49       }
50       l->clear();
51       delete l;;
52       l = GetNextCoherentFileList();
53    }
54 }
55
56 /**
57  * \brief   Canonical destructor.
58  */
59 SerieHelper::~SerieHelper()
60 {
61    // For all the Coherent File lists of the gdcm::Serie
62    FileList *l = GetFirstCoherentFileList();
63    while (l)
64    { 
65       // For all the files of a Coherent File list
66       for (FileList::iterator it  = l->begin();
67                               it != l->end(); 
68                             ++it)
69       {
70          delete *it;
71       }
72       l->clear();
73       delete l;
74       l = GetNextCoherentFileList();
75    }
76 }
77
78 //-----------------------------------------------------------------------------
79
80 //-----------------------------------------------------------------------------
81
82 // Public
83 /**
84  * \brief add a gdcm::File to the list corresponding to its Serie UID
85  * @param   filename Name of the file to deal with
86  */
87 void SerieHelper::AddFileName(std::string const &filename)
88 {
89    // Create a DICOM file
90    File *header = new File( filename ); 
91    if( header->IsReadable() )
92    {
93       int allrules = 1;
94       // First step the user has defined s set of rules for the DICOM he is looking for
95       // make sure the file correspond to his set of rules:
96       for(SerieRestrictions::iterator it = Restrictions.begin();
97           it != Restrictions.end();
98           ++it)
99       {
100          const Rule &r = *it;
101          const std::string s;// = header->GetEntryValue( r.first );
102          if( !Util::DicomStringEqual(s, r.second.c_str()))
103          {
104            // Argh ! This rule is unmatch let's just quit
105            allrules = 0;
106            break;
107          }
108       }
109       if( allrules ) // all rules are respected:
110       {
111          // Alright ! we have a found a DICOM that match the user expectation. 
112          // Let's add it !
113
114          // 0020 000e UI REL Series Instance UID
115          const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
116          // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
117          // no need here to do anything special
118
119          if ( CoherentFileListHT.count(uid) == 0 )
120          {
121             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
122             // create a std::list in 'uid' position
123             CoherentFileListHT[uid] = new FileList;
124          }
125          // Current Serie UID and DICOM header seems to match add the file:
126          CoherentFileListHT[uid]->push_back( header );
127       }
128       else
129       {
130          // at least one rule was unmatch we need to deallocate the file:
131          delete header;
132       }
133    }
134    else
135    {
136       gdcmWarningMacro("Could not read file: " << filename );
137       delete header;
138    }
139 }
140 /**
141  * \brief add a rules for restricting a DICOM file to be in the serie we are
142  * trying to find. For example you can select only the DICOM file from a
143  * directory which would have a particular EchoTime==4.0.
144  * This method is a user level, value is not required to be formatted as a DICOM
145  * string
146  */
147 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
148 {
149    Rule r;
150    r.first = key;
151    r.second = value;
152    Restrictions.push_back( r ); 
153 }
154
155 /**
156  * \brief Sets the root Directory
157  * @param   dir Name of the directory to deal with
158  * @param recursive whether we want explore recursively the Directory
159  */
160 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
161 {
162    DirList dirList(dir, recursive); // OS specific
163   
164    DirListType filenames_list = dirList.GetFilenames();
165    for( DirListType::const_iterator it = filenames_list.begin(); 
166         it != filenames_list.end(); ++it)
167    {
168       AddFileName( *it );
169    }
170 }
171
172 /**
173  * \brief Sorts the given File List
174  * \warning This could be implemented in a 'Strategy Pattern' approach
175  *          But as I don't know how to do it, I leave it this way
176  *          BTW, this is also a Strategy, I don't know this is the best approach :)
177  */
178 void SerieHelper::OrderFileList(FileList *CoherentFileList)
179 {
180    if( ImagePositionPatientOrdering( CoherentFileList ) )
181    {
182       return ;
183    }
184    else if( ImageNumberOrdering(CoherentFileList ) )
185    {
186       return ;
187    }
188    else  
189    {
190       FileNameOrdering(CoherentFileList );
191    }
192 }
193
194 /**
195  * \brief   Get the first List while visiting the CoherentFileListHT
196  * @return  The first FileList if found, otherwhise NULL
197  */
198 FileList *SerieHelper::GetFirstCoherentFileList()
199 {
200    ItListHt = CoherentFileListHT.begin();
201    if( ItListHt != CoherentFileListHT.end() )
202       return ItListHt->second;
203    return NULL;
204 }
205
206 /**
207  * \brief   Get the next List while visiting the CoherentFileListHT
208  * \note : meaningfull only if GetFirstCoherentFileList already called
209  * @return  The next FileList if found, otherwhise NULL
210  */
211 FileList *SerieHelper::GetNextCoherentFileList()
212 {
213    gdcmAssertMacro (ItListHt != CoherentFileListHT.end());
214   
215    ++ItListHt;
216    if ( ItListHt != CoherentFileListHT.end() )
217       return ItListHt->second;
218    return NULL;
219 }
220
221 /**
222  * \brief   Get the Coherent Files list according to its Serie UID
223  * @param SerieUID SerieUID
224  * \return  pointer to the Coherent Filseslist if found, otherwhise NULL
225  */
226 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
227 {
228    if ( CoherentFileListHT.count(SerieUID) == 0 )
229       return 0;     
230    return CoherentFileListHT[SerieUID];
231 }
232
233 //-----------------------------------------------------------------------------
234 // Protected
235
236 //-----------------------------------------------------------------------------
237 // Private
238 /**
239  * \brief sorts the images, according to their Patient Position
240  *  We may order, considering :
241  *   -# Image Position Patient
242  *   -# Image Number
243  *   -# More to come :-)
244  * @param fileList Coherent File list (same Serie UID) to sort
245  * @return false only if the header is bugged !
246  */
247 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
248 //based on Jolinda's algorithm
249 {
250    //iop is calculated based on the file file
251    float cosines[6];
252    float normal[3];
253    float ipp[3];
254    float dist;
255    float min = 0, max = 0;
256    bool first = true;
257    int n=0;
258    std::vector<float> distlist;
259
260    //!\todo rewrite this for loop.
261    for ( FileList::const_iterator 
262          it = fileList->begin();
263          it != fileList->end(); ++it )
264    {
265       if( first ) 
266       {
267          (*it)->GetImageOrientationPatient( cosines );
268       
269          // You only have to do this once for all slices in the volume. Next, 
270          // for each slice, calculate the distance along the slice normal 
271          // using the IPP tag ("dist" is initialized to zero before reading 
272          // the first slice) :
273          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
274          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
275          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
276   
277          ipp[0] = (*it)->GetXOrigin();
278          ipp[1] = (*it)->GetYOrigin();
279          ipp[2] = (*it)->GetZOrigin();
280
281          dist = 0;
282          for ( int i = 0; i < 3; ++i )
283          {
284             dist += normal[i]*ipp[i];
285          }
286     
287          distlist.push_back( dist );
288
289          max = min = dist;
290          first = false;
291       }
292       else 
293       {
294          ipp[0] = (*it)->GetXOrigin();
295          ipp[1] = (*it)->GetYOrigin();
296          ipp[2] = (*it)->GetZOrigin();
297   
298          dist = 0;
299          for ( int i = 0; i < 3; ++i )
300          {
301             dist += normal[i]*ipp[i];
302          }
303
304          distlist.push_back( dist );
305
306          min = (min < dist) ? min : dist;
307          max = (max > dist) ? max : dist;
308       }
309       ++n;
310    }
311
312    // Then I order the slices according to the value "dist". Finally, once
313    // I've read in all the slices, I calculate the z-spacing as the difference
314    // between the "dist" values for the first two slices.
315    FileVector CoherentFileVector(n);
316    // CoherentFileVector.reserve( n );
317    CoherentFileVector.resize( n );
318    // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
319
320    // Find out if min/max are coherent
321    if( min == max )
322      {
323      gdcmWarningMacro( "Looks like all images have the exact same image position...");
324      return false;
325      }
326
327    float step = (max - min)/(n - 1);
328    int pos;
329    n = 0;
330     
331    //VC++ don't understand what scope is !! it -> it2
332    for (FileList::const_iterator it2  = fileList->begin();
333         it2 != fileList->end(); ++it2, ++n)
334    {
335       //2*n sort algo !!
336       //Assumption: all files are present (no one missing)
337       pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
338
339       // a Dicom 'Serie' may contain scout views
340       // and images may have differents directions
341       // -> More than one may have the same 'pos'
342       // Sorting has then NO meaning !
343       if (CoherentFileVector[pos]==NULL)
344          CoherentFileVector[pos] = *it2;
345       else
346       {
347          gdcmWarningMacro( "2 files same position");
348          return false;
349       }
350    }
351
352    fileList->clear();  // doesn't delete list elements, only node
353   
354    //VC++ don't understand what scope is !! it -> it3
355    for (FileVector::const_iterator it3  = CoherentFileVector.begin();
356         it3 != CoherentFileVector.end(); ++it3)
357    {
358       fileList->push_back( *it3 );
359    }
360
361    distlist.clear();
362    CoherentFileVector.clear();
363
364    return true;
365 }
366
367 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
368 {
369   return file1->GetImageNumber() < file2->GetImageNumber();
370 }
371
372 /**
373  * \brief sorts the images, according to their Image Number
374  * \note Works only on bona fide files  (i.e image number is a character string
375  *                                      corresponding to an integer)
376  *             within a bona fide serie (i.e image numbers are consecutive)
377  * @param fileList Coherent File list (same Serie UID) to sort 
378  * @return false if non nona fide stuff encountered
379  */
380 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
381 {
382    int min, max, pos;
383    int n = fileList->size();
384
385    FileList::const_iterator it = fileList->begin();
386    min = max = (*it)->GetImageNumber();
387
388    for (; it != fileList->end(); ++it, ++n)
389    {
390       pos = (*it)->GetImageNumber();
391       min = (min < pos) ? min : pos;
392       max = (max > pos) ? max : pos;
393    }
394
395    // Find out if image numbers are coherent (consecutive)
396    if( min == max || max == 0 || max >= (n+min))
397       return false;
398
399    std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
400
401    return true;
402 }
403
404 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
405 {
406   return file1->GetFileName() < file2->GetFileName();
407 }
408
409 /**
410  * \brief sorts the images, according to their File Name
411  * @param fileList Coherent File list (same Serie UID) to sort
412  * @return false only if the header is bugged !
413  */
414 bool SerieHelper::FileNameOrdering(FileList *fileList)
415 {
416    std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
417    return true;
418 }
419
420 //-----------------------------------------------------------------------------
421 // Print
422 /**
423  * \brief   Canonical printer.
424  */
425 void SerieHelper::Print(std::ostream &os, std::string const & indent)
426 {
427    // For all the Coherent File lists of the gdcm::Serie
428    CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
429    if ( itl == CoherentFileListHT.end() )
430    {
431       gdcmWarningMacro( "No Coherent File list found" );
432       return;
433    }
434    while (itl != CoherentFileListHT.end())
435    { 
436       os << "Serie UID :[" << itl->first << "]" << std::endl;
437
438       // For all the files of a Coherent File list
439       for (FileList::iterator it =  (itl->second)->begin();
440                                   it != (itl->second)->end(); 
441                                 ++it)
442       {
443          os << indent << " --- " << (*it)->GetFileName() << std::endl;
444       }
445       ++itl;
446    }
447 }
448
449 //-----------------------------------------------------------------------------
450 } // end namespace gdcm