]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
Summer nights are really too hot to sleep.
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/06/24 10:55:59 $
7   Version:   $Revision: 1.10 $
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 Files list 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  * WARNING : FileList = std::vector<File* >
245  * @param fileList Coherent File list (same Serie UID) to sort
246  * @return false only if the header is bugged !
247  */
248 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
249 //based on Jolinda's algorithm
250 {
251    //iop is calculated based on the file file
252    float cosines[6];
253    float normal[3];
254    float ipp[3];
255    float dist;
256    float min = 0, max = 0;
257    bool first = true;
258    int n=0;
259    std::vector<float> distlist;
260
261    //!\todo rewrite this for loop.
262    for ( FileList::const_iterator 
263          it = fileList->begin();
264          it != fileList->end(); ++it )
265    {
266       if ( first ) 
267       {
268          (*it)->GetImageOrientationPatient( cosines );
269       
270          // You only have to do this once for all slices in the volume. Next, 
271          // for each slice, calculate the distance along the slice normal 
272          // using the IPP tag ("dist" is initialized to zero before reading 
273          // the first slice) :
274          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
275          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
276          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
277   
278          ipp[0] = (*it)->GetXOrigin();
279          ipp[1] = (*it)->GetYOrigin();
280          ipp[2] = (*it)->GetZOrigin();
281
282          dist = 0;
283          for ( int i = 0; i < 3; ++i )
284          {
285             dist += normal[i]*ipp[i];
286          }
287     
288          distlist.push_back( dist );
289
290          max = min = dist;
291          first = false;
292       }
293       else 
294       {
295          ipp[0] = (*it)->GetXOrigin();
296          ipp[1] = (*it)->GetYOrigin();
297          ipp[2] = (*it)->GetZOrigin();
298   
299          dist = 0;
300          for ( int i = 0; i < 3; ++i )
301          {
302             dist += normal[i]*ipp[i];
303          }
304
305          distlist.push_back( dist );
306
307          min = (min < dist) ? min : dist;
308          max = (max > dist) ? max : dist;
309       }
310       ++n;
311    }
312
313    // Then I order the slices according to the value "dist". Finally, once
314    // I've read in all the slices, I calculate the z-spacing as the difference
315    // between the "dist" values for the first two slices.
316    FileVector CoherentFileVector(n);
317    // CoherentFileVector.reserve( n );
318    CoherentFileVector.resize( n );
319    // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
320
321    // Find out if min/max are coherent
322    if ( min == max )
323      {
324      gdcmWarningMacro( "Looks like all images have the exact same image position...");
325      return false;
326      }
327
328    float step = (max - min)/(n - 1);
329    int pos;
330    n = 0;
331     
332    //VC++ don't understand what scope is !! it -> it2
333    for (FileList::const_iterator it2  = fileList->begin();
334         it2 != fileList->end(); ++it2, ++n)
335    {
336       //2*n sort algo !!
337       //Assumption: all files are present (no one missing)
338       pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
339
340       // a Dicom 'Serie' may contain scout views
341       // and images may have differents directions
342       // -> More than one may have the same 'pos'
343       // Sorting has then NO meaning !
344       if (CoherentFileVector[pos]==NULL)
345          CoherentFileVector[pos] = *it2;
346       else
347       {
348          gdcmWarningMacro( "2 files same position");
349          return false;
350       }
351    }
352
353    fileList->clear();  // doesn't delete list elements, only node
354   
355    //VC++ don't understand what scope is !! it -> it3
356    for (FileVector::const_iterator it3  = CoherentFileVector.begin();
357         it3 != CoherentFileVector.end(); ++it3)
358    {
359       fileList->push_back( *it3 );
360    }
361
362    distlist.clear();
363    CoherentFileVector.clear();
364
365    return true;
366 }
367
368 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
369 {
370   return file1->GetImageNumber() < file2->GetImageNumber();
371 }
372
373 /**
374  * \brief sorts the images, according to their Image Number
375  * \note Works only on bona fide files  (i.e image number is a character string
376  *                                      corresponding to an integer)
377  *             within a bona fide serie (i.e image numbers are consecutive)
378  * @param fileList Coherent File list (same Serie UID) to sort 
379  * @return false if non nona fide stuff encountered
380  */
381 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
382 {
383    int min, max, pos;
384    int n = fileList->size();
385
386    FileList::const_iterator it = fileList->begin();
387    min = max = (*it)->GetImageNumber();
388
389    for (; it != fileList->end(); ++it, ++n)
390    {
391       pos = (*it)->GetImageNumber();
392       min = (min < pos) ? min : pos;
393       max = (max > pos) ? max : pos;
394    }
395
396    // Find out if image numbers are coherent (consecutive)
397    if ( min == max || max == 0 || max >= (n+min) )
398       return false;
399
400    std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
401
402    return true;
403 }
404
405 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
406 {
407   return file1->GetFileName() < file2->GetFileName();
408 }
409
410 /**
411  * \brief sorts the images, according to their File Name
412  * @param fileList Coherent File list (same Serie UID) to sort
413  * @return false only if the header is bugged !
414  */
415 bool SerieHelper::FileNameOrdering(FileList *fileList)
416 {
417    std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
418    return true;
419 }
420
421 //-----------------------------------------------------------------------------
422 // Print
423 /**
424  * \brief   Canonical printer.
425  */
426 void SerieHelper::Print(std::ostream &os, std::string const &indent)
427 {
428    // For all the Coherent File lists of the gdcm::Serie
429    CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
430    if ( itl == CoherentFileListHT.end() )
431    {
432       gdcmWarningMacro( "No Coherent File list found" );
433       return;
434    }
435    while (itl != CoherentFileListHT.end())
436    { 
437       os << "Serie UID :[" << itl->first << "]" << std::endl;
438
439       // For all the files of a Coherent File list
440       for (FileList::iterator it =  (itl->second)->begin();
441                                   it != (itl->second)->end(); 
442                                 ++it)
443       {
444          os << indent << " --- " << (*it)->GetFileName() << std::endl;
445       }
446       ++itl;
447    }
448 }
449
450 //-----------------------------------------------------------------------------
451 } // end namespace gdcm