]> Creatis software - creaBruker.git/blobdiff - lib/src1/bruker2dicom.cxx
Fix bug when checking incoherences
[creaBruker.git] / lib / src1 / bruker2dicom.cxx
index 0473bb3ac3be310019cbbc36da201c6b931604c2..a381993f822a9f4da8199105c03a77c690edcce6 100644 (file)
@@ -1,6 +1,7 @@
 #include "bruker2dicom.h"
 #include <boost/filesystem/path.hpp>
 #include <boost/filesystem/operations.hpp>
+#include "brukerexception.h"
 
 #ifndef PATH_MAX // If not defined yet : do it 
    #define PATH_MAX 2048
@@ -30,7 +31,8 @@ bool Bruker2Dicom::Execute()
    bool res=CreateDirectory(strDirNameOut);
    if (!res) {
       std::cout << "[" << OutputDirName << "] Directory creation failure " << std::endl;
-      exit (0);
+      //exit (0);
+      throw ( BrukerHopelessException ("Output directory creation failure "));
    }
 
    std::string strDirNamein(InputDirName);
@@ -71,7 +73,8 @@ bool Bruker2Dicom::Execute()
    if (!canOpen)
    {
       std::cout << "Hopeless! no 'subject' found" << std::endl;
-      exit(0);  /// \TODO throw an exception !     
+      throw ( BrukerHopelessException ("Hopeless! no 'subject' found in root input directory "));    
+      //exit(0);  /// \TODO throw an exception !     
    }
    else
    { 
@@ -79,8 +82,7 @@ bool Bruker2Dicom::Execute()
    }
    //br_subject.PrintSelf();
 
-  // get info for 'Study Description'
-  
+  // get info for 'Study Description'  
 
          BrukerFieldData b_name=br_subject.GetFieldData("SUBJECT_name_string");
          std::string subject_name = b_name.GetStringValue()[0];
@@ -114,6 +116,7 @@ bool Bruker2Dicom::Execute()
 
    strStudyUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
    serieNumber = 0;
+   instanceNumber = 0;
    // -----------------------------------------------------
    // Iterate to ALL the objets(files/directories) found in the input directory
    // (this is level ZERO)
@@ -157,7 +160,7 @@ bool Bruker2Dicom::Execute()
          cleanString(acqp_method);
 
          BrukerFieldData b_list_size = br_acqp.GetFieldData("ACQ_O1_list_size");
-         b_list_size.PrintSelf(); //JP
+         //b_list_size.PrintSelf(); //JP
  
          nbSlices =  b_list_size.GetIntValue()[0];
 
@@ -178,8 +181,14 @@ bool Bruker2Dicom::Execute()
 
         if (verbose)
            printf ("outputDirName [%s]\n", outputDirName);   
-
-        DealWithNiveau1(*it, outputDirName);
+        try {
+           DealWithNiveau1(*it, outputDirName);
+       }
+       catch (BrukerHopelessException &e)
+       {
+        std::cout << "And Exception was thrown in DealWithNiveau1 (" << e.what() << ") " << std::endl;
+        continue;
+       }
       }
    } // end of : for (GDCM_NAME_SPACE::DirListType::iterator it
 }
@@ -197,7 +206,8 @@ void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string curr
 
    if (!res) {
       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
-      exit (0);
+      throw ( BrukerHopelessException ("Level 1 output directory creation failure "));    
+     // exit (0);
    }
    GDCM_NAME_SPACE::DirList dirList(level1Directory, false, true); // DON'T get recursively the list of files
    GDCM_NAME_SPACE::DirListType fileNames;
@@ -264,8 +274,11 @@ void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string curr
              canOpen = br_method.LoadFile(strMethod);
              if (!canOpen)
              {
-                std::cout << "Hopeless! neither 'method' nor 'imnd' found" << std::endl;
-                exit(0);  /// \TODO throw an exception !
+                std::cout << "Hopeless! neither 'method' nor 'imnd' found in ["
+                         << level1Directory  << "]; we skip it!" << std::endl;
+               continue;
+                //throw ( BrukerHopelessException ("Hopeless! neither 'method' nor 'imnd' found "));           
+                //exit(0);  /// \TODO throw an exception !
              }
           }
           if (verbose)
