]> Creatis software - gdcm.git/blob - src/gdcmSerieHelper.cxx
As a side effect,
[gdcm.git] / src / gdcmSerieHelper.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSerieHelper.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/03/30 16:41:22 $
7   Version:   $Revision: 1.48 $
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 #include <map>
30 #include <stdio.h>  //for sscanf
31
32 namespace gdcm
33 {
34
35 //-----------------------------------------------------------------------------
36 // Constructor / Destructor
37 /**
38  * \brief   Constructor from a given SerieHelper
39  */
40 SerieHelper::SerieHelper()
41 {
42    m_UseSeriesDetails = false;
43    ClearAll();
44    UserLessThanFunction = 0;
45    DirectOrder = true;
46 }
47
48 /**
49  * \brief   Canonical destructor.
50  */
51 SerieHelper::~SerieHelper()
52 {
53    ClearAll();
54 }
55
56 /**
57  * \brief  Preventively, clear everything at constructor time.
58  *         ( use it at destructor time.)
59  */
60 void SerieHelper::ClearAll()
61 {
62    // For all the 'Single SerieUID' Filesets that may already exist 
63    FileList *l = GetFirstSingleSerieUIDFileSet();
64    while (l)
65    { 
66       // For all the gdcm::File of a File set
67       for (gdcm::FileList::iterator it  = l->begin();
68                                     it != l->end(); 
69                                   ++it)
70       {
71          (*it)->Delete(); // remove each entry
72       }
73       l->clear();
74       delete l;     // remove the container
75       l = GetNextSingleSerieUIDFileSet();
76    }
77    // Need to clear that too:
78    SingleSerieUIDFileSetHT.clear();
79 }
80
81 //-----------------------------------------------------------------------------
82
83 //-----------------------------------------------------------------------------
84
85 // Public
86 /**
87  * \brief add a gdcm::File to the Fileset corresponding to its Serie UID
88  * @param   filename Name of the file to deal with
89  */
90 void SerieHelper::AddFileName(std::string const &filename)
91 {
92    // Create a DICOM file
93    File *header = File::New();
94    header->SetLoadMode(LoadMode);
95    header->SetFileName( filename ); 
96    header->Load();
97
98    if ( header->IsReadable() )
99    {
100       if ( !AddFile( header ) )
101       {
102          // at least one rule was unmatched we need to deallocate the file:
103          header->Delete();
104       }
105    }
106    else
107    {
108       gdcmWarningMacro("Could not read file: " << filename );
109       header->Delete();
110    }
111 }
112
113 /**
114  * \brief add a gdcm::File to the first (and supposed to be unique) file set
115  *        of the gdcm::SerieHelper.
116  * \warning : this method should be used by aware users only!
117  *           Passing a gdcm::File* has the same effect than passing a file name!
118  * \todo : decide which one is wrong (the method, or the commentary)!
119  *           the following comment doesn't match the method :-(
120  *            User is supposed to know the files he want to deal with
121  *           and consider them they belong to the same Serie
122  *           (even if their Serie UID is different)
123  *           user will probabely OrderFileList() this list (actually, ordering
124  *           user choosen gdm::File is the sole interest of this method)
125  *           Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
126  *           vtkGdcmReader parsing twice the same files. 
127  *           *no* coherence check is performed, but those specified
128  *           by SerieHelper::AddRestriction()
129  * @param   header gdcm::File* of the file to deal with
130  * @return  true if file was added, false if file was rejected
131  */
132 bool SerieHelper::AddFile(File *header)
133 {
134    int allrules = 1;
135    // First step the user has defined a set of rules for the DICOM 
136    // he is looking for.
137    // make sure the file correspond to his set of rules:
138
139    std::string s;
140    for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
141      it2 != ExRestrictions.end();
142      ++it2)
143    {
144       const ExRule &r = *it2;
145       s = header->GetEntryString( r.group, r.elem );
146       if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
147       {
148          // Argh ! This rule is unmatched; let's just quit
149          allrules = 0;
150          break;
151       }
152    }
153
154    if ( allrules ) // all rules are respected:
155    {
156       // Allright! we have a found a DICOM that matches the user expectation. 
157       // Let's add it to the specific 'id' which by default is uid (Serie UID)
158       // but can be `refined` by user with more paramater (see AddRestriction(g,e))
159  
160       std::string id = CreateUniqueSeriesIdentifier( header );
161       // if id == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
162       // no need here to do anything special
163  
164       if ( SingleSerieUIDFileSetHT.count(id) == 0 )
165       {
166          gdcmDebugMacro(" New Serie UID :[" << id << "]");
167          // create a std::list in 'id' position
168          SingleSerieUIDFileSetHT[id] = new FileList;
169       }
170       // Current Serie UID and DICOM header seems to match add the file:
171       SingleSerieUIDFileSetHT[id]->push_back( header );
172    }
173    else
174    {
175       // one rule not matched, tell user:
176       return false;
177    }
178    return true;
179 }
180
181 /**
182  * \brief add a rule for restricting a DICOM file to be in the serie we are
183  * trying to find. For example you can select only the DICOM files from a
184  * directory which would have a particular EchoTime==4.0.
185  * This method is a user level, value is not required to be formatted as a DICOM
186  * string
187  * \todo find a trick to allow user to say if he wants the Rectrictions 
188  *       to be *ored* (and not only *anded*)
189  * @param   key  Target tag we want restrict on a given value
190  * @param value value to be checked to exclude File
191  * @param op  operator we want to use to check
192  */
193 void SerieHelper::AddRestriction(TagKey const &key, 
194                                  std::string const &value, int op)
195 {
196    ExRule r;
197    r.group = key[0];
198    r.elem  = key[1];
199    r.value = value;
200    r.op    = op;
201    ExRestrictions.push_back( r ); 
202 }
203
204 void SerieHelper::AddRestriction(TagKey const &key)
205 {
206   ExRule r;
207   r.group = key[0];
208   r.elem  = key[1];
209   ExRefine.push_back( r );
210 }
211
212 #ifndef GDCM_LEGACY_REMOVE
213 /**
214  * \brief add a rule for restricting a DICOM file to be in the serie we are
215  * trying to find. For example you can select only the DICOM files from a
216  * directory which would have a particular EchoTime==4.0.
217  * This method is a user level, value is not required to be formatted as a DICOM
218  * string
219  * @param   group tag group number we want restrict on a given value
220  * @param   elem  tag element number we want restrict on a given value 
221  * @param value value to be checked to exclude File
222  * @param op  operator we want to use to check
223  * @deprecated use : AddRestriction(TagKey const &key, 
224  *                                 std::string const &value, int op);
225  */
226 void SerieHelper::AddRestriction(uint16_t group, uint16_t elem, 
227                                  std::string const &value, int op)
228 {
229   TagKey t(group, elem);
230   AddRestriction(t, value, op);
231 }
232 #endif
233
234 /**
235  * \brief add an extra  'SerieDetail' for building a 'Serie Identifier'
236  *        that ensures (hope so) File constistency (Series Instance UID doesn't.
237  * @param   group tag group number we want restrict on a given value
238  * @param   elem  tag element number we want restrict on a given value
239  * @param  convert wether we want 'convertion', to allow further ordering
240  *         e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK 
241  */
242 void SerieHelper::AddSeriesDetail(uint16_t group, uint16_t elem, bool convert)
243 {
244    
245    ExDetail d;
246    d.group   = group;
247    d.elem    = elem;
248    d.convert = convert;
249    ExDetails.push_back( d ); 
250 }
251 /**
252  * \brief Sets the root Directory
253  * @param   dir Name of the directory to deal with
254  * @param recursive whether we want explore recursively the root Directory
255  */
256 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
257 {
258    DirList dirList(dir, recursive); // OS specific
259   
260    DirListType filenames_list = dirList.GetFilenames();
261    for( DirListType::const_iterator it = filenames_list.begin(); 
262         it != filenames_list.end(); ++it)
263    {
264       AddFileName( *it );
265    }
266 }
267
268 /**
269  * \brief Sorts the given Fileset
270  * \warning This could be implemented in a 'Strategy Pattern' approach
271  *          But as I don't know how to do it, I leave it this way
272  *          BTW, this is also a Strategy, I don't know this is 
273  *          the best approach :)
274  */
275 void SerieHelper::OrderFileList(FileList *fileSet)
276 {
277
278    if ( SerieHelper::UserLessThanFunction )
279    {
280       UserOrdering( fileSet );
281       return; 
282    }
283    else if ( ImagePositionPatientOrdering( fileSet ) )
284    {
285       return ;
286    }
287    else if ( ImageNumberOrdering(fileSet ) )
288    {
289       return ;
290    }
291    else  
292    {
293       FileNameOrdering(fileSet );
294    }
295 }
296
297 /**
298  * \brief Elementary coherence checking of the files with the same Serie UID
299  * Only sizes and pixel type are checked right now ...
300  */ 
301 bool SerieHelper::IsCoherent(FileList *fileSet)
302 {
303    if(fileSet->size() == 1)
304    return true;
305
306    FileList::const_iterator it = fileSet->begin();
307
308    int nX =               (*it)->GetXSize();
309    int nY =               (*it)->GetYSize();
310    int pixelSize =        (*it)->GetPixelSize();
311    bool signedPixelData = (*it)->IsSignedPixelData();
312    it ++;
313    for ( ;
314          it != fileSet->end();
315        ++it)
316    {
317       if ( (*it)->GetXSize() != nX )
318          return false;
319       if ( (*it)->GetYSize() != nY )
320          return false;
321       if ( (*it)->GetPixelSize() != pixelSize )
322          return false;
323       if ( (*it)->IsSignedPixelData() != signedPixelData )
324          return false;
325       // probabely more is to be checked (?)
326    }
327    return true;
328 }
329
330 #ifndef GDCM_LEGACY_REMOVE
331 /**
332  * \brief   accessor (DEPRECATED :  use GetFirstSingleSerieUIDFileSet )
333  *          Warning : 'coherent' means here they have the same Serie UID
334  * @return  The first FileList if found, otherwhise NULL
335  */
336 FileList *SerieHelper::GetFirstCoherentFileList()
337 {
338    ItFileSetHt = SingleSerieUIDFileSetHT.begin();
339    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
340       return ItFileSetHt->second;
341    return NULL;
342 }
343
344 /**
345  * \brief   accessor (DEPRECATED :  use GetNextSingleSerieUIDFileSet )
346  *          Warning : 'coherent' means here they have the same Serie UID
347  * \note : meaningfull only if GetFirstCoherentFileList() already called 
348  * @return  The next FileList if found, otherwhise NULL
349  */
350 FileList *SerieHelper::GetNextCoherentFileList()
351 {
352    gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
353   
354    ++ItFileSetHt;
355    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
356       return ItFileSetHt->second;
357    return NULL;
358 }
359
360 /**
361  * \brief   accessor (DEPRECATED :  use GetSingleSerieUIDFileSet )
362   *          Warning : 'coherent' means here they have the same Serie UID
363  * @param SerieUID SerieUID
364  * \return  pointer to the FileList if found, otherwhise NULL
365  */
366 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
367 {
368    if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
369       return 0;     
370    return SingleSerieUIDFileSetHT[SerieUID];
371 }
372 #endif
373
374
375 /**
376  * \brief   Get the first Fileset while visiting the SingleSerieUIDFileSetmap
377  * @return  The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
378  */
379 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
380 {
381    ItFileSetHt = SingleSerieUIDFileSetHT.begin();
382    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
383       return ItFileSetHt->second;
384    return NULL;
385 }
386
387 /**
388  * \brief   Get the next Fileset while visiting the SingleSerieUIDFileSetmap
389  * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called 
390  * @return  The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
391  */
392 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
393 {
394    gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
395   
396    ++ItFileSetHt;
397    if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
398       return ItFileSetHt->second;
399    return NULL;
400 }
401
402 /**
403  * \brief   Get the SingleSerieUIDFileSet according to its Serie UID
404  * @param SerieUID SerieUID to retrieve
405  * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
406  */
407 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
408 {
409    if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
410       return 0;     
411    return SingleSerieUIDFileSetHT[SerieUID];
412 }
413
414 /**
415  * \brief   Splits a Single SerieUID Fileset according to the Orientations
416  * @param fileSet File Set to be splitted
417  * \return  std::map of 'Xcoherent' File sets
418  */
419
420 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
421 {
422    XCoherentFileSetmap CoherentFileSet;
423
424    int nb = fileSet->size();
425    if (nb == 0 )
426       return CoherentFileSet;
427    float iop[6];
428    std::string strOrient;
429    std::ostringstream ossOrient;
430
431    FileList::const_iterator it = fileSet->begin();
432    it ++;
433    for ( ;
434          it != fileSet->end();
435        ++it)
436    {     
437       // Information is in :      
438       // 0020 0037 : Image Orientation (Patient) or
439       // 0020 0035 : Image Orientation (RET)
440
441       // Let's build again the 'cosines' string, to be sure of it's format      
442       (*it)->GetImageOrientationPatient(iop);
443
444       ossOrient << iop[0];      
445       for (int i = 1; i < 6; i++)
446       {
447         ossOrient << "\\";
448         ossOrient << iop[i]; 
449       }      
450       strOrient = ossOrient.str();
451       ossOrient.str("");
452       if ( CoherentFileSet.count(strOrient) == 0 )
453       {
454          gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
455          // create a File set in 'orientation' position
456          CoherentFileSet[strOrient] = new FileList;
457       }
458       // Current Orientation and DICOM header match; add the file:
459       CoherentFileSet[strOrient]->push_back( (*it) );
460    }
461    return CoherentFileSet;
462 }
463
464 /**
465  * \brief   Splits a 'Single SerieUID' Fileset according to the Positions
466  * @param fileSet File Set to be splitted
467  * \return  std::map of 'Xcoherent' File sets
468  */
469
470 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
471 {
472    XCoherentFileSetmap CoherentFileSet;
473
474    int nb = fileSet->size();
475    if (nb == 0 )
476       return CoherentFileSet;
477    float pos[3];
478    std::string strImPos;  // read on disc
479    std::ostringstream ossPosition;
480    std::string strPosition; // re computed
481    FileList::const_iterator it = fileSet->begin();
482    it ++;
483    for ( ;
484          it != fileSet->end();
485        ++it)
486    {     
487       // Information is in :      
488       // 0020,0032 : Image Position Patient
489       // 0020,0030 : Image Position (RET)
490
491       strImPos = (*it)->GetEntryString(0x0020,0x0032);
492       if ( strImPos == GDCM_UNFOUND)
493       {
494          gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
495          strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
496          if ( strImPos == GDCM_UNFOUND )
497          {
498             gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
499             // User wants to split on the 'Position'
500             // No 'Position' info found.
501             // We return an empty Htable !
502             return CoherentFileSet;
503          }  
504       }
505
506       if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", 
507                                               &pos[0], &pos[1], &pos[2]) != 3 )
508       {
509             gdcmWarningMacro( "Wrong number for Position : ["
510                        << strImPos << "]" );
511              return CoherentFileSet;
512       }
513
514       // Let's build again the 'position' string, to be sure of it's format      
515
516       ossPosition << pos[0];      
517       for (int i = 1; i < 3; i++)
518       {
519         ossPosition << "\\";
520         ossPosition << pos[i]; 
521       }      
522       strPosition = ossPosition.str();
523       ossPosition.str("");
524
525       if ( CoherentFileSet.count(strPosition) == 0 )
526       {
527          gdcmDebugMacro(" New Position :[" << strPosition << "]");
528          // create a File set in 'position' position
529          CoherentFileSet[strPosition] = new FileList;
530       }
531       // Current Position and DICOM header match; add the file:
532       CoherentFileSet[strPosition]->push_back( (*it) );
533    }   
534    return CoherentFileSet;
535 }
536
537 /**
538  * \brief   Splits a 'Single SerieUID' File set Coherent according to the
539  *          value of a given Tag
540  * @param fileSet File Set to be splitted
541  * @param   group  group number of the target Element
542  * @param   elem element number of the target Element
543  * \return  std::map of 'Xcoherent' File sets
544  */
545
546 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet, 
547                                                uint16_t group, uint16_t element)
548 {
549    XCoherentFileSetmap CoherentFileSet;
550
551    int nb = fileSet->size();
552    if (nb == 0 )
553       return CoherentFileSet;
554
555    std::string strTagValue;  // read on disc
556
557    FileList::const_iterator it = fileSet->begin();
558    it ++;
559    for ( ;
560          it != fileSet->end();
561        ++it)
562    {     
563       // Information is in :      
564       // 0020,0032 : Image Position Patient
565       // 0020,0030 : Image Position (RET)
566
567       strTagValue = (*it)->GetEntryString(group,element);
568       
569       if ( CoherentFileSet.count(strTagValue) == 0 )
570       {
571          gdcmDebugMacro(" New Tag Value :[" << strTagValue << "]");
572          // create a File set in 'position' position
573          CoherentFileSet[strTagValue] = new FileList;
574       }
575       // Current Tag value and DICOM header match; add the file:
576       CoherentFileSet[strTagValue]->push_back( (*it) );
577    }
578    return CoherentFileSet;
579 }
580
581 //-----------------------------------------------------------------------------
582 // Protected
583
584 //-----------------------------------------------------------------------------
585 // Private
586 /**
587  * \brief sorts the images, according to their Patient Position.
588  *  As a side effect, it computes the ZSpacing, according to Jolinda Smith'
589  *  algorithm. (get it with double GetZSpacing() !)
590  *  We may order, considering :
591  *   -# Image Position Patient
592  *   -# Image Number
593  *   -# file name
594  *   -# More to come :-)
595  * \note : FileList = std::vector<File* >
596  * @param fileList Coherent File list (same Serie UID) to sort
597  * @return false only if the header is bugged !
598  */
599 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
600 //based on Jolinda Smith's algorithm
601 {
602 gdcmDebugMacro( "In ImagePositionPatientOrdering()" << std::endl );
603 std::cout << "In ImagePositionPatientOrdering()" << std::endl;
604 //Tags always use the same coordinate system, where "x" is left
605 //to right, "y" is posterior to anterior, and "z" is foot to head (RAH).
606
607    //iop is calculated based on the file file
608    float cosines[6];
609    double normal[3];
610    double ipp[3];
611    double dist;
612    double min = 0, max = 0;
613    bool first = true;
614    ZSpacing = -1.0;  // will be updated if process doesn't fail
615
616    std::multimap<double,File *> distmultimap;
617    // Use a multimap to sort the distances from 0,0,0
618    for ( FileList::const_iterator 
619          it = fileList->begin();
620          it != fileList->end(); ++it )
621    {
622       if ( first ) 
623       {
624          (*it)->GetImageOrientationPatient( cosines );
625
626    // The "Image Orientation Patient" tag gives the direction cosines 
627    // for the rows and columns for the three axes defined above. 
628    // Typical axial slices will have a value 1/0/0/0/1/0: 
629    // rows increase from left to right, 
630    // columns increase from posterior to anterior. This is your everyday
631    // "looking up from the bottom of the head with the eyeballs up" image. 
632    
633    // The "Image Position Patient" tag gives the coordinates of the first
634    // voxel in the image in the "RAH" coordinate system, relative to some
635    // origin.   
636
637    // First, calculate the slice normal from IOP : 
638           
639          // You only have to do this once for all slices in the volume. Next, 
640          // for each slice, calculate the distance along the slice normal 
641          // using the IPP ("Image Position Patient") tag.
642          // ("dist" is initialized to zero before reading the first slice) :
643          normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
644          normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
645          normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
646
647    // For each slice (here : the first), calculate the distance along 
648    // the slice normal using the IPP tag 
649     
650          ipp[0] = (*it)->GetXOrigin();
651          ipp[1] = (*it)->GetYOrigin();
652          ipp[2] = (*it)->GetZOrigin();
653
654          dist = 0;
655          for ( int i = 0; i < 3; ++i )
656          {
657             dist += normal[i]*ipp[i];
658          }
659     
660          distmultimap.insert(std::pair<const double,File *>(dist, *it));
661
662          max = min = dist;
663          first = false;
664       }
665       else 
666       {
667    // Next, for each slice, calculate the distance along the slice normal
668    // using the IPP tag 
669          ipp[0] = (*it)->GetXOrigin();
670          ipp[1] = (*it)->GetYOrigin();
671          ipp[2] = (*it)->GetZOrigin();
672
673          dist = 0;
674          for ( int i = 0; i < 3; ++i )
675          {
676             dist += normal[i]*ipp[i];
677          }
678
679          distmultimap.insert(std::pair<const double,File *>(dist, *it));
680
681          min = (min < dist) ? min : dist;
682          max = (max > dist) ? max : dist;
683       }
684    }
685
686    // Find out if min/max are coherent
687    if ( min == max )
688    {
689      gdcmWarningMacro("Looks like all images have the exact same image position"
690                       << ". No PositionPatientOrdering sort performed" );
691      return false;
692    }
693
694    // Check to see if image shares a common position
695    bool ok = true;
696    for (std::multimap<double, File *>::iterator it2 = distmultimap.begin();
697         it2 != distmultimap.end();
698         ++it2)
699    {
700       if (distmultimap.count((*it2).first) != 1)
701       {
702          gdcmErrorMacro("File: "
703               << ((*it2).second->GetFileName())
704               << " Distance: "
705               << (*it2).first
706               << " position is not unique");
707
708          ok = false;
709       }
710    }
711    if (!ok)
712    {
713       return false;
714    }
715
716 // Now, we could calculate Z Spacing as the difference
717 // between the "dist" values for the first two slices.
718
719 // The following (un)-commented out code is let here
720 // to be re-used by whomsoever is interested...
721
722     std::multimap<double, File *>::iterator it5 = distmultimap.begin();
723     double d1 = (*it5).first;
724     it5++;
725     double d2 = (*it5).first;
726     ZSpacing = d1-d2;
727     if (ZSpacing < 0.0)
728        ZSpacing = - ZSpacing;
729
730    fileList->clear();  // doesn't delete list elements, only nodes
731
732 // Acording to user requierement, we sort direct order or reverse order.
733    if (DirectOrder)
734    {  
735       for (std::multimap<double, File *>::iterator it3 = distmultimap.begin();
736            it3 != distmultimap.end();
737            ++it3)
738       {
739          fileList->push_back( (*it3).second );
740       }
741    }
742    else // user asked for reverse order
743    {
744       std::multimap<double, File *>::const_iterator it4;
745       it4 = distmultimap.end();
746       do
747       {
748          it4--;
749          fileList->push_back( (*it4).second );
750       } while (it4 != distmultimap.begin() );
751    }
752
753    distmultimap.clear();
754
755    return true;
756 }
757
758 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
759 {
760   return file1->GetImageNumber() < file2->GetImageNumber();
761 }
762
763 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
764 {
765   return file1->GetImageNumber() > file2->GetImageNumber();
766 }
767
768 /**
769  * \brief sorts the images, according to their Image Number
770  * \note Works only on bona fide files  (i.e image number is a character string
771  *                                      corresponding to an integer)
772  *             within a bona fide serie (i.e image numbers are consecutive)
773  * @param fileList File set (same Serie UID) to sort 
774  * @return false if non bona fide stuff encountered
775  */
776 bool SerieHelper::ImageNumberOrdering(FileList *fileList) 
777 {
778    int min, max, pos;
779    int n = fileList->size();
780
781    FileList::const_iterator it = fileList->begin();
782    min = max = (*it)->GetImageNumber();
783
784    for (; it != fileList->end(); ++it, ++n)
785    {
786       pos = (*it)->GetImageNumber();
787       min = (min < pos) ? min : pos;
788       max = (max > pos) ? max : pos;
789    }
790
791    // Find out if image numbers are coherent (consecutive)
792    if ( min == max || max == 0 || max >= (n+min) )
793    {
794       gdcmWarningMacro( " 'Image numbers' not coherent. "
795                         << " No ImageNumberOrdering sort performed.");
796       return false;
797    }
798    if (DirectOrder)
799       Sort(fileList,SerieHelper::ImageNumberLessThan);
800    else
801       Sort(fileList,SerieHelper::ImageNumberGreaterThan);
802
803    return true;
804 }
805
806 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
807 {
808    return file1->GetFileName() < file2->GetFileName();
809 }
810
811 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
812 {
813    return file1->GetFileName() > file2->GetFileName();
814 }
815 /**
816  * \brief sorts the images, according to their File Name
817  * @param fileList Coherent File list (same Serie UID) to sort
818  * @return false only if the header is bugged !
819  */
820 bool SerieHelper::FileNameOrdering(FileList *fileList)
821 {
822    if (DirectOrder) 
823       Sort(fileList,SerieHelper::FileNameLessThan);
824    else
825       Sort(fileList,SerieHelper::FileNameGreaterThan);   
826
827    return true;
828 }
829
830 /**
831  * \brief sorts the images, according to user supplied function
832  * @param fileList Coherent File list (same Serie UID) to sort
833  * @return false only if the header is bugged !
834  */
835 bool SerieHelper::UserOrdering(FileList *fileList)
836 {
837    Sort(fileList,SerieHelper::UserLessThanFunction);   
838    if (!DirectOrder) 
839    {
840       std::reverse(fileList->begin(), fileList->end());
841    }
842    return true;
843 }
844
845 //-----------------------------------------------------------------------------
846 // Print
847 /**
848  * \brief   Canonical printer.
849  */
850 void SerieHelper::Print(std::ostream &os, std::string const &indent)
851 {
852    // For all the Coherent File lists of the gdcm::Serie
853    SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
854    if ( itl == SingleSerieUIDFileSetHT.end() )
855    {
856       gdcmWarningMacro( "No SingleSerieUID File set found" );
857       return;
858    }
859    while (itl != SingleSerieUIDFileSetHT.end())
860    { 
861       os << "Serie UID :[" << itl->first << "]" << std::endl;
862
863       // For all the files of a SingleSerieUID File set
864       for (FileList::iterator it =  (itl->second)->begin();
865                                   it != (itl->second)->end(); 
866                                 ++it)
867       {
868          os << indent << " --- " << (*it)->GetFileName() << std::endl;
869       }
870       ++itl;
871    }
872 }
873
874 void SerieHelper::CreateDefaultUniqueSeriesIdentifier()
875 {
876    // If the user requests, additional information can be appended
877    // to the SeriesUID to further differentiate volumes in the DICOM
878    // objects being processed.
879  
880    // 0020 0011 Series Number
881    // A scout scan prior to a CT volume scan can share the same
882    //   SeriesUID, but they will sometimes have a different Series Number
883    AddRestriction( TagKey(0x0020, 0x0011) );
884    // 0018 0024 Sequence Name
885    // For T1-map and phase-contrast MRA, the different flip angles and
886    //   directions are only distinguished by the Sequence Name
887    AddRestriction( TagKey(0x0018, 0x0024) );
888    // 0018 0050 Slice Thickness
889    // On some CT systems, scout scans and subsequence volume scans will
890    //   have the same SeriesUID and Series Number - YET the slice 
891    //   thickness will differ from the scout slice and the volume slices.
892    AddRestriction( TagKey(0x0018, 0x0050));
893    // 0028 0010 Rows
894    // If the 2D images in a sequence don't have the same number of rows,
895    // then it is difficult to reconstruct them into a 3D volume.
896    AddRestriction( TagKey(0x0028, 0x0010));
897    // 0028 0011 Columns
898    // If the 2D images in a sequence don't have the same number of columns,
899    // then it is difficult to reconstruct them into a 3D volume.
900    AddRestriction( TagKey(0x0028, 0x0011));
901 }
902
903 /**
904  * \brief Heuristics to *try* to build a Serie Identifier that would ensure
905  *        all the images are coherent.
906  *
907  * By default, uses the SeriesUID.  If UseSeriesDetails(true) has been called,
908  *         then additional identifying information is used.
909  *  We allow user to add his own critierions, using AddSeriesDetail
910  *        (he knows more than we do about his images!)
911  *        ex : in tagging series, the only pertnent tag is
912  *        0018|1312 [In-plane Phase Encoding Direction] value : ROW/COLUMN
913  * @param inFile gdcm::File we want to build a Serie Identifier for.
914  * @return the SeriesIdentifier
915  */
916 std::string SerieHelper::CreateUniqueSeriesIdentifier( File *inFile )
917 {
918    if( inFile->IsReadable() )
919    {
920     // 0020 000e UI REL Series Instance UID
921     std::string uid = inFile->GetEntryString (0x0020, 0x000e);
922     std::string id = uid.c_str();
923     if(m_UseSeriesDetails)
924       {
925       for(SerieExRestrictions::iterator it2 = ExRefine.begin();
926         it2 != ExRefine.end();
927         ++it2)
928         {
929         const ExRule &r = *it2;
930         std::string s = inFile->GetEntryString( r.group, r.elem );
931         if( s == gdcm::GDCM_UNFOUND )
932           {
933           s = "";
934           }
935         if( id == uid && !s.empty() )
936           {
937           id += "."; // add separator
938           }
939         id += s;
940         }
941       }
942     // Eliminate non-alnum characters, including whitespace...
943     //   that may have been introduced by concats.
944     for(unsigned int i=0; i<id.size(); i++)
945       {
946       while(i<id.size() 
947         && !( id[i] == '.'
948           || (id[i] >= 'a' && id[i] <= 'z')
949           || (id[i] >= '0' && id[i] <= '9')
950           || (id[i] >= 'A' && id[i] <= 'Z')))
951         {
952         id.erase(i, 1);
953         }
954       }
955     return id;
956     }
957   else // Could not open inFile
958     {
959     gdcmWarningMacro("Could not parse series info.");
960     std::string id = gdcm::GDCM_UNFOUND;
961     return id;
962     }
963 }
964
965 /**
966  * \brief Allow user to build is own File Identifier (to be able to sort
967  *        temporal series just as he wants)
968  *        Criterions will be set with AddSeriesDetail.
969  *        (Maybe the method should be moved elsewhere 
970  *       -File class? FileHelper class?-
971  * @return FileIdentifier (Tokenizable on '%%%'. Hope it's enough !)
972  */
973 std::string SerieHelper::CreateUserDefinedFileIdentifier( File * inFile )
974 {
975   //     Deal with all user supplied tags.
976   //      (user knows more than we do about his images!)
977   
978    double converted;
979    std::string id;
980    std::string s; 
981    char charConverted[17]; 
982    
983    for(SeriesExDetails::iterator it2 = ExDetails.begin();
984       it2 != ExDetails.end();
985       ++it2)
986    {
987       const ExDetail &r = *it2;
988       s = inFile->GetEntryString( r.group, r.elem );
989
990       // User is allowed to ask 'convertion', to allow further ordering
991       // e.g : 100 would be *before* 20; 000020.00 vs 00100.00 : OK
992       if (it2->convert)
993       {
994          if ( s != GDCM_UNFOUND) // Don't convert unfound fields !
995          {
996             converted = atof(s.c_str());
997             // probabely something much more complicated is possible, 
998             // using C++ features
999             /// \todo check the behaviour when there are >0 and <0 numbers
1000             sprintf(charConverted, "%016.6f",converted);
1001             s = charConverted;
1002          }
1003       }
1004       // Eliminate non-alphanum characters, including whitespace.
1005       for(unsigned int i=0; i<s.size(); i++)
1006       {
1007          while(i<s.size()
1008             && !( s[i] == '.' || s[i] == '%'
1009                     || (s[i] >= 'a' && s[i] <= 'z')
1010                     || (s[i] >= '0' && s[i] <= '9')
1011                     || (s[i] >= 'A' && s[i] <= 'Z')))
1012          {
1013             s.erase(i, 1);
1014          }
1015       }
1016       
1017       id += s.c_str();
1018       id += "%%%"; // make the FileIdentifier Tokenizable
1019    }
1020    
1021    return id;             
1022 }
1023
1024 //-----------------------------------------------------------------------------
1025 // Sort
1026 /**
1027  * \brief   Sort FileList.
1028  */
1029 void SerieHelper::Sort(FileList *fileList, bool (*pt2Func)( File *file1, File *file2) )
1030 {
1031  std::sort(fileList->begin(), fileList->end(), pt2Func );
1032 }
1033
1034 //-----------------------------------------------------------------------------
1035 } // end namespace gdcm