]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
Reverse order sorting now works, even with user supplied function.
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/08/30 14:15:34 $
7   Version:   $Revision: 1.19 $
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 "gdcmDictEntry.h" // for TranslateToKey
23 #include "gdcmDebug.h"
24 #include "gdcmUtil.h"
25
26 #include <math.h>
27 #include <vector>
28 #include <algorithm>
29
30 namespace gdcm 
31 {
32 //-----------------------------------------------------------------------------
33
34 //-----------------------------------------------------------------------------
35 // Constructor / Destructor
36 /**
37  * \brief   Constructor from a given SerieHelper
38  */
39 SerieHelper::SerieHelper()
40 {
41    UserLessThanFunction = 0;
42
43    // For all the File lists that may already exist within the gdcm::Serie
44    FileList *l = GetFirstCoherentFileList();
45    while (l)
46    { 
47       // For all the files of a File list
48       for (gdcm::FileList::iterator it  = l->begin();
49                               it != l->end(); 
50                             ++it)
51       {
52          delete *it; // remove entry
53       }
54       l->clear();
55       delete l;     // remove the list
56       l = GetNextCoherentFileList();
57    }
58    DirectOrder = true;
59 }
60
61 /**
62  * \brief   Canonical destructor.
63  */
64 SerieHelper::~SerieHelper()
65 {
66    // For all the Coherent File lists of the gdcm::Serie
67    FileList *l = GetFirstCoherentFileList();
68    while (l)
69    { 
70       // For all the files of a Coherent File list
71       for (FileList::iterator it  = l->begin();
72                               it != l->end(); 
73                             ++it)
74       {
75          delete *it; // remove entry
76       }
77       l->clear();
78       delete l;  // remove the list
79       l = GetNextCoherentFileList();
80    }
81 }
82
83 //-----------------------------------------------------------------------------
84
85 //-----------------------------------------------------------------------------
86
87 // Public
88 /**
89  * \brief add a gdcm::File to the list corresponding to its Serie UID
90  * @param   filename Name of the file to deal with
91  */
92 void SerieHelper::AddFileName(std::string const &filename)
93 {
94    // Create a DICOM file
95    File *header = new File ();
96    header->SetLoadMode(LoadMode);
97    header->SetFileName( filename ); 
98    header->Load();
99
100    if ( header->IsReadable() )
101    {
102       int allrules = 1;
103       // First step the user has defined a set of rules for the DICOM file
104       // he is looking for.
105       // make sure the file correspond to his set of rules:
106
107 /*
108       for(SerieRestrictions::iterator it = Restrictions.begin();
109           it != Restrictions.end();
110           ++it)
111       {
112          const Rule &r = *it;
113          // doesn't compile (no matching function...).
114          const std::string s;// = header->GetEntryValue( r.first );
115          if ( !Util::DicomStringEqual(s, r.second.c_str()) )
116          {
117            // Argh ! This rule is unmatch let's just quit
118            allrules = 0;
119            break;
120          }
121       }
122 */
123       // Just keep 'new style' for Rules
124       std::string s;
125       for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
126           it2 != ExRestrictions.end();
127           ++it2)
128       {
129          const ExRule &r = *it2;
130          s = header->GetEntryValue( r.group, r.elem );
131          if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
132          {
133            // Argh ! This rule is unmatch let's just quit
134            allrules = 0;
135            break;
136          }
137       }
138
139       if ( allrules ) // all rules are respected:
140       {
141          // Allright ! we have a found a DICOM that match the user expectation. 
142          // Let's add it !
143
144          // 0020 000e UI REL Series Instance UID
145          const std::string &uid = header->GetEntryValue (0x0020, 0x000e);
146          // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
147          // no need here to do anything special
148
149          if ( CoherentFileListHT.count(uid) == 0 )
150          {
151             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
152             // create a std::list in 'uid' position
153             CoherentFileListHT[uid] = new FileList;
154          }
155          // Current Serie UID and DICOM header seems to match; add the file:
156          CoherentFileListHT[uid]->push_back( header );
157       }
158       else
159       {
160          // at least one rule was unmatch we need to deallocate the file:
161          delete header;
162       }
163    }
164    else
165    {
166       gdcmWarningMacro("Could not read file: " << filename );
167       delete header;
168    }
169 }
170
171 /**
172  * \brief add a gdcm::File to the first (and supposed to be unique) list
173  *        of the gdcm::SerieHelper.
174  * \warning : this method should be used by aware users only!
175  *            User is supposed to know the files he want to deal with
176  *           and consider them they belong to the same Serie
177  *           (even if their Serie UID is different)
178  *           user will probabely OrderFileList() this list (actually, ordering
179  *           user choosen gdm::File is the sole interest of this method)
180  *           Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
181  *           vtkGdcmReader parsing twice the same files. 
182  *           *no* coherence check is performed, but those specified
183  *           by SerieHelper::AddRestriction()
184  * @param   header gdcm::File* of the file to deal with
185  */
186 void SerieHelper::AddGdcmFile(File *header)
187 {
188       int allrules = 1;
189       // First step the user has defined a set of rules for the DICOM 
190       // he is looking for.
191       // make sure the file correspond to his set of rules:
192       for(SerieRestrictions::iterator it = Restrictions.begin();
193           it != Restrictions.end();
194           ++it)
195       {
196          const Rule &r = *it;
197          const std::string s;// = header->GetEntryValue( r.first );
198          if ( !Util::DicomStringEqual(s, r.second.c_str()) )
199          {
200            // Argh ! This rule is unmatch let's just quit
201            allrules = 0;
202            break;
203          }
204       }
205       if ( allrules ) // all rules are respected:
206       {
207          // Allright ! we have a found a DICOM that match the user expectation. 
208          // Let's add it !
209
210          const std::string &uid = "0";
211          // Serie UID of the gdcm::File* may be different.
212          // User is supposed to know what he wants
213
214          if ( CoherentFileListHT.count(uid) == 0 )
215          {
216             gdcmDebugMacro(" New Serie UID :[" << uid << "]");
217             // create a std::list in 'uid' position
218             CoherentFileListHT[uid] = new FileList;
219          }
220          // Current Serie UID and DICOM header seems to match; add the file:
221          CoherentFileListHT[uid]->push_back( header );
222       }
223          // Even if a rule was unmatch we don't deallocate the gdcm::File:
224 }
225
226 /**
227  * \brief add a rules for restricting a DICOM file to be in the serie we are
228  * trying to find. For example you can select only the DICOM file from a
229  * directory which would have a particular EchoTime==4.0.
230  * This method is a user level, value is not required to be formatted as a DICOM
231  * string
232  */
233 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem, 
234                                  std::string const &value, int op)
235 {
236    ExRule r;
237    r.group = group;
238    r.elem  = elem;
239    r.value = value;
240    r.op    = op;
241    ExRestrictions.push_back( r ); 
242 }
243
244 #ifndef GDCM_LEGACY_REMOVE
245 /**
246  * \brief add a rules for restricting a DICOM file to be in the serie we are
247  * trying to find. For example you can select only the DICOM file from a
248  * directory which would have a particular EchoTime==4.0.
249  * This method is a user level, value is not required to be formatted as a DICOM
250  * string
251  * @deprecated use : AddRestriction(uint16_t group, uint16_t elem, 
252  *                                 std::string const &value, int op);
253  */
254 void SerieHelper::AddRestriction(TagKey const &key, std::string const &value)
255 {
256    Rule r;
257    r.first = key;
258    r.second = value;
259    Restrictions.push_back( r ); 
260 }
261 #endif
262
263 /**
264  * \brief Sets the root Directory
265  * @param   dir Name of the directory to deal with
266  * @param recursive whether we want explore recursively the Directory
267  */
268 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
269 {
270    DirList dirList(dir, recursive); // OS specific
271   
272    DirListType filenames_list = dirList.GetFilenames();
273    for( DirListType::const_iterator it = filenames_list.begin(); 
274         it != filenames_list.end(); ++it)
275    {
276       AddFileName( *it );
277    }
278 }
279
280 /**
281  * \brief Sorts the given File List
282  * \warning This could be implemented in a 'Strategy Pattern' approach
283  *          But as I don't know how to do it, I leave it this way
284  *          BTW, this is also a Strategy, I don't know this is the best approach :)
285  */
286 void SerieHelper::OrderFileList(FileList *coherentFileList)
287 {
288
289    if ( SerieHelper::UserLessThanFunction )
290    {
291       UserOrdering( coherentFileList );
292       return; 
293    }
294    else if ( ImagePositionPatientOrdering( coherentFileList ) )
295    {
296       return ;
297    }
298    else if ( ImageNumberOrdering(coherentFileList ) )
299    {
300       return ;
301    }
302    else  
303    {
304       FileNameOrdering(coherentFileList );
305    }
306 }
307
308 /**
309  * \brief Elementary coherence checking of the files with the same Serie UID
310  * Only sizes and pixel type are checked right now ...
311  */ 
312 bool SerieHelper::IsCoherent(FileList *coherentFileList)
313 {
314    if(coherentFileList->size() == 1)
315    return true;
316
317    FileList::const_iterator it = coherentFileList->begin();
318
319    int nX = (*it)->GetXSize();
320    int nY = (*it)->GetYSize();
321    int pixelSize = (*it)->GetPixelSize();
322
323    it ++;
324    for ( ;
325          it != coherentFileList->end();
326        ++it)
327    {
328       if ( (*it)->GetXSize() != nX )
329          return false;
330       if ( (*it)->GetYSize() != nY )
331          return false;
332       if ( (*it)->GetPixelSize() != pixelSize )
333          return false;
334       // probabely more is to be checked (?)
335    }
336    return true;
337 }
338 /**
339  * \brief   Get the first List while visiting the CoherentFileListHT
340  * @return  The first FileList if found, otherwhise NULL
341  */
342 FileList *SerieHelper::GetFirstCoherentFileList()
343 {
344    ItListHt = CoherentFileListHT.begin();
345    if ( ItListHt != CoherentFileListHT.end() )
346       return ItListHt->second;
347    return NULL;
348 }
349
350 /**
351  * \brief   Get the next List while visiting the CoherentFileListHT
352  * \note : meaningfull only if GetFirstCoherentFileList() already called
353  * @return  The next FileList if found, otherwhise NULL
354  */
355 FileList *SerieHelper::GetNextCoherentFileList()
356 {
357    gdcmAssertMacro (ItListHt != CoherentFileListHT.end());
358   
359    ++ItListHt;
360    if ( ItListHt != CoherentFileListHT.end() )
361       return ItListHt->second;
362    return NULL;
363 }
364
365 /**
366  * \brief   Get the Coherent Files list according to its Serie UID
367  * @param SerieUID SerieUID
368  * \return  pointer to the Coherent Files list if found, otherwhise NULL
369  */
370 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
371 {
372    if ( CoherentFileListHT.count(SerieUID) == 0 )
373       return 0;     
374    return CoherentFileListHT[SerieUID];
375 }
376
377 //-----------------------------------------------------------------------------
378 // Protected
379
380 //-----------------------------------------------------------------------------
381 // Private
382 /**
383  * \brief sorts the images, according to their Patient Position
384  *  We may order, considering :
385  *   -# Image Position Patient
386  *   -# Image Number
387  *   -# More to come :-)
388  * WARNING : FileList = std::vector<File* >
389  * @param fileList Coherent File list (same Serie UID) to sort
390  * @return false only if the header is bugged !
391  */
392 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
393 //based on Jolinda Smith's algorithm
394 {
395    //iop is calculated based on the file file
396    float cosines[6];
397    float normal[3];
398    float ipp[3];
399    float dist;
400    float min = 0, max = 0;
401    bool first = true;
402    int n=0;
403    std::vector<float> distlist;
404
405    //!\todo rewrite this for loop.
406    for ( FileList::const_iterator 
407          it = fileList->begin();
408          it != fileList->end(); ++it )
409    {
410       if ( first ) 
411       {
412          (*it)->GetImageOrientationPatient( cosines );
413       
414          // You only have to do this once for all slices in the volume. Next, 
415          // for each slice, calculate the distance along the slice normal 
416          // using the IPP tag ("dist" is initialized to zero before reading 
417          // the first slice) :
418          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
419          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
420          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
421   
422          ipp[0] = (*it)->GetXOrigin();
423          ipp[1] = (*it)->GetYOrigin();
424          ipp[2] = (*it)->GetZOrigin();
425
426          dist = 0;
427          for ( int i = 0; i < 3; ++i )
428          {
429             dist += normal[i]*ipp[i];
430          }
431     
432          distlist.push_back( dist );
433
434          max = min = dist;
435          first = false;
436       }
437       else 
438       {
439          ipp[0] = (*it)->GetXOrigin();
440          ipp[1] = (*it)->GetYOrigin();
441          ipp[2] = (*it)->GetZOrigin();
442   
443          dist = 0;
444          for ( int i = 0; i < 3; ++i )
445          {
446             dist += normal[i]*ipp[i];
447          }
448
449          distlist.push_back( dist );
450
451          min = (min < dist) ? min : dist;
452          max = (max > dist) ? max : dist;
453       }
454       ++n;
455    }
456
457    // Then I order the slices according to the value "dist". Finally, once
458    // I've read in all the slices, I calculate the z-spacing as the difference
459    // between the "dist" values for the first two slices.
460    FileVector CoherentFileVector(n);
461    // CoherentFileVector.reserve( n );
462    CoherentFileVector.resize( n );
463    // gdcmAssertMacro( CoherentFileVector.capacity() >= n );
464
465    // Find out if min/max are coherent
466    if ( min == max )
467      {
468      gdcmWarningMacro( "Looks like all images have the exact same image position."
469                        << "No PositionPatientOrdering sort performed" );
470      return false;
471      }
472
473    float step = (max - min)/(n - 1);
474    int pos;
475    n = 0;
476     
477    //VC++ don't understand what scope is !! it -> it2
478    for (FileList::const_iterator it2  = fileList->begin();
479         it2 != fileList->end(); ++it2, ++n)
480    {
481       //2*n sort algo !!
482       //Assumption: all files are present (no one missing)
483       pos = (int)( fabs( (distlist[n]-min)/step) + .5 );
484
485       // a Dicom 'Serie' may contain scout views
486       // and images may have differents directions
487       // -> More than one may have the same 'pos'
488       // Sorting has then NO meaning !
489       if (CoherentFileVector[pos]==NULL)
490          CoherentFileVector[pos] = *it2;
491       else
492       {
493          gdcmWarningMacro( "At least 2 files with same position. No PositionPatientOrdering sort performed");
494          return false;
495       }
496    }
497
498    fileList->clear();  // doesn't delete list elements, only nodes
499
500    if (DirectOrder)
501    {  
502       //VC++ don't understand what scope is !! it -> it3
503       for (FileVector::const_iterator it3  = CoherentFileVector.begin();
504            it3 != CoherentFileVector.end(); ++it3)
505       {
506          fileList->push_back( *it3 );
507       }
508    }
509    else // user asked for reverse order
510    {
511       FileVector::const_iterator it4;
512       it4 = CoherentFileVector.end();
513       do
514       {
515          it4--;
516          fileList->push_back( *it4 );
517       } while (it4 != CoherentFileVector.begin() );
518    } 
519
520    distlist.clear();
521    CoherentFileVector.clear();
522
523    return true;
524 }
525
526 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
527 {
528   return file1->GetImageNumber() < file2->GetImageNumber();
529 }
530
531 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
532 {
533   return file1->GetImageNumber() > file2->GetImageNumber();
534 }
535 /**
536  * \brief sorts the images, according to their Image Number
537  * \note Works only on bona fide files  (i.e image number is a character string
538  *                                      corresponding to an integer)
539  *             within a bona fide serie (i.e image numbers are consecutive)
540  * @param fileList Coherent File list (same Serie UID) to sort 
541  * @return false if non bona fide stuff encountered
542  */
543 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
544 {
545    int min, max, pos;
546    int n = fileList->size();
547
548    FileList::const_iterator it = fileList->begin();
549    min = max = (*it)->GetImageNumber();
550
551    for (; it != fileList->end(); ++it, ++n)
552    {
553       pos = (*it)->GetImageNumber();
554       min = (min < pos) ? min : pos;
555       max = (max > pos) ? max : pos;
556    }
557
558    // Find out if image numbers are coherent (consecutive)
559    if ( min == max || max == 0 || max >= (n+min) )
560    {
561       gdcmWarningMacro( " 'Image numbers' not coherent. No ImageNumberOrdering sort performed.");
562       return false;
563    }
564    if (DirectOrder) 
565       std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberLessThan );
566    else
567       std::sort(fileList->begin(), fileList->end(), SerieHelper::ImageNumberGreaterThan );
568
569    return true;
570 }
571
572 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
573 {
574    return file1->GetFileName() < file2->GetFileName();
575 }
576
577 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
578 {
579    return file1->GetFileName() > file2->GetFileName();
580 }
581 /**
582  * \brief sorts the images, according to their File Name
583  * @param fileList Coherent File list (same Serie UID) to sort
584  * @return false only if the header is bugged !
585  */
586 bool SerieHelper::FileNameOrdering(FileList *fileList)
587 {
588    if (DirectOrder) 
589       std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameLessThan);
590    else
591       std::sort(fileList->begin(), fileList->end(), SerieHelper::FileNameGreaterThan);
592
593    return true;
594 }
595
596 /**
597  * \brief sorts the images, according to user supplied function
598  * @param fileList Coherent File list (same Serie UID) to sort
599  * @return false only if the header is bugged !
600  */
601 bool SerieHelper::UserOrdering(FileList *fileList)
602 {
603    std::sort(fileList->begin(), fileList->end(), SerieHelper::UserLessThanFunction);
604    if (!DirectOrder) 
605    {
606       std::reverse(fileList->begin(), fileList->end());
607    }
608    return true;
609 }
610
611 //-----------------------------------------------------------------------------
612 // Print
613 /**
614  * \brief   Canonical printer.
615  */
616 void SerieHelper::Print(std::ostream &os, std::string const &indent)
617 {
618    // For all the Coherent File lists of the gdcm::Serie
619    CoherentFileListmap::iterator itl = CoherentFileListHT.begin();
620    if ( itl == CoherentFileListHT.end() )
621    {
622       gdcmWarningMacro( "No Coherent File list found" );
623       return;
624    }
625    while (itl != CoherentFileListHT.end())
626    { 
627       os << "Serie UID :[" << itl->first << "]" << std::endl;
628
629       // For all the files of a Coherent File list
630       for (FileList::iterator it =  (itl->second)->begin();
631                                   it != (itl->second)->end(); 
632                                 ++it)
633       {
634          os << indent << " --- " << (*it)->GetFileName() << std::endl;
635       }
636       ++itl;
637    }
638 }
639
640 //-----------------------------------------------------------------------------
641 } // end namespace gdcm