]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
Add SerieHelper::AddGdcmFile(File *header) method.
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/07/19 09:04:58 $
7   Version:   $Revision: 1.13 $
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 (gdcm::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 ();
91    header->SetLoadMode(LoadMode);
92    header->SetFileName( filename ); 
93    header->Load();
94    //File *header = new File( filename ); // Deprecated old style 
95    if ( header->IsReadable() )
96    {
97       int allrules = 1;
98       // First step the user has defined a set of rules for the DICOM 
99       // he is looking for.
100       // make sure the file correspond to his set of rules:
101       for(SerieRestrictions::iterator it = Restrictions.begin();
102           it != Restrictions.end();
103           ++it)
104       {
105          const Rule &r = *it;
106          const std::string s;// = header->GetEntryValue( r.first );
107          if ( !Util::DicomStringEqual(s, r.second.c_str()) )
108          {
109            // Argh ! This rule is unmatch let's just quit
110            allrules = 0;
111            break;
112          }
113       }
114       if ( allrules ) // all rules are respected:
115       {
116          // Allright ! we have a found a DICOM that match the user expectation. 
117          // Let's add it !
118
119          // 0020 000e UI REL Series Instance UID
120          const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
121          // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
122          // no need here to do anything special
123
124          if ( CoherentFileListHT.count(uid) == 0 )
125          {
126             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
127             // create a std::list in 'uid' position
128             CoherentFileListHT[uid] = new FileList;
129          }
130          // Current Serie UID and DICOM header seems to match; add the file:
131          CoherentFileListHT[uid]->push_back( header );
132       }
133       else
134       {
135          // at least one rule was unmatch we need to deallocate the file:
136          delete header;
137       }
138    }
139    else
140    {
141       gdcmWarningMacro("Could not read file: " << filename );
142       delete header;
143    }
144 }
145
146 /**
147  * \brief add a gdcm::File to the first (and supposed to be unique) list
148  *        of the gdcm::SerieHelper.
149  * \warning : this method should be used by aware users only!
150  *            User is supposed to know the files he want to deal with
151  *           and consider them they belong to the same Serie
152  *           (even if their Serie UID is different)
153  *           user will probabely OrderFileList() this list (actually, ordering
154  *           user choosen gdm::File is the sole interest of this method)
155  *           Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
156  *           vtkGdcmReader parsing twice the same files. 
157  *           *no* coherence check is performed, but those specified
158  *           by SerieHelper::AddRestriction()
159  * @param   header gdcm::File* of the file to deal with
160  */
161 void SerieHelper::AddGdcmFile(File *header)
162 {
163       int allrules = 1;
164       // First step the user has defined a set of rules for the DICOM 
165       // he is looking for.
166       // make sure the file correspond to his set of rules:
167       for(SerieRestrictions::iterator it = Restrictions.begin();
168           it != Restrictions.end();
169           ++it)
170       {
171          const Rule &r = *it;
172          const std::string s;// = header->GetEntryValue( r.first );
173          if ( !Util::DicomStringEqual(s, r.second.c_str()) )
174          {
175            // Argh ! This rule is unmatch let's just quit
176            allrules = 0;
177            break;
178          }
179       }
180       if ( allrules ) // all rules are respected:
181       {
182          // Allright ! we have a found a DICOM that match the user expectation. 
183          // Let's add it !
184
185          const std::string &uid = "0";
186          // Serie UID of the gdcm::File* may be different.
187          // User is supposed to know what he wants
188
189          if ( CoherentFileListHT.count(uid) == 0 )
190          {
191             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
192             // create a std::list in 'uid' position
193             CoherentFileListHT[uid] = new FileList;
194          }
195          // Current Serie UID and DICOM header seems to match; add the file:
196          CoherentFileListHT[uid]->push_back( header );
197       }
198          // Even if a rule was unmatch we don't deallocate the gdcm::File:
199 }
200 /**
201  * \brief add a rules for restricting a DICOM file to be in the serie we are
202  * trying to find. For example you can select only the DICOM file from a
203  * directory which would have a particular EchoTime==4.0.
204  * This method is a user level, value is not required to be formatted as a DICOM
205  * string
206  */
207 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
208 {
209    Rule r;
210    r.first = key;
211    r.second = value;
212    Restrictions.push_back( r ); 
213 }
214
215 /**
216  * \brief Sets the root Directory
217  * @param   dir Name of the directory to deal with
218  * @param recursive whether we want explore recursively the Directory
219  */
220 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
221 {
222    DirList dirList(dir, recursive); // OS specific
223   
224    DirListType filenames_list = dirList.GetFilenames();
225    for( DirListType::const_iterator it = filenames_list.begin(); 
226         it != filenames_list.end(); ++it)
227    {
228       AddFileName( *it );
229    }
230 }
231
232 /**
233  * \brief Sorts the given File List
234  * \warning This could be implemented in a 'Strategy Pattern' approach
235  *          But as I don't know how to do it, I leave it this way
236  *          BTW, this is also a Strategy, I don't know this is the best approach :)
237  */
238 void SerieHelper::OrderFileList(FileList *coherentFileList)
239 {
240    if ( ImagePositionPatientOrdering( coherentFileList ) )
241    {
242       return ;
243    }
244    else if ( ImageNumberOrdering(coherentFileList ) )
245    {
246       return ;
247    }
248    else  
249    {
250       FileNameOrdering(coherentFileList );
251    }
252 }
253
254 /**
255  * \brief   Get the first List while visiting the CoherentFileListHT
256  * @return  The first FileList if found, otherwhise NULL
257  */
258 FileList *SerieHelper::GetFirstCoherentFileList()
259 {
260    ItListHt = CoherentFileListHT.begin();
261    if ( ItListHt != CoherentFileListHT.end() )
262       return ItListHt->second;
263    return NULL;
264 }
265
266 /**
267  * \brief   Get the next List while visiting the CoherentFileListHT
268  * \note : meaningfull only if GetFirstCoherentFileList() already called
269  * @return  The next FileList if found, otherwhise NULL
270  */
271 FileList *SerieHelper::GetNextCoherentFileList()
272 {
273    gdcmAssertMacro (ItListHt != CoherentFileListHT.end());
274   
275    ++ItListHt;
276    if ( ItListHt != CoherentFileListHT.end() )
277       return ItListHt->second;
278    return NULL;
279 }
280
281 /**
282  * \brief   Get the Coherent Files list according to its Serie UID
283  * @param SerieUID SerieUID
284  * \return  pointer to the Coherent Files list if found, otherwhise NULL
285  */
286 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
287 {
288    if ( CoherentFileListHT.count(SerieUID) == 0 )
289       return 0;     
290    return CoherentFileListHT[SerieUID];
291 }
292
293 //-----------------------------------------------------------------------------
294 // Protected
295
296 //-----------------------------------------------------------------------------
297 // Private
298 /**
299  * \brief sorts the images, according to their Patient Position
300  *  We may order, considering :
301  *   -# Image Position Patient
302  *   -# Image Number
303  *   -# More to come :-)
304  * WARNING : FileList = std::vector<File* >
305  * @param fileList Coherent File list (same Serie UID) to sort
306  * @return false only if the header is bugged !
307  */
308 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
309 //based on Jolinda Smith's algorithm
310 {
311    //iop is calculated based on the file file
312    float cosines[6];
313    float normal[3];
314    float ipp[3];
315    float dist;
316    float min = 0, max = 0;
317    bool first = true;
318    int n=0;
319    std::vector<float> distlist;
320
321    //!\todo rewrite this for loop.
322    for ( FileList::const_iterator 
323          it = fileList->begin();
324          it != fileList->end(); ++it )
325    {
326       if ( first ) 
327       {
328          (*it)->GetImageOrientationPatient( cosines );
329       
330          // You only have to do this once for all slices in the volume. Next, 
331          // for each slice, calculate the distance along the slice normal 
332          // using the IPP tag ("dist" is initialized to zero before reading 
333          // the first slice) :
334          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
335          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
336          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
337   
338          ipp[0] = (*it)->GetXOrigin();
339          ipp[1] = (*it)->GetYOrigin();
340          ipp[2] = (*it)->GetZOrigin();
341
342          dist = 0;
343          for ( int i = 0; i < 3; ++i )
344          {
345             dist += normal[i]*ipp[i];
346          }
347     
348          distlist.push_back( dist );
349
350          max = min = dist;
351          first = false;
352       }
353       else 
354       {
355          ipp[0] = (*it)->GetXOrigin();
356          ipp[1] = (*it)->GetYOrigin();
357          ipp[2] = (*it)->GetZOrigin();
358   
359          dist = 0;
360          for ( int i = 0; i < 3; ++i )
361          {
362             dist += normal[i]*ipp[i];
363          }
364
365          distlist.push_back( dist );
366
367          min = (min < dist) ? min : dist;
368          max = (max > dist) ? max : dist;
369       }
370       ++n;
371    }
372
373    // Then I order the slices according to the value "dist". Finally, once
374    // I've read in all the slices, I calculate the z-spacing as the difference
375    // between the "dist" values for the first two slices.
376    FileVector CoherentFileVector(n);
377    // CoherentFileVector.reserve( n );
378    CoherentFileVector.resize( n );
379    // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
380
381    // Find out if min/max are coherent
382    if ( min == max )
383      {
384      gdcmWarningMacro( "Looks like all images have the exact same image position."
385                        << "No PositionPatientOrdering sort performed" );
386      return false;
387      }
388
389    float step = (max - min)/(n - 1);
390    int pos;
391    n = 0;
392     
393    //VC++ don't understand what scope is !! it -> it2
394    for (FileList::const_iterator it2  = fileList->begin();
395         it2 != fileList->end(); ++it2, ++n)
396    {
397       //2*n sort algo !!
398       //Assumption: all files are present (no one missing)
399       pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
400
401       // a Dicom 'Serie' may contain scout views
402       // and images may have differents directions
403       // -> More than one may have the same 'pos'
404       // Sorting has then NO meaning !
405       if (CoherentFileVector[pos]==NULL)
406          CoherentFileVector[pos] = *it2;
407       else
408       {
409          gdcmWarningMacro( "At least 2 files with same position. No PositionPatientOrdering sort performed");
410          return false;
411       }
412    }
413
414    fileList->clear();  // doesn't delete list elements, only nodes
415   
416    //VC++ don't understand what scope is !! it -> it3
417    for (FileVector::const_iterator it3  = CoherentFileVector.begin();
418         it3 != CoherentFileVector.end(); ++it3)
419    {
420       fileList->push_back( *it3 );
421    }
422
423    distlist.clear();
424    CoherentFileVector.clear();
425
426    return true;
427 }
428
429 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
430 {
431   return file1->GetImageNumber() < file2->GetImageNumber();
432 }
433
434 /**
435  * \brief sorts the images, according to their Image Number
436  * \note Works only on bona fide files  (i.e image number is a character string
437  *                                      corresponding to an integer)
438  *             within a bona fide serie (i.e image numbers are consecutive)
439  * @param fileList Coherent File list (same Serie UID) to sort 
440  * @return false if non bona fide stuff encountered
441  */
442 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
443 {
444    int min, max, pos;
445    int n = fileList->size();
446
447    FileList::const_iterator it = fileList->begin();
448    min = max = (*it)->GetImageNumber();
449
450    for (; it != fileList->end(); ++it, ++n)
451    {
452       pos = (*it)->GetImageNumber();
453       min = (min < pos) ? min : pos;
454       max = (max > pos) ? max : pos;
455    }
456
457    // Find out if image numbers are coherent (consecutive)
458    if ( min == max || max == 0 || max >= (n+min) )
459    {
460       gdcmWarningMacro( " 'Image numbers' not coherent. No ImageNumberOrdering sort performed.");
461       return false;
462    }
463    std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
464
465    return true;
466 }
467
468 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
469 {
470   return file1->GetFileName() < file2->GetFileName();
471 }
472
473 /**
474  * \brief sorts the images, according to their File Name
475  * @param fileList Coherent File list (same Serie UID) to sort
476  * @return false only if the header is bugged !
477  */
478 bool SerieHelper::FileNameOrdering(FileList *fileList)
479 {
480    std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
481    return true;
482 }
483
484 //-----------------------------------------------------------------------------
485 // Print
486 /**
487  * \brief   Canonical printer.
488  */
489 void SerieHelper::Print(std::ostream &os, std::string const &indent)
490 {
491    // For all the Coherent File lists of the gdcm::Serie
492    CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
493    if ( itl == CoherentFileListHT.end() )
494    {
495       gdcmWarningMacro( "No Coherent File list found" );
496       return;
497    }
498    while (itl != CoherentFileListHT.end())
499    { 
500       os << "Serie UID :[" << itl->first << "]" << std::endl;
501
502       // For all the files of a Coherent File list
503       for (FileList::iterator it =  (itl->second)->begin();
504                                   it != (itl->second)->end(); 
505                                 ++it)
506       {
507          os << indent << " --- " << (*it)->GetFileName() << std::endl;
508       }
509       ++itl;
510    }
511 }
512
513 //-----------------------------------------------------------------------------
514 } // end namespace gdcm