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