@@ -283,7 +296,14 @@ void Bruker2Dicom::DealWithNiveau1(std::string level1Directory, std::string curr
           ##$PVM_SPackArrNSlices=( 2 )
           7 1  
   */    
-         DealWithNiveau2(*it,outputDirName );
+         try {
+            DealWithNiveau2(*it,outputDirName );
+        }
+        catch (BrukerHopelessException &e)
+        {
+           std::cout << "And Exception was thrown in DealWithNiveau2 (" << e.what() << ") " << std::endl;
+           continue;
+        }
       }
    }
 }
@@ -301,7 +321,8 @@ void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string curr
 
    if (!res) {
       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
-      exit (0);
+      throw ( BrukerHopelessException ("Hopeless! Level2 output directory creation failure"));       
+      //exit (0);
    }
   
    GDCM_NAME_SPACE::DirList dirList(level2Directory, false, true); // DON'T get recursively the list of files
@@ -373,8 +394,22 @@ void Bruker2Dicom::DealWithNiveau2(std::string level2Directory, std::string curr
                                           GDCM_NAME_SPACE::GDCM_FILESEPARATOR,
                                           GDCM_NAME_SPACE::Util::GetName(*it).c_str(),
              str_isa_func_name.c_str());
-          } 
-          DealWithNiveau3(*it, outputDirName);
+          }
+         try { 
+             DealWithNiveau3(*it, outputDirName);
+         }
+         catch (BrukerHopelessException &e)
+         {
+            std::cout << "And Exception was thrown in DealWithNiveau3 (" << e.what() << "); " 
+                      << " We skip [" << level2Directory << "]" << std::endl;
+            continue;
+         }
+         catch (BrukerInitException &e)
+         {
+            std::cout << "And Init Exception was thrown in DealWithNiveau3 (" << e.what() << "); " 
+                      << " We skip [" << level2Directory << "]" << std::endl;
+            continue;
+         }                  
       }
    }
 }
@@ -398,7 +433,8 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
    if (!res)
    {
       std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
-      exit (0);
+      throw ( BrukerHopelessException ("Hopeless! Level3 output directory creation failure"));      
+      //exit (0);
    }
 
    GDCM_NAME_SPACE::DirList dirList(level3Directory, false, true); // DON'T get recursively the list of files
@@ -423,21 +459,23 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
    sprintf(char_d3proc,"%s%c%s", level3Directory.c_str(), GDCM_NAME_SPACE::GDCM_FILESEPARATOR,"d3proc" );     
    
    if (verbose)
-      std::cout << "try d3proc: --- => [" << char_d3proc << "]" << std::endl;
+      std::cout << "d3proc: --- => [" << char_d3proc << "]" << std::endl;
    std::string str_d3proc(char_d3proc);       
    canOpen = br_d3proc.LoadFile(str_d3proc);
 
    if (!canOpen)
    {
       std::cout << "Hopeless! no 'd3proc' found" << std::endl;
-      exit(0);  /// \TODO throw an exception ! 
+      throw ( BrukerHopelessException ("Hopeless! no 'd3proc' found"));
+      //exit(0);  /// \TODO throw an exception ! 
    }
 
    canOpen = br_d3proc.FillMap();
    if (!canOpen)
    {
       std::cout << "Hopeless! FillMap failed on 'd3proc'" << std::endl;
-      exit(0);  /// \TODO throw an exception !     
+      throw ( BrukerHopelessException ("Hopeless! FillMap failed on 'd3proc'"));      
+      //exit(0);  /// \TODO throw an exception !     
    }
  
    //-------------- end try d3proc;
@@ -452,7 +490,7 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
     //             GDCM_NAME_SPACE::GDCM_FILESEPARATOR +
     //             "d3proc";
    if (verbose)
-      std::cout << "try reco --- => [" << char_reco << "]" << std::endl;
+      std::cout << "reco --- => [" << char_reco << "]" << std::endl;
    std::string str_reco(char_reco);       
    canOpen = br_reco.LoadFile(str_reco);
 
@@ -467,8 +505,9 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
       canOpen = br_reco.LoadFile(str_reco);
       if (!canOpen)
       {
-         std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]"  << std::endl;
-         exit(0);  /// \TODO throw an exception !    
+         std::cout << "Hopeless! cannot find 'reco' in [" << str_reco << "]"  << std::endl;     
+         throw ( BrukerHopelessException ("Hopeless! cannot find 'reco'"));  
+         //exit(0);  /// \TODO throw an exception !    
       }
    }
 
@@ -476,7 +515,8 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
    if (!canOpen)
    {
       std::cout << "Hopeless! FillMap failed on [" << str_reco << "]" << std::endl;
-      exit(0);  /// \TODO throw an exception !     
+      throw ( BrukerHopelessException ("Hopeless! FillMap failed on 'reco'"));  
+      //exit(0);  /// \TODO throw an exception !     
    }
    //std::cout << "------------------------------------------------------------------------------------------------" << std::cout;
    // br_reco.PrintSelf();
@@ -488,16 +528,19 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
    BrukerFieldData bX = br_d3proc.GetFieldData("IM_SIX");
    int NX = bX.GetIntValue()[0];
 
-   std::cout << "IM_SIX " << NX << std::endl;
+   if (verbose)
+      std::cout << "IM_SIX " << NX << std::endl;
    BrukerFieldData bY=br_d3proc.GetFieldData("IM_SIY"); 
    int NY = bY.GetIntValue()[0];
 
-   std::cout << "IM_SIY " << NY << std::endl;
+   if (verbose)
+         std::cout << "IM_SIY " << NY << std::endl;
    /// \todo : check if there are actually 3 dimensions or only 2
   
    BrukerFieldData bZ= br_d3proc.GetFieldData("IM_SIZ");
    int nbFrames = bZ.GetIntValue()[0]; 
-   std::cout << "IM_SIZ " << nbFrames << std::endl;
+   if (verbose)
+         std::cout << "IM_SIZ " << nbFrames << std::endl;
 
         // WARNING DATTYPE is, either in {ip_short, ip_int, ip_char, ...}, or in {1, 2, 3, ...}
  
@@ -525,18 +568,22 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
       res = CreateDirectory( currentOutputMhdDirName );
       if (!res) {
          std::cout << "[" << currentOutputDirName << "] Directory creation failure " << std::endl;
-         exit (0);
+        throw ( BrukerHopelessException ("Hopeless!FillMap failed on 'reco'"));  
+         //exit (0);
       } 
 
       if (verbose)
          std::cout << "Directory creation [" <<  currentOutputDirName << "]" << std::endl;
    }  // end if mhd
 
-   std::cout << "nbFrames " << nbFrames << std::endl;
-   std::cout << "nbSlices " << nbSlices << std::endl;
+   if (verbose)
+         std::cout << "nbFrames " << nbFrames << std::endl;
+   if (verbose)
+         std::cout << "nbSlices " << nbSlices << std::endl;
    int k;
    int nbInstants = nbFrames/nbSlices;
-   std::cout << "nbInstants (deduced )" << nbInstants << std::endl;    
+   if (verbose)
+         std::cout << "nbInstants (deduced )" << nbInstants << std::endl;    
    int instantNb;
    int sliceNb; 
    FILE *fp;  // for MHD files
@@ -552,7 +599,8 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
    if (!fp) 
    {
       std::cout << "Cannot open [" << original2dseqName << "] for reading" << std::endl;
-      exit (0);
+      throw ( BrukerHopelessException ("Hopeless! Cannot open '2dseq'"));
+      //exit (0);
    }
    
    unsigned char *buffer_2dseq = new unsigned char[NX*NY*pixelSize*nbSlices*nbInstants];   
@@ -561,13 +609,24 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
 
    // This one will be important!
    // ---------------------------
-   imageSet = CreateImageSet ( );
+   try {
+      imageSet = CreateImageSet ( );
+   }
+   catch (BrukerInitException& e)
+   {
+      if (verbose)
+         std::cout <<  "an Init Exception was thrown in CreateImageSet ( ); " << e.what() 
+                   <<  "catched in DealWithNiveau3" << std::endl;
+      //return;
+      throw (e);
+   }
    
    serieNumber++;
    strSerieUID =  GDCM_NAME_SPACE::Util::CreateUniqueUID();
    if (nbInstants==1) // creer un seul fichier .mhd  pour toutes les Slices! (images natives)
    {
-       std::cout << "Single instant : do not split" << std::endl;
+       if (verbose)
+          std::cout << "Single instant : do not split" << std::endl;
        if (mhd)
        {
              sprintf(outputMhdFileName, "%s%cMhdData_All_the_Slices.mhd", currentOutputMhdDirName,
@@ -576,7 +635,8 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
              if (!fp)
              {
                 std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
-                exit(0);
+               throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
+                //exit(0);
              }
              else
              {
@@ -601,6 +661,7 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
              if (!fp)
              {
                 std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
+               throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseq file for writting"));             
              }
              else
              {
@@ -656,7 +717,8 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
                if (!fp)
                {
                    std::cout << "Cannot open [" << outputMhdFileName << "] for writting" << std::endl;
-                   exit(0);
+                  throw ( BrukerHopelessException ("Hopeless! Cannot open  mhd file for writting"));
+                   //exit(0);
                }
                else
                {
@@ -685,7 +747,8 @@ void Bruker2Dicom::DealWithNiveau3(std::string level3Directory, std::string curr
                if (!fp)
                {     
                    std::cout << "Cannot open [" << output2dseqSliceFileName << "] for writting" << std::endl;
-                   exit (0);
+                  throw ( BrukerHopelessException ("Hopeless! Cannot open 2dseqSliceFile file for writting"));            
+                   //exit (0);
                }
                int frameSize = NX*NY*pixelSize;
                for (instantNb=0; instantNb<nbInstants; instantNb++)
@@ -797,7 +860,7 @@ void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX
    //  deal with MatLab-generated Carto file.
    // -----------------------------------------------------
    
-   char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak" , ""};  // add more carto file name identifiers if necessary; end with ""
+   char *code[] ={ "ADC", "adc", "TTP", "ttp", "PEAK", "peak", "" };  // add more carto file name identifiers if necessary; end with ""
    int icode; 
    GDCM_NAME_SPACE::DirListType::iterator it;
    char file_name_ident[500];
@@ -818,7 +881,7 @@ void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX
 
          while (code[icode][0] != 0)
          {
-            sprintf(file_name_ident, "2dseq_%s",code[icode]); // e.g  "2dseq_ADC"
+            sprintf(file_name_ident, "2dseq.%s",code[icode]); // e.g  "2dseq_ADC"
             std::string::size_type loc = (*it).rfind(file_name_ident); 
 
             if ( loc != std::string::npos )
@@ -829,7 +892,7 @@ void Bruker2Dicom::dealWithCarto(GDCM_NAME_SPACE::DirListType &fileNames, int NX
               fp = fopen ( (*it).c_str(), "rb");
               if (!fp){
                  std::cout << "Cannot open [" << *it << "] for reading" << std::endl;
-
+                 throw ( BrukerHopelessException ("Level 1 Unable to open 'carto' file "));
                }
                fread(buffer_carto, NX*NY*sizeof(double), nbSlices, fp);
 
@@ -939,8 +1002,8 @@ bool Bruker2Dicom::CreateDirectory(std::string OutputDirName)
       {
          if (verbose) 
             std::cout << "KO : not a dir : [" << OutputDirName << "] (creation failure ?)" << std::endl;
-         return 0;
-         /// \todo : THROW AN EXCEPTION
+         //return 0;
+        throw ( BrukerHopelessException ("Level 1 output directory creation failure "));
       }
       else
       {
@@ -993,7 +1056,8 @@ void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPix
    if(bDPT.GetDataType() == "string")
    {         
          std::string brukerDataPixelType = bDPT.GetStringValue()[0];
-         std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
+        if (verbose)
+            std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
          
          if (brukerDataPixelType ==  "ip_short") {
@@ -1030,7 +1094,8 @@ void Bruker2Dicom::getImhDataType(BrukerFieldData &bDPT, std::string &mhdDataPix
     else
     {
          int brukerDataPixelType = bDPT.GetIntValue()[0];
-         std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
+         if (verbose)
+           std::cout << "DATTYPE " << brukerDataPixelType << std::endl;          
          //std::string brukerDataPixelType = br_d3proc.GetFieldData("DATTYPE").GetStringValue()[0];
  
 // Cross your fingers !!!
@@ -1060,7 +1125,13 @@ std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
          br_acqp.SetLoopStructure();
          std::vector<int> tempVect                      = br_acqp.GetLoopStructure() ;
          std::map<std::string, BrukerFieldData> map     = br_acqp.GetBrukerHeaderMap();
+        
          bool result                                    = br_acqp.ObjectVaryingProperties.init(map,tempVect);
+         if (result == false)
+        {
+           throw ( BrukerInitException  ("ObjectVaryingProperties.init() failure in Bruker2Dicom::CreateImageSet()") );
+        }
 
          br_acqp.SetImageLoopStructure();
          br_acqp.SetBrukerImageList();
@@ -1090,7 +1161,7 @@ std::vector<BrukerImage> Bruker2Dicom::CreateImageSet ( )
            imageOrientation =  imageSet[i].getRotationMatrixRPS2XYZ();
            std::cout << "\t  Orientation " ;
            for(int i1=0; i1<3;i1++)for(int i2=0; i2<3;i2++)
-              std::cout << imageOrientation[i1][i2] << " ";
+              std::cout << imageOrientation[i1][i2] << " ";CreateImageSet
        
            //std::cout << "\t  Abs Time " << imageSet[i].getAbsoluteTimePosition();
            std::cout << "\t  Relat Time " << imageSet[i].getRelativeTimePosition();
@@ -1170,14 +1241,27 @@ void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
  //   0018 0050 DS 1 Slice Thickness 
    str.str("");    
    str << sliceDistance;
-   file->InsertEntryString(str.str(),0x0018,0x0050, "DS");     
-     
+   file->InsertEntryString(str.str(),0x0018,0x0050, "DS"); 
+   
+//    0020 0011 IS 1 Series Number
+   str.str("");    
+   str << serieNumber;
+   file->InsertEntryString(str.str(),0x0020,0x0011, "IS");
+      
+//    0020|0013 [IS]  [Instance Number] 
+   instanceNumber++;
+   str.str("");    
+   str << instanceNumber;
+   file->InsertEntryString(str.str(),0x0020,0x0013, "IS");
+   
+       
   // 1.2.840.10008.5.1.4.1.1.4.1 : Enhanced MR Image Storage
  //  file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
   // file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4.1" , 0x0008, 0x0016, "UI");  // [SOP Class UID]
 
 
 // OK : MR is NOT multiframe, but I want just a quick an dirty solution
+
 // 1.2.840.10008.5.1.4.1.1.4         MR Image Storage
    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0002, 0x0002, "UI");  // [Media Storage SOP Class UID]
    file->InsertEntryString("1.2.840.10008.5.1.4.1.1.4" , 0x0008, 0x0016, "UI");  // [SOP Class UID]     
@@ -1193,10 +1277,10 @@ void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
 
 /// \TODO split into 2 strings!
    file->InsertEntryString(strStudyTimeDate.substr(10,11).c_str(),0x0008,0x0020, "DA");
-   file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),0x0008,0x0030, "TM");
+   file->InsertEntryString(strStudyTimeDate.substr(1,8).c_str(),  0x0008,0x0030, "TM");
 
-   file->InsertEntryString(studyDescr,0x0008,0x1030, "LO");  // Study Description  
-   file->InsertEntryString(serieDescr,0x0008,0x103e, "LO");  // Series Description 
+   file->InsertEntryString(studyDescr, 0x0008,0x1030, "LO");  // Study Description  
+   file->InsertEntryString(serieDescr, 0x0008,0x103e, "LO");  // Series Description 
 
 //0008|0060 [CS] [Modality] 
    file->InsertEntryString("MR",0x0008,0x0060, "CS");
@@ -1205,7 +1289,7 @@ void Bruker2Dicom::MakeDicomImage(unsigned char *tabPixels,
    char charImageOrientation[256];
 
 /*
-std::cout << "try charImageOrientation  " << 
+std::cout << "charImageOrientation  " << 
                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][0] << " " <<
                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][1] << " " <<
                               imageSet[imgNum].getRotationMatrixRPS2XYZ()[0][2] << " " <<
@@ -1263,10 +1347,13 @@ std::cout << "try charImageOrientation  " <<
    fileH->SetImageData((uint8_t *)tabPixels, X*Y*nbFrames*pixelSize);
    fileH->SetWriteModeToRaw(); 
    fileH->SetWriteTypeToDcmExplVR();
-   if( !fileH->Write(dcmImageName))
+   if( !fileH->Write(dcmImageName)) {
       std::cout << "Failed for [" << dcmImageName << "]\n"
-                << "           File is unwrittable" << std::endl;
-
+                << "           File is unwrittable" << std::endl;              
+      file->Delete();
+      fileH->Delete();                 
+      throw ( BrukerHopelessException ("Level 1 Unable to write Dicom file "));
+   }
    if (verbose)
       file->Print();