1 /*=========================================================================
4 Module: $RCSfile: gdcmSerieHelper.cxx,v $
6 Date: $Date: 2005/11/28 11:54:51 $
7 Version: $Revision: 1.37 $
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.
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.
17 =========================================================================*/
19 #include "gdcmSerieHelper.h"
20 #include "gdcmDirList.h"
22 #include "gdcmDictEntry.h" // for TranslateToKey
23 #include "gdcmDebug.h"
30 #include <stdio.h> //for sscanf
34 //-----------------------------------------------------------------------------
36 //-----------------------------------------------------------------------------
37 // Constructor / Destructor
39 * \brief Constructor from a given SerieHelper
41 SerieHelper::SerieHelper()
43 m_UseSeriesDetails = false;
45 UserLessThanFunction = 0;
50 * \brief Canonical destructor.
52 SerieHelper::~SerieHelper()
58 * \brief Preventively, clear everything at constructor time.
59 * ( use it at destructor time.)
61 void SerieHelper::ClearAll()
63 // For all the 'Single SerieUID' Filesets that may already exist
64 FileList *l = GetFirstSingleSerieUIDFileSet();
67 // For all the gdcm::File of a File set
68 for (gdcm::FileList::iterator it = l->begin();
72 (*it)->Delete(); // remove each entry
75 delete l; // remove the container
76 l = GetNextSingleSerieUIDFileSet();
80 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
86 * \brief add a gdcm::File to the Fileset corresponding to its Serie UID
87 * @param filename Name of the file to deal with
89 void SerieHelper::AddFileName(std::string const &filename)
91 // Create a DICOM file
92 File *header = File::New();
93 header->SetLoadMode(LoadMode);
94 header->SetFileName( filename );
97 if ( header->IsReadable() )
100 // First step : the user defined a set of rules for the DICOM file
101 // he is looking for.
102 // Make sure the file corresponds to his set of rules:
105 for(SerieExRestrictions::iterator it2 = ExRestrictions.begin();
106 it2 != ExRestrictions.end();
109 const ExRule &r = *it2;
110 s = header->GetEntryString( r.group, r.elem );
111 if ( !Util::CompareDicomString(s, r.value.c_str(), r.op) )
113 // Argh ! This rule is unmatched; let's just quit
120 if ( allrules ) // all rules are respected:
122 // Allright! we have a found a DICOM that matches the user expectation.
125 // 0020 000e UI REL Series Instance UID
126 const std::string &uid = header->GetEntryString(0x0020, 0x000e);
127 // if uid == GDCM_UNFOUND then consistently we should find GDCM_UNFOUND
128 // no need here to do anything special
131 if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
133 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
134 // create a std::list in 'uid' position
135 SingleSerieUIDFileSetHT[uid] = new FileList;
137 // Current Serie UID and DICOM header seems to match; add the file:
138 SingleSerieUIDFileSetHT[uid]->push_back( header );
142 // at least one rule was unmatched we need to deallocate the file:
148 gdcmWarningMacro("Could not read file: " << filename );
154 * \brief add a gdcm::File to the first (and supposed to be unique) file set
155 * of the gdcm::SerieHelper.
156 * \warning : this method should be used by aware users only!
157 * Passing a gdcm::File* has the same effect than passing a file name!
158 * \todo : decide which one is wrong (the method, or the commentary)!
159 * the following comment doesn't match the method :-(
160 * User is supposed to know the files he want to deal with
161 * and consider them they belong to the same Serie
162 * (even if their Serie UID is different)
163 * user will probabely OrderFileList() this list (actually, ordering
164 * user choosen gdm::File is the sole interest of this method)
165 * Moreover, using vtkGdcmReader::SetCoherentFileList() will avoid
166 * vtkGdcmReader parsing twice the same files.
167 * *no* coherence check is performed, but those specified
168 * by SerieHelper::AddRestriction()
169 * @param header gdcm::File* of the file to deal with
171 void SerieHelper::AddGdcmFile(File *header)
174 // First step the user has defined a set of rules for the DICOM
175 // he is looking for.
176 // make sure the file correspond to his set of rules:
177 for(SerieRestrictions::iterator it = Restrictions.begin();
178 it != Restrictions.end();
182 const std::string s;// = header->GetEntryString( r.first );
183 if ( !Util::DicomStringEqual(s, r.second.c_str()) )
185 // Argh ! This rule is unmatch let's just quit
190 if ( allrules ) // all rules are respected:
192 // Allright ! we have a found a DICOM that match the user expectation.
195 const std::string &uid = "0";
196 // Serie UID of the gdcm::File* may be different.
197 // User is supposed to know what he wants
199 if ( SingleSerieUIDFileSetHT.count(uid) == 0 )
201 gdcmDebugMacro(" New Serie UID :[" << uid << "]");
202 // create a std::list in 'uid' position
203 SingleSerieUIDFileSetHT[uid] = new FileList;
205 // Current Serie UID and DICOM header seems to match; add the file:
206 SingleSerieUIDFileSetHT[uid]->push_back( header );
208 // Even if a rule was unmatch we don't deallocate the gdcm::File:
212 * \brief add a rules for restricting a DICOM file to be in the serie we are
213 * trying to find. For example you can select only the DICOM file from a
214 * directory which would have a particular EchoTime==4.0.
215 * This method is a user level, value is not required to be formatted as a DICOM
217 * @param key Target tag we want restrict on a given value
218 * @param value value to be checked to exclude File
219 * @param op operator we want to use to check
221 void SerieHelper::AddRestriction(TagKey const &key,
222 std::string const &value, int op)
229 ExRestrictions.push_back( r );
233 * \brief Sets the root Directory
234 * @param dir Name of the directory to deal with
235 * @param recursive whether we want explore recursively the root Directory
237 void SerieHelper::SetDirectory(std::string const &dir, bool recursive)
239 DirList dirList(dir, recursive); // OS specific
241 DirListType filenames_list = dirList.GetFilenames();
242 for( DirListType::const_iterator it = filenames_list.begin();
243 it != filenames_list.end(); ++it)
250 * \brief Sorts the given Fileset
251 * \warning This could be implemented in a 'Strategy Pattern' approach
252 * But as I don't know how to do it, I leave it this way
253 * BTW, this is also a Strategy, I don't know this is
254 * the best approach :)
256 void SerieHelper::OrderFileList(FileList *fileSet)
259 if ( SerieHelper::UserLessThanFunction )
261 UserOrdering( fileSet );
264 else if ( ImagePositionPatientOrdering( fileSet ) )
268 else if ( ImageNumberOrdering(fileSet ) )
274 FileNameOrdering(fileSet );
279 * \brief Elementary coherence checking of the files with the same Serie UID
280 * Only sizes and pixel type are checked right now ...
282 bool SerieHelper::IsCoherent(FileList *fileSet)
284 if(fileSet->size() == 1)
287 FileList::const_iterator it = fileSet->begin();
289 int nX = (*it)->GetXSize();
290 int nY = (*it)->GetYSize();
291 int pixelSize = (*it)->GetPixelSize();
292 bool signedPixelData = (*it)->IsSignedPixelData();
295 it != fileSet->end();
298 if ( (*it)->GetXSize() != nX )
300 if ( (*it)->GetYSize() != nY )
302 if ( (*it)->GetPixelSize() != pixelSize )
304 if ( (*it)->IsSignedPixelData() != signedPixelData )
306 // probabely more is to be checked (?)
311 #ifndef GDCM_LEGACY_REMOVE
313 FileList *SerieHelper::GetFirstCoherentFileList()
315 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
316 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
317 return ItFileSetHt->second;
322 FileList *SerieHelper::GetNextCoherentFileList()
324 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
327 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
328 return ItFileSetHt->second;
333 FileList *SerieHelper::GetCoherentFileList(std::string SerieUID)
335 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
337 return SingleSerieUIDFileSetHT[SerieUID];
343 * \brief Get the first Fileset while visiting the SingleSerieUIDFileSetmap
344 * @return The first FileList (SingleSerieUIDFileSet) if found, otherwhise 0
346 FileList *SerieHelper::GetFirstSingleSerieUIDFileSet()
348 ItFileSetHt = SingleSerieUIDFileSetHT.begin();
349 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
350 return ItFileSetHt->second;
355 * \brief Get the next Fileset while visiting the SingleSerieUIDFileSetmap
356 * \note : meaningfull only if GetNextSingleSerieUIDFileSet() already called
357 * @return The next FileList (SingleSerieUIDFileSet) if found, otherwhise 0
359 FileList *SerieHelper::GetNextSingleSerieUIDFileSet()
361 gdcmAssertMacro (ItFileSetHt != SingleSerieUIDFileSetHT.end());
364 if ( ItFileSetHt != SingleSerieUIDFileSetHT.end() )
365 return ItFileSetHt->second;
370 * \brief Get the SingleSerieUIDFileSet according to its Serie UID
371 * @param SerieUID SerieUID to retrieve
372 * \return pointer to the FileList (SingleSerieUIDFileSet) if found, otherwhise 0
374 FileList *SerieHelper::GetSingleSerieUIDFileSet(std::string SerieUID)
376 if ( SingleSerieUIDFileSetHT.count(SerieUID) == 0 )
378 return SingleSerieUIDFileSetHT[SerieUID];
382 * \brief Splits a Single SerieUID Fileset according to the Orientations
383 * @param fileSet File Set to be splitted
384 * \return std::map of 'Xcoherent' File sets
387 XCoherentFileSetmap SerieHelper::SplitOnOrientation(FileList *fileSet)
389 XCoherentFileSetmap CoherentFileSet;
391 int nb = fileSet->size();
393 return CoherentFileSet;
396 std::string strOrient;
397 std::ostringstream ossOrient;
398 FileList::const_iterator it = fileSet->begin();
401 it != fileSet->end();
404 // Information is in :
405 // 0020 0037 : Image Orientation (Patient) or
406 // 0020 0035 : Image Orientation (RET)
408 // Let's build again the 'cosines' string, to be sure of it's format
409 (*it)->GetImageOrientationPatient(iop);
412 for (int i = 1; i < 6; i++)
417 strOrient = ossOrient.str();
419 // FIXME : is it a 'cleaner' way to initialize an ostringstream?
421 if ( CoherentFileSet.count(strOrient) == 0 )
423 gdcmDebugMacro(" New Orientation :[" << strOrient << "]");
424 // create a File set in 'orientation' position
425 CoherentFileSet[strOrient] = new FileList;
427 // Current Orientation and DICOM header match; add the file:
428 CoherentFileSet[strOrient]->push_back( (*it) );
430 return CoherentFileSet;
434 * \brief Splits a 'Single SerieUID' Fileset according to the Positions
435 * @param fileSet File Set to be splitted
436 * \return std::map of 'Xcoherent' File sets
439 XCoherentFileSetmap SerieHelper::SplitOnPosition(FileList *fileSet)
441 XCoherentFileSetmap CoherentFileSet;
443 int nb = fileSet->size();
445 return CoherentFileSet;
447 std::string strImPos; // read on disc
448 std::ostringstream ossPosition;
449 std::string strPosition; // re computed
450 FileList::const_iterator it = fileSet->begin();
453 it != fileSet->end();
456 // Information is in :
457 // 0020,0032 : Image Position Patient
458 // 0020,0030 : Image Position (RET)
460 strImPos = (*it)->GetEntryString(0x0020,0x0032);
461 if ( strImPos == GDCM_UNFOUND)
463 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
464 strImPos = (*it)->GetEntryString(0x0020,0x0030); // For ACR-NEMA images
465 if ( strImPos == GDCM_UNFOUND )
467 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
468 // User wants to split on the 'Position'
469 // No 'Position' info found.
470 // We return an empty Htable !
471 return CoherentFileSet;
475 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ",
476 &pos[0], &pos[1], &pos[2]) != 3 )
478 gdcmWarningMacro( "Wrong number for Position : ["
479 << strImPos << "]" );
480 return CoherentFileSet;
483 // Let's build again the 'position' string, to be sure of it's format
485 ossPosition << pos[0];
486 for (int i = 1; i < 3; i++)
489 ossPosition << pos[i];
491 strPosition = ossPosition.str();
494 if ( CoherentFileSet.count(strPosition) == 0 )
496 gdcmDebugMacro(" New Position :[" << strPosition << "]");
497 // create a File set in 'position' position
498 CoherentFileSet[strPosition] = new FileList;
500 // Current Position and DICOM header match; add the file:
501 CoherentFileSet[strPosition]->push_back( (*it) );
503 return CoherentFileSet;
507 * \brief Splits a 'Single SerieUID' File set Coherent according to the
508 * value of a given Tag
509 * @param fileSet File Set to be splitted
510 * @param group group number of the target Element
511 * @param elem element number of the target Element
512 * \return std::map of 'Xcoherent' File sets
515 XCoherentFileSetmap SerieHelper::SplitOnTagValue(FileList *fileSet,
516 uint16_t group, uint16_t elem)
518 XCoherentFileSetmap CoherentFileSet;
520 int nb = fileSet->size();
522 return CoherentFileSet;
524 std::string strTagValue; // read on disc
526 FileList::const_iterator it = fileSet->begin();
529 it != fileSet->end();
532 // Information is in :
533 // 0020,0032 : Image Position Patient
534 // 0020,0030 : Image Position (RET)
536 strTagValue = (*it)->GetEntryString(group,elem);
538 if ( CoherentFileSet.count(strTagValue) == 0 )
540 gdcmDebugMacro(" New Tag Value :[" << strTagValue << "]");
541 // create a File set in 'position' position
542 CoherentFileSet[strTagValue] = new FileList;
544 // Current Tag value and DICOM header match; add the file:
545 CoherentFileSet[strTagValue]->push_back( (*it) );
547 return CoherentFileSet;
550 //-----------------------------------------------------------------------------
553 //-----------------------------------------------------------------------------
556 * \brief sorts the images, according to their Patient Position.
558 * We may order, considering :
559 * -# Image Position Patient
562 * -# More to come :-)
563 * \note : FileList = std::vector<File* >
564 * @param fileList Coherent File list (same Serie UID) to sort
565 * @return false only if the header is bugged !
567 bool SerieHelper::ImagePositionPatientOrdering( FileList *fileList )
568 //based on Jolinda Smith's algorithm
570 //iop is calculated based on the file file
575 float min = 0, max = 0;
578 std::multimap<float,File *> distmultimap;
579 // Use a multimap to sort the distances from 0,0,0
580 for ( FileList::const_iterator
581 it = fileList->begin();
582 it != fileList->end(); ++it )
586 (*it)->GetImageOrientationPatient( cosines );
588 // You only have to do this once for all slices in the volume. Next,
589 // for each slice, calculate the distance along the slice normal
590 // using the IPP ("Image Position Patient") tag.
591 // ("dist" is initialized to zero before reading the first slice) :
592 normal[0] = cosines[1]*cosines[5] - cosines[2]*cosines[4];
593 normal[1] = cosines[2]*cosines[3] - cosines[0]*cosines[5];
594 normal[2] = cosines[0]*cosines[4] - cosines[1]*cosines[3];
596 ipp[0] = (*it)->GetXOrigin();
597 ipp[1] = (*it)->GetYOrigin();
598 ipp[2] = (*it)->GetZOrigin();
601 for ( int i = 0; i < 3; ++i )
603 dist += normal[i]*ipp[i];
606 distmultimap.insert(std::pair<const float,File *>(dist, *it));
613 ipp[0] = (*it)->GetXOrigin();
614 ipp[1] = (*it)->GetYOrigin();
615 ipp[2] = (*it)->GetZOrigin();
618 for ( int i = 0; i < 3; ++i )
620 dist += normal[i]*ipp[i];
623 distmultimap.insert(std::pair<const float,File *>(dist, *it));
625 min = (min < dist) ? min : dist;
626 max = (max > dist) ? max : dist;
631 // Find out if min/max are coherent
634 gdcmWarningMacro("Looks like all images have the exact same image position"
635 << ". No PositionPatientOrdering sort performed" );
639 // Check to see if image shares a common position
641 for (std::multimap<float, File *>::iterator it2 = distmultimap.begin();
642 it2 != distmultimap.end();
645 if (distmultimap.count((*it2).first) != 1)
647 gdcmErrorMacro("File: "
648 << ((*it2).second->GetFileName())
651 << " position is not unique");
660 fileList->clear(); // doesn't delete list elements, only nodes
664 for (std::multimap<float, File *>::iterator it3 = distmultimap.begin();
665 it3 != distmultimap.end();
668 fileList->push_back( (*it3).second );
671 else // user asked for reverse order
673 std::multimap<float, File *>::const_iterator it4;
674 it4 = distmultimap.end();
678 fileList->push_back( (*it4).second );
679 } while (it4 != distmultimap.begin() );
682 distmultimap.clear();
687 bool SerieHelper::ImageNumberLessThan(File *file1, File *file2)
689 return file1->GetImageNumber() < file2->GetImageNumber();
692 bool SerieHelper::ImageNumberGreaterThan(File *file1, File *file2)
694 return file1->GetImageNumber() > file2->GetImageNumber();
698 * \brief sorts the images, according to their Image Number
699 * \note Works only on bona fide files (i.e image number is a character string
700 * corresponding to an integer)
701 * within a bona fide serie (i.e image numbers are consecutive)
702 * @param fileList File set (same Serie UID) to sort
703 * @return false if non bona fide stuff encountered
705 bool SerieHelper::ImageNumberOrdering(FileList *fileList)
708 int n = fileList->size();
710 FileList::const_iterator it = fileList->begin();
711 min = max = (*it)->GetImageNumber();
713 for (; it != fileList->end(); ++it, ++n)
715 pos = (*it)->GetImageNumber();
716 min = (min < pos) ? min : pos;
717 max = (max > pos) ? max : pos;
720 // Find out if image numbers are coherent (consecutive)
721 if ( min == max || max == 0 || max >= (n+min) )
723 gdcmWarningMacro( " 'Image numbers' not coherent. "
724 << " No ImageNumberOrdering sort performed.");
728 std::sort(fileList->begin(), fileList->end(),
729 SerieHelper::ImageNumberLessThan );
731 std::sort(fileList->begin(), fileList->end(),
732 SerieHelper::ImageNumberGreaterThan );
737 bool SerieHelper::FileNameLessThan(File *file1, File *file2)
739 return file1->GetFileName() < file2->GetFileName();
742 bool SerieHelper::FileNameGreaterThan(File *file1, File *file2)
744 return file1->GetFileName() > file2->GetFileName();
747 * \brief sorts the images, according to their File Name
748 * @param fileList Coherent File list (same Serie UID) to sort
749 * @return false only if the header is bugged !
751 bool SerieHelper::FileNameOrdering(FileList *fileList)
754 std::sort(fileList->begin(), fileList->end(),
755 SerieHelper::FileNameLessThan);
757 std::sort(fileList->begin(), fileList->end(),
758 SerieHelper::FileNameGreaterThan);
764 * \brief sorts the images, according to user supplied function
765 * @param fileList Coherent File list (same Serie UID) to sort
766 * @return false only if the header is bugged !
768 bool SerieHelper::UserOrdering(FileList *fileList)
770 std::sort(fileList->begin(), fileList->end(),
771 SerieHelper::UserLessThanFunction);
774 std::reverse(fileList->begin(), fileList->end());
779 std::string SerieHelper::CreateUniqueSeriesIdentifier( File * inFile )
781 if( inFile->IsReadable() )
783 // 0020 000e UI REL Series Instance UID
784 std::string uid = inFile->GetEntryString (0x0020, 0x000e);
785 std::string id = uid.c_str();
786 if(m_UseSeriesDetails)
788 // If the user requests, additional information can be appended
789 // to the SeriesUID to further differentiate volumes in the DICOM
790 // objects being processed.
792 // 0020 0011 Series Number
793 // A scout scan prior to a CT volume scan can share the same
794 // SeriesUID, but they will sometimes have a different Series Number
795 std::string sNum = inFile->GetEntryString(0x0020, 0x0011);
796 if( sNum == gdcm::GDCM_UNFOUND )
800 // 0018 0024 Sequence Name
801 // For T1-map and phase-contrast MRA, the different flip angles and
802 // directions are only distinguished by the Sequence Name
803 std::string sName = inFile->GetEntryString(0x0018, 0x0024);
804 if( sName == gdcm::GDCM_UNFOUND )
808 // 0018 0050 Slice Thickness
809 // On some CT systems, scout scans and subsequence volume scans will
810 // have the same SeriesUID and Series Number - YET the slice
811 // thickness will differ from the scout slice and the volume slices.
812 std::string sThick = inFile->GetEntryString (0x0018, 0x0050);
813 if( sThick == gdcm::GDCM_UNFOUND )
818 // If the 2D images in a sequence don't have the same number of rows,
819 // then it is difficult to reconstruct them into a 3D volume.
820 std::string sRows = inFile->GetEntryString (0x0028, 0x0010);
821 if( sRows == gdcm::GDCM_UNFOUND )
826 // If the 2D images in a sequence don't have the same number of columns,
827 // then it is difficult to reconstruct them into a 3D volume.
828 std::string sColumns = inFile->GetEntryString (0x0028, 0x0011);
829 if( sColumns == gdcm::GDCM_UNFOUND )
834 // Concat the new info
835 std::string num = sNum.c_str();
836 num += sName.c_str();
837 num += sThick.c_str();
838 num += sRows.c_str();
839 num += sColumns.c_str();
841 // Append the new info to the SeriesUID
846 // Eliminate non-alnum characters, including whitespace...
847 // that may have been introduced by concats.
848 for(unsigned int i=0; i<id.size(); i++)
852 || (id[i] >= 'a' && id[i] <= 'z')
853 || (id[i] >= '0' && id[i] <= '9')
854 || (id[i] >= 'A' && id[i] <= 'Z')))
861 else // Could not open inFile
863 gdcmWarningMacro("Could not parse series info.");
864 std::string id = gdcm::GDCM_UNFOUND;
870 //-----------------------------------------------------------------------------
873 * \brief Canonical printer.
875 void SerieHelper::Print(std::ostream &os, std::string const &indent)
877 // For all the Coherent File lists of the gdcm::Serie
878 SingleSerieUIDFileSetmap::iterator itl = SingleSerieUIDFileSetHT.begin();
879 if ( itl == SingleSerieUIDFileSetHT.end() )
881 gdcmWarningMacro( "No SingleSerieUID File set found" );
884 while (itl != SingleSerieUIDFileSetHT.end())
886 os << "Serie UID :[" << itl->first << "]" << std::endl;
888 // For all the files of a SingleSerieUID File set
889 for (FileList::iterator it = (itl->second)->begin();
890 it != (itl->second)->end();
893 os << indent << " --- " << (*it)->GetFileName() << std::endl;
899 //-----------------------------------------------------------------------------
900 } // end namespace gdcm