Cleaning up generation and reading back of lookup tables. Also moved core generation...
authoraszostak <aszostak@f7af4fe6-9843-0410-8265-dc069ae4e863>
Fri, 18 Apr 2008 13:53:51 +0000 (13:53 +0000)
committeraszostak <aszostak@f7af4fe6-9843-0410-8265-dc069ae4e863>
Fri, 18 Apr 2008 13:53:51 +0000 (13:53 +0000)
HLT/MUON/OnlineAnalysis/AliHLTMUONHitReconstructor.cxx
HLT/MUON/OnlineAnalysis/AliHLTMUONHitReconstructor.h
HLT/MUON/OnlineAnalysis/AliHLTMUONHitReconstructorComponent.cxx
HLT/MUON/OnlineAnalysis/AliHLTMUONHitReconstructorComponent.h
HLT/MUON/macros/CreateHitRecoLookupTables.C

index be5544a..7d4617d 100644 (file)
@@ -60,7 +60,6 @@ AliHLTMUONHitReconstructor::AliHLTMUONHitReconstructor() :
        fMaxRecPointsCount(0),
        fCentralCountB(0),
        fCentralCountNB(0),
-       fDDLId(0),
        fDigitPerDDL(0),
        fCentralChargeB(NULL),
        fCentralChargeNB(NULL),
@@ -108,106 +107,31 @@ AliHLTMUONHitReconstructor::~AliHLTMUONHitReconstructor()
 {
        /// Default destructor
        
-       if(fPadData)
+       if (fPadData)
        {
                delete [] fPadData;
                fPadData = NULL;
        }
-       
-       if(fLookUpTableData)
-       {
-               delete [] fLookUpTableData;
-               fLookUpTableData = NULL;
-       }
 }
 
 
-bool AliHLTMUONHitReconstructor::LoadLookUpTable(AliHLTMUONHitRecoLutRow* lookUpTableData, int lookUpTableId)
+void AliHLTMUONHitReconstructor::SetLookUpTable(
+               const AliHLTMUONHitRecoLutRow* lookupTable,
+               const IdManuChannelToEntry* idToEntry
+       )
 {
-  // function that loads LookUpTable (= position of each pad with electronic channel associated with it)
-
-  if(lookUpTableId<fgkDDLOffSet || lookUpTableId>= fgkDDLOffSet + fgkNofDDL){
-    HLTError("DDL number %d is out of range (must be %d<=iDDL<%d)\n",lookUpTableId,fgkDDLOffSet,fgkDDLOffSet+fgkNofDDL);
-    return false;
-  }
-
-
-  if(fIdToEntry.size()==0){
-    HLTError("SetLineNumToIdManuChannel() is not set properly");
-    return false;
-  }else{
-    
-//     if(fLookUpTableData){
-//       delete []fLookUpTableData;
-//       fLookUpTableData = NULL;
-//     }
-
-    try{
-      fLookUpTableData = new AliHLTMUONHitRecoLutRow[fIdToEntry.size()+1];
-    }
-    catch(const std::bad_alloc&){
-      HLTError("Dynamic memory allocation failed for AliHLTMUONHitReconstructor::fLookUpTableData");
-      return false;
-    }
-
-  }
+       /// Sets the Lookup table (LUT) containing the position of each pad with
+       /// electronic channel associated with it. Also the appropriate manu
+       /// channel ID mapping to LUT row is also set.
 
-  fDDLId = lookUpTableId;
-
-  fLookUpTableData[0].fDetElemId = 0;
-  fLookUpTableData[0].fIX = 0 ;
-  fLookUpTableData[0].fIY = 0 ;
-  fLookUpTableData[0].fRealX = 0.0 ;
-  fLookUpTableData[0].fRealY = 0.0 ;
-  fLookUpTableData[0].fRealZ = 0.0 ;
-  fLookUpTableData[0].fHalfPadSize = 0.0 ;
-  fLookUpTableData[0].fPlane = -1 ;
-  fLookUpTableData[0].fPed = -1 ;
-  fLookUpTableData[0].fSigma = -1 ;
-  fLookUpTableData[0].fA0 = -1 ;
-  fLookUpTableData[0].fA1 = -1 ;
-  fLookUpTableData[0].fThres = -1 ;
-  fLookUpTableData[0].fSat = -1 ;
-
-  for(int i=0; i<int(fIdToEntry.size()); i++){
-
-    fLookUpTableData[i+1].fDetElemId = lookUpTableData[i].fDetElemId;
-    fLookUpTableData[i+1].fIX = lookUpTableData[i].fIX ;
-    fLookUpTableData[i+1].fIY = lookUpTableData[i].fIY ;
-    fLookUpTableData[i+1].fRealX = lookUpTableData[i].fRealX ;
-    fLookUpTableData[i+1].fRealY = lookUpTableData[i].fRealY ;
-    fLookUpTableData[i+1].fRealZ = lookUpTableData[i].fRealZ ;
-    fLookUpTableData[i+1].fHalfPadSize = lookUpTableData[i].fHalfPadSize ;
-    fLookUpTableData[i+1].fPlane = lookUpTableData[i].fPlane ;
-    fLookUpTableData[i+1].fPed = lookUpTableData[i].fPed ;
-    fLookUpTableData[i+1].fSigma = lookUpTableData[i].fSigma ;
-    fLookUpTableData[i+1].fA0 = lookUpTableData[i].fA0 ;
-    fLookUpTableData[i+1].fA1 = lookUpTableData[i].fA1 ;
-    fLookUpTableData[i+1].fThres= lookUpTableData[i].fThres ;
-    fLookUpTableData[i+1].fSat = lookUpTableData[i].fSat ;
-    
-  }
-
-  return true;
-  
+       assert( lookupTable != NULL );
+       assert( idToEntry != NULL );
+       
+       fIdToEntry = idToEntry;
+       fLookUpTableData = lookupTable;
 }
 
 
-bool AliHLTMUONHitReconstructor::SetIdManuChannelToEntry(IdManuChannelToEntry idToEntry)
-{
-
-  // function that loads LineNumber To IdManuChannel map
-
-  if(idToEntry.size()==0) {
-    HLTError("Empty idToEntry mapping");
-    return false;
-  } else {
-    fIdToEntry = idToEntry;
-  }
-  
-  return true;
-}
-
 bool AliHLTMUONHitReconstructor::Run(
                const AliHLTUInt32_t* rawData,
                AliHLTUInt32_t rawDataSize,
@@ -821,6 +745,7 @@ AliHLTMUONHitReconstructor::AliHLTMUONRawDecoder::~AliHLTMUONRawDecoder()
        // dtor
 }
 
+
 void AliHLTMUONHitReconstructor::AliHLTMUONRawDecoder::OnData(UInt_t dataWord, bool /*parityError*/)
 {
   //function to arrange the decoded Raw Data
@@ -829,7 +754,8 @@ void AliHLTMUONHitReconstructor::AliHLTMUONRawDecoder::OnData(UInt_t dataWord, b
   fIdManuChannel = (fIdManuChannel|fBusPatchId)<<17;
   fIdManuChannel |= (dataWord >> 12) & 0x1FFFF;
   
-  fLutEntry = fIdToEntry[fIdManuChannel];
+  IdManuChannelToEntry& idToEntry = * const_cast<IdManuChannelToEntry*>(fIdToEntry);
+  fLutEntry = idToEntry[fIdManuChannel];
   fPadCharge = int(((unsigned short)(dataWord & 0xFFF)) - fLookUpTableData[fLutEntry].fPed);
   
   fCharge = 0;   
index 3af34be..9d9fa53 100644 (file)
@@ -47,10 +47,13 @@ public:
        
        AliHLTMUONHitReconstructor();
        virtual ~AliHLTMUONHitReconstructor(void);
-
-       bool LoadLookUpTable(AliHLTMUONHitRecoLutRow* lookUpTableData, AliHLTInt32_t lookUpTableId);
-       bool SetIdManuChannelToEntry(IdManuChannelToEntry lineToId);
        
+       void SetLookUpTable(
+                       const AliHLTMUONHitRecoLutRow* lookupTable,
+                       const IdManuChannelToEntry* idToEntry
+               );
+       
+       void SetDCCut(AliHLTInt32_t dcCut) { fDCCut = dcCut; }
        
        bool Run(
                        const AliHLTUInt32_t* rawData,
@@ -58,7 +61,6 @@ public:
                        AliHLTMUONRecHitStruct* recHit,
                        AliHLTUInt32_t& nofHit
                );
-       void SetDCCut(AliHLTInt32_t dcCut) {fDCCut = dcCut;}
        
        static AliHLTInt32_t GetkDetectorId() { return fgkDetectorId; }
        static AliHLTInt32_t GetkDDLOffSet() { return fgkDDLOffSet; }
@@ -123,9 +125,9 @@ private:
                
                void SetDCCut(AliHLTInt32_t dcCut) {fDCCut = dcCut;}
                void SetPadData(AliHLTMUONPad* padData) {fPadData = padData;}
-               void SetLookUpTable(AliHLTMUONHitRecoLutRow* lookUpTableData) {fLookUpTableData = lookUpTableData;}
+               void SetLookUpTable(const AliHLTMUONHitRecoLutRow* lookUpTableData) {fLookUpTableData = lookUpTableData;}
                void SetNofFiredDetElemId(AliHLTInt32_t& nofFiredDetElem) {fNofFiredDetElem = &nofFiredDetElem;}
-               void SetIdManuChannelToEntry(IdManuChannelToEntry idToEntry) {fIdToEntry = idToEntry;}
+               void SetIdManuChannelToEntry(const IdManuChannelToEntry* idToEntry) {fIdToEntry = idToEntry;}
                void SetMaxFiredPerDetElem(AliHLTInt32_t* maxFiredPerDetElem) {fMaxFiredPerDetElem = maxFiredPerDetElem;}
                
                AliHLTInt32_t GetDataCount() {return fDataCount;}
@@ -138,48 +140,47 @@ private:
                AliHLTMUONRawDecoder& operator=(const AliHLTMUONRawDecoder& rhs); // assignment operator
        
                const void* fBufferStart;   // Pointer to the start of the current DDL payload buffer.
-               AliHLTInt32_t fBusPatchId;                                                // buspatchId
-               AliHLTInt32_t fDCCut;                                                     // DC Cut value
-               AliHLTMUONPad* fPadData;                  // pointer to the array containing the information of each padhits
-               AliHLTMUONHitRecoLutRow* fLookUpTableData;          // pointer to the array of Lookuptable data
-               AliHLTInt32_t* fNofFiredDetElem;                                          // counter for detector elements that are fired 
-               AliHLTInt32_t* fMaxFiredPerDetElem;                                       // array for detector elements that are fired 
-               IdManuChannelToEntry fIdToEntry;                                // Mapping between Linenumber to IdManuChannel;
+               AliHLTInt32_t fBusPatchId;  // buspatchId
+               AliHLTInt32_t fDCCut;       // DC Cut value
+               AliHLTMUONPad* fPadData;    // pointer to the array containing the information of each padhits
+               const AliHLTMUONHitRecoLutRow* fLookUpTableData;   // pointer to the array of Lookuptable data
+               AliHLTInt32_t* fNofFiredDetElem;         // counter for detector elements that are fired 
+               AliHLTInt32_t* fMaxFiredPerDetElem;      // array for detector elements that are fired 
+               const IdManuChannelToEntry* fIdToEntry;  // Mapping between Linenumber to IdManuChannel;
                
-               AliHLTInt32_t fDataCount;                                                 // Data Counter
-               AliHLTInt32_t fPrevDetElemId;                                             // previous detection elementId
-               AliHLTInt32_t fPadCharge;                                                 // pedestal subtracted pad charge
-               AliHLTFloat32_t fCharge;                                                  //calibrated pad charge 
-               AliHLTInt32_t fIdManuChannel;                                             // id manu channel
-               AliHLTInt32_t fLutEntry;                                                  // i-th entry in lookuptable
+               AliHLTInt32_t fDataCount;           // Data Counter
+               AliHLTInt32_t fPrevDetElemId;       // previous detection elementId
+               AliHLTInt32_t fPadCharge;           // pedestal subtracted pad charge
+               AliHLTFloat32_t fCharge;            //calibrated pad charge 
+               AliHLTInt32_t fIdManuChannel;       // id manu channel
+               AliHLTInt32_t fLutEntry;            // i-th entry in lookuptable
        };
 
        AliMUONTrackerDDLDecoder<AliHLTMUONRawDecoder> fHLTMUONDecoder; // robust HLTMUON Decoder
        
-       AliHLTInt32_t fkBlockHeaderSize;                     // Block header size
-       AliHLTInt32_t fkDspHeaderSize;                       // DSP header size
-       AliHLTInt32_t fkBuspatchHeaderSize;                  // buspatch header size
+       AliHLTInt32_t fkBlockHeaderSize;      // Block header size
+       AliHLTInt32_t fkDspHeaderSize;        // DSP header size
+       AliHLTInt32_t fkBuspatchHeaderSize;   // buspatch header size
        
-       AliHLTInt32_t fDCCut;                                // DC Cut value
+       AliHLTInt32_t fDCCut;                 // DC Cut value
        
-       AliHLTMUONPad* fPadData;                         // pointer to the array containing the information of each padhits
-       AliHLTMUONHitRecoLutRow* fLookUpTableData;                 // pointer to the array of Lookuptable data
+       AliHLTMUONPad* fPadData;  // pointer to the array containing the information of each padhits
+       const AliHLTMUONHitRecoLutRow* fLookUpTableData;  // pointer to the array of Lookuptable data (The memory is not owned by this component).
        
-       AliHLTMUONRecHitStruct* fRecPoints;       // Reconstructed hits
-       AliHLTUInt32_t *fRecPointsCount;                      // nof reconstructed hit  
-       AliHLTUInt32_t fMaxRecPointsCount;                    // max nof reconstructed hit  
+       AliHLTMUONRecHitStruct* fRecPoints;      // Reconstructed hits
+       AliHLTUInt32_t *fRecPointsCount;         // nof reconstructed hit.
+       AliHLTUInt32_t fMaxRecPointsCount;       // max nof reconstructed hit.
        
-       AliHLTInt32_t fCentralCountB, fCentralCountNB;        // centeral hits 
-       AliHLTInt32_t fDDLId;                                 // DDLId
-       AliHLTInt32_t fDigitPerDDL;                           // Total nof Digits perDDL 
+       AliHLTInt32_t fCentralCountB, fCentralCountNB;   // centeral hits.
+       AliHLTInt32_t fDigitPerDDL;                      // Total nof Digits perDDL.
        
-       AliHLTInt32_t *fCentralChargeB, *fCentralChargeNB;           // pointer to an array of central hit
-       AliHLTFloat32_t *fRecX, *fRecY;                              // pointer to an array of reconstructed hit
-       AliHLTFloat32_t *fAvgChargeX, *fAvgChargeY;                  // average charge on central pad found using CG method
-       AliHLTInt32_t *fNofBChannel, *fNofNBChannel;                 // number of channels bending and non-bending.
-       AliHLTInt32_t fGetIdTotalData[336][237][2];                  // an array of idManuChannel with argument of centralX, centralY and planeType.
-       AliHLTInt32_t fNofFiredDetElem,fMaxFiredPerDetElem[13];      // counter for detector elements that are fired
-       IdManuChannelToEntry fIdToEntry;       // Mapping between Linenumber to IdManuChannel;
+       AliHLTInt32_t *fCentralChargeB, *fCentralChargeNB;       // pointer to an array of central hit
+       AliHLTFloat32_t *fRecX, *fRecY;                          // pointer to an array of reconstructed hit
+       AliHLTFloat32_t *fAvgChargeX, *fAvgChargeY;              // average charge on central pad found using CG method
+       AliHLTInt32_t *fNofBChannel, *fNofNBChannel;             // number of channels bending and non-bending.
+       AliHLTInt32_t fGetIdTotalData[336][237][2];              // an array of idManuChannel with argument of centralX, centralY and planeType.
+       AliHLTInt32_t fNofFiredDetElem,fMaxFiredPerDetElem[13];  // counter for detector elements that are fired
+       const IdManuChannelToEntry* fIdToEntry;   // Mapping between Linenumber to IdManuChannel (The object is not owned by this component).
        
        //bool ReadDDL(const AliHLTUInt32_t* rawData, AliHLTUInt32_t rawDataSize);
        bool DecodeDDL(const AliHLTUInt32_t* rawData, AliHLTUInt32_t rawDataSize);
index b75b26d..c8e05ac 100644 (file)
 #include <cstdlib>
 #include <cerrno>
 #include <cassert>
+#include <fstream>
 
 //STEER 
 #include "AliCDBManager.h"
+#include "AliCDBStorage.h"
 #include "AliGeomManager.h"
 
 //MUON
@@ -65,6 +67,8 @@ AliHLTMUONHitReconstructorComponent::AliHLTMUONHitReconstructorComponent() :
        AliHLTProcessor(),
        fHitRec(NULL),
        fDDL(-1),
+       fLutSize(0),
+       fLut(NULL),
        fIdToEntry(),
        fWarnForUnexpecedBlock(false)
 {
@@ -84,6 +88,10 @@ AliHLTMUONHitReconstructorComponent::~AliHLTMUONHitReconstructorComponent()
        {
                delete fHitRec;
        }
+       if (fLut != NULL)
+       {
+               delete fLut;
+       }
 }
 
 const char* AliHLTMUONHitReconstructorComponent::GetComponentID()
@@ -147,8 +155,8 @@ int AliHLTMUONHitReconstructorComponent::DoInit(int argc, const char** argv)
 
        HLTInfo("Initialising dHLT hit reconstruction component.");
        
-       // Must make sure that fHitRec is deleted if it is still allocated for
-       // whatever reason.
+       // Must make sure that fHitRec and fLut is deleted if it is still
+       // allocated for whatever reason.
        FreeMemory();
        
        try
@@ -188,7 +196,7 @@ int AliHLTMUONHitReconstructorComponent::DoInit(int argc, const char** argv)
                        unsigned long num = strtoul( argv[i+1], &cpErr, 0 );
                        if (cpErr == NULL or *cpErr != '\0')
                        {
-                               HLTError("Cannot convert '%s' to DDL Number ", argv[i+1] );
+                               HLTError("Cannot convert '%s' to DDL a number.", argv[i+1] );
                                FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
                                return -EINVAL;
                        }
@@ -198,7 +206,7 @@ int AliHLTMUONHitReconstructorComponent::DoInit(int argc, const char** argv)
                                FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
                                return -EINVAL;
                        }
-                       fDDL = num - 1;
+                       fDDL = num - 1;  // convert to range [12..19]
                        
                        i++;
                        continue;
@@ -273,76 +281,34 @@ int AliHLTMUONHitReconstructorComponent::DoInit(int argc, const char** argv)
        
        } // for loop
        
+       if (lutFileName == NULL) useCDB = true;
+       
        if (fDDL == -1)
        {
                HLTWarning("DDL number not specified. Cannot check if incomming data is valid.");
        }
        
-       if (lutFileName == NULL) useCDB = true;
-       
-       AliHLTMUONHitRecoLutRow* lookupTable = NULL;
-       
+       int result = 0;
        if (useCDB)
        {
-               if (not ReadCDB(lookupTable,cdbPath,run))
-               {
-                       HLTError("Failed to read cdb, cdb cannot be read, DoInit");
-                       FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
-                       if (lookupTable != NULL)
-                               delete [] lookupTable;
-                       return -ENOENT;
-               }
+               HLTInfo("Loading lookup table information from CDB for DDL %d.", fDDL+1);
+               if (fDDL == -1)
+                       HLTWarning("DDL number not specified. The lookup table loaded from CDB will be empty!");
+               result = ReadCDB(cdbPath, run);
        }
        else
        {
-               AliHLTUInt32_t lutLine;
-               if (not GetLutLine(lutFileName, lutLine))
-               {
-                       HLTError("Failed for lookuptable count the number of lines in lookuptable, DoInit");
-                       FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
-                       return -EIO;
-               }
-       
-               try
-               {
-                       lookupTable = new AliHLTMUONHitRecoLutRow[lutLine];
-               }
-               catch(const std::bad_alloc&)
-               {
-                       HLTError("Dynamic memory allocation failed for lookuptable, DoInit");
-                       FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
-                       return -ENOMEM;
-               }
-       
-               if (not ReadLookUpTable(lookupTable, lutFileName))
-               {
-                       HLTError("Failed to read lut, lut cannot be read, DoInit");
-                       FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
-                       if (lookupTable != NULL)
-                               delete [] lookupTable;
-                       return -ENOENT;
-               }
-       }
-       
-       if (not fHitRec->SetIdManuChannelToEntry(fIdToEntry))
-       {
-               HLTError("Failed to set fIdToEntry mapping, DoInit");
-               FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
-               if (lookupTable != NULL)
-                       delete [] lookupTable;
-               return -ENOENT;
+               HLTInfo("Loading lookup table information from file %s.", lutFileName);
+               result = ReadLookUpTable(lutFileName);
        }
-       
-       if (not fHitRec->LoadLookUpTable(lookupTable, fDDL))
+       if (result != 0)
        {
-               HLTError("Cannot Laod hitrec lookuptable , DoInit");
+               // Error messages already generated in ReadCDB or ReadLookUpTable.
                FreeMemory(); // Make sure we cleanup to avoid partial initialisation.
-               if (lookupTable != NULL)
-                       delete [] lookupTable;
-               return -ENOENT;
+               return result;
        }
        
-       delete [] lookupTable;
+       fHitRec->SetLookUpTable(fLut, &fIdToEntry);
        
        return 0;
 }
@@ -501,259 +467,400 @@ void AliHLTMUONHitReconstructorComponent::FreeMemory()
        /// Deletes any allocated objects if they are allocated else nothing is
        /// done for objects not yet allocated.
        /// This is used as a helper method to make sure the corresponding pointers
-       /// are NULL and we are back to a well defined state.
+       /// are NULL and we get back to a well defined state.
 
        if (fHitRec != NULL)
        {
                delete fHitRec;
                fHitRec = NULL;
        }
+       if (fLut != NULL)
+       {
+               delete fLut;
+               fLut = NULL;
+               fLutSize = 0;
+       }
        
        fIdToEntry.clear();
 }
 
 
-bool AliHLTMUONHitReconstructorComponent::GetLutLine(
-               const char* lutFileName, AliHLTUInt32_t& iLine
-       )
+int AliHLTMUONHitReconstructorComponent::ReadLookUpTable(const char* lutFileName)
 {
-  // Reads LUT from CDB.
-  // TODO: combine this with ReadLookUpTable().
-  
-  ifstream fin(lutFileName);
-
-  if(!fin){
-    HLTError("Failed to open file '%s' ",lutFileName);
-    return false;
-  }
-
-  string s;
-  iLine = 0;
-  while(getline(fin,s)){
-    iLine++;
-  }
-
-  fin.close();
-
-  return true;
+       /// Read in the lookup table from a text file.
+       /// Note that this method could leave fLut allocated which is cleaned up
+       /// by DoInit with a call to FreeMemory().
+       
+       assert( fLut == NULL );
+       assert( fLutSize == 0 );
+       assert( fIdToEntry.empty() );
+       
+       std::ifstream file(lutFileName);
+       if (not file.good())
+       {
+               HLTError("Could not open the LUT file %s", lutFileName);
+               return -ENOENT;
+       }
+       
+       // First count the number of lines of text in the LUT file before decoding.
+       // This is not the most optimal. It would be better to read and decode at the
+       // same time but we are not allowed to use STL and ROOT containers are too
+       // heavy for this task. At least this is done only at the start of run.
+       std::string str;
+       AliHLTUInt32_t lineCount = 0;
+       while (std::getline(file, str)) lineCount++;
+       if (not file.eof())
+       {
+               HLTError("There was a problem reading the LUT file %s", lutFileName);
+               return -EIO;
+       }
+       if (lineCount == 0)
+       {
+               HLTWarning("The LUT file %s was empty.", lutFileName);
+       }
+       
+       // Add one extra LUT line for the first element which is used as a sentinel value.
+       lineCount++;
+       
+       try
+       {
+               fLut = new AliHLTMUONHitRecoLutRow[lineCount];
+               fLutSize = lineCount;
+       }
+       catch (const std::bad_alloc&)
+       {
+               HLTError("Could not allocate more memory for the lookuptable.");
+               return -ENOMEM;
+       }
+       
+       // Initialise the sentinel value.
+       fLut[0].fDetElemId = 0;
+       fLut[0].fIX = 0;
+       fLut[0].fIY = 0;
+       fLut[0].fRealX = 0.0;
+       fLut[0].fRealY = 0.0;
+       fLut[0].fRealZ = 0.0;
+       fLut[0].fHalfPadSize = 0.0;
+       fLut[0].fPlane = -1;
+       fLut[0].fPed = -1;
+       fLut[0].fSigma = -1;
+       fLut[0].fA0 = -1;
+       fLut[0].fA1 = -1;
+       fLut[0].fThres = -1;
+       fLut[0].fSat = -1;
+       
+       // Clear the eof flag and start reading from the beginning of the file again.
+       file.clear();
+       file.seekg(0, std::ios::beg);
+       if (not file.good())
+       {
+               HLTError("There was a problem seeking in the LUT file %s", lutFileName);
+               return -EIO;
+       }
+       
+       AliHLTInt32_t idManuChannel;
+       for (AliHLTUInt32_t i = 1; i < fLutSize; i++)
+       {
+               if (std::getline(file, str).fail())
+               {
+                       HLTError("There was a problem reading line %d of LUT file %s", i, lutFileName);
+                       return -EIO;
+               }
+               
+               int result = sscanf(
+                       str.c_str(), "%d\t%d\t%d\t%d\t%e\t%e\t%e\t%e\t%d\t%e\t%e\t%e\t%e\t%d\t%d",
+                       &idManuChannel, &fLut[i].fDetElemId, &fLut[i].fIX,
+                       &fLut[i].fIY, &fLut[i].fRealX,
+                       &fLut[i].fRealY, &fLut[i].fRealZ,
+                       &fLut[i].fHalfPadSize, &fLut[i].fPlane,
+                       &fLut[i].fPed, &fLut[i].fSigma, &fLut[i].fA0,
+                       &fLut[i].fA1, &fLut[i].fThres, &fLut[i].fSat
+               );
+               
+               if (result != 15)
+               {
+                       HLTError("Line %d in LUT file %s does not contain 15 elements.", i, lutFileName);
+                       return -EIO;
+               }
+               
+               fIdToEntry[idManuChannel] = i;
+       }
+       
+       return 0;
 }
 
 
-bool AliHLTMUONHitReconstructorComponent::ReadLookUpTable(
-               AliHLTMUONHitRecoLutRow* lookupTable, const char* lutFileName
-       )
+int AliHLTMUONHitReconstructorComponent::ReadCDB(const char* cdbPath, Int_t run)
 {
-       ///
-       /// Read in the lookup table from a text file.
-       ///
-  
-  if (fDDL < AliHLTMUONHitReconstructor::GetkDDLOffSet() ||
-      fDDL >= AliHLTMUONHitReconstructor::GetkDDLOffSet() + AliHLTMUONHitReconstructor::GetkNofDDL())
-  {
-    HLTError("DDL number is out of range");
-    return false;
-  }
-  
-  AliHLTUInt32_t lutLine;
-  if(!GetLutLine(lutFileName, lutLine)){
-    HLTError("Failed for lookuptable count the number of lines in lookuptable, DoInit");
-    
-    return false;
-  }
-  
-  int idManuChannel;
-  fIdToEntry.clear();
-  
-  FILE *fin = fopen(lutFileName,"r");
-  if(fin == NULL){
-    printf("Failed to open file %s\n",lutFileName);
-    return false;
-  }else{
-    for(AliHLTUInt32_t i=0;i<lutLine;i++){
-      fscanf(fin,"%d\t%d\t%d\t%d\t%f\t%f\t%f\t%f\t%d\t%f\t%f\t%f\t%f\t%d\t%d\n",
-            &idManuChannel,&lookupTable[i].fDetElemId,&lookupTable[i].fIX,
-            &lookupTable[i].fIY,&lookupTable[i].fRealX,
-            &lookupTable[i].fRealY,&lookupTable[i].fRealZ,
-            &lookupTable[i].fHalfPadSize,&lookupTable[i].fPlane,
-            &lookupTable[i].fPed,&lookupTable[i].fSigma,&lookupTable[i].fA0,
-            &lookupTable[i].fA1,&lookupTable[i].fThres,&lookupTable[i].fSat);
-      
-      fIdToEntry[idManuChannel] = i+1;
-
-      
-    }
-  }
-
-  fclose(fin);
-
-  return true;
+       // Reads LUT from CDB.
+       // TODO: merge this with CreateHitRecoLookupTables.C, make this static and use in the macro for example.
+
+       assert( fLut == NULL );
+       assert( fLutSize == 0 );
+       assert( fIdToEntry.empty() );
+       
+       std::vector<AliHLTMUONHitRecoLutRow> lutList;
+       AliHLTMUONHitRecoLutRow lut;
+       AliHLTUInt32_t iEntry = 0;
+       
+       Bool_t warn = kFALSE;
+       
+       AliCDBManager* cdbManager = AliCDBManager::Instance();
+       if (cdbManager == NULL)
+       {
+               HLTError("CDB manager instance does not exist.");
+               return -EIO;
+       }
+       
+       const char* cdbPathUsed = "unknown (not set)";
+       if (cdbPath != NULL)
+       {
+               cdbManager->SetDefaultStorage(cdbPath);
+               cdbPathUsed = cdbPath;
+       }
+       else
+       {
+               AliCDBStorage* store = cdbManager->GetDefaultStorage();
+               if (store != NULL) cdbPathUsed = store->GetURI().Data();
+       }
+       
+       if (run != -1) cdbManager->SetRun(run);
+       Int_t runUsed = cdbManager->GetRun();
+       
+       if (not AliMpCDB::LoadDDLStore(warn))
+       {
+               HLTError("Failed to load DDL store specified for CDB path '%s' and run no. %d",
+                       cdbPathUsed, runUsed
+               );
+               return -ENOENT;
+       }
+       AliMpDDLStore* ddlStore = AliMpDDLStore::Instance();
+       if (ddlStore == NULL)
+       {
+               HLTError("Could not find DDL store instance.");
+               return -EIO;
+       }
+       AliMpSegmentation* mpSegFactory = AliMpSegmentation::Instance();
+       if (mpSegFactory == NULL)
+       {
+               HLTError("Could not find segmentation mapping (AliMpSegmentation) instance.");
+               return -EIO;
+       }
+       
+       AliGeomManager::LoadGeometry();
+       AliMUONGeometryTransformer chamberGeometryTransformer;
+       if (not chamberGeometryTransformer.LoadGeometryData())
+       {
+               HLTError("Failed to load geomerty data.");
+               return -ENOENT;
+       }
+       
+       AliMUONCalibrationData calibData(run);
+       
+       Int_t chamberId;
+       
+       for(Int_t iCh = 6; iCh < 10; iCh++)
+       {
+               chamberId = iCh;
+               
+               AliMpDEIterator it;
+               for ( it.First(chamberId); ! it.IsDone(); it.Next() )
+               {
+                       Int_t detElemId = it.CurrentDEId();
+                       int iDDL = ddlStore->GetDetElement(detElemId)->GetDdlId();
+                       if (iDDL != fDDL) continue;
+               
+                       for (Int_t iCath = 0 ; iCath <= 1 ; iCath++)
+                       {
+                               AliMp::CathodType cath;
+                               
+                               if(iCath == 0)
+                                       cath = AliMp::kCath0;
+                               else
+                                       cath = AliMp::kCath1;
+                               
+                               const AliMpVSegmentation* seg = mpSegFactory->GetMpSegmentation(detElemId, cath);
+                               AliMp::PlaneType plane = seg->PlaneType();
+                               Int_t maxIX = seg->MaxPadIndexX();
+                               Int_t maxIY = seg->MaxPadIndexY();
+                               
+                               Int_t idManuChannel, manuId, channelId, buspatchId;
+                               AliHLTFloat32_t padSizeX, padSizeY;
+                               AliHLTFloat32_t halfPadSize;
+                               Double_t realX, realY, realZ;
+                               Double_t localX, localY, localZ;
+                               Float_t calibA0Coeff,calibA1Coeff,pedestal,sigma;
+                               Int_t thresold,saturation;
+                               
+                               // Pad Info of a slat to print in lookuptable
+                               for (Int_t iX = 0; iX<= maxIX ; iX++)
+                               for (Int_t iY = 0; iY<= maxIY ; iY++)
+                               {
+                                       if (not seg->HasPad(AliMpIntPair(iX,iY))) continue;
+
+                                       AliMpPad pad = seg->PadByIndices(AliMpIntPair(iX,iY), kFALSE);
+                                       
+                                       // Getting Manu id
+                                       manuId = pad.GetLocation().GetFirst();
+                                       manuId &= 0x7FF; // 11 bits 
+                       
+                                       buspatchId = ddlStore->GetBusPatchId(detElemId,manuId);
+                                       
+                                       // Getting channel id
+                                       channelId =  pad.GetLocation().GetSecond();
+                                       channelId &= 0x3F; // 6 bits
+                                       
+                                       idManuChannel = buspatchId << 11;
+                                       idManuChannel = (idManuChannel | manuId) << 6;
+                                       idManuChannel |= channelId;
+                                       
+                                       localX = pad.Position().X();
+                                       localY = pad.Position().Y();
+                                       localZ = 0.0;
+                                       
+                                       chamberGeometryTransformer.Local2Global(
+                                               detElemId,localX,localY,localZ,
+                                               realX,realY,realZ
+                                       );
+                                       
+                                       padSizeX = pad.Dimensions().X();
+                                       padSizeY = pad.Dimensions().Y();
+                                       
+                                       calibA0Coeff = (calibData.Gains(detElemId, manuId))->ValueAsFloat(channelId, 0);
+                                       calibA1Coeff = (calibData.Gains(detElemId, manuId))->ValueAsFloat(channelId, 1);
+                                       thresold = (calibData.Gains(detElemId, manuId))->ValueAsInt(channelId, 2);
+                                       saturation = (calibData.Gains(detElemId, manuId))->ValueAsInt(channelId, 4);
+                                       
+                                       pedestal = (calibData.Pedestals(detElemId, manuId))->ValueAsFloat(channelId, 0);
+                                       sigma = (calibData.Pedestals(detElemId, manuId))->ValueAsFloat(channelId, 1);
+                                       
+                                       if (plane == 0)
+                                               halfPadSize = padSizeX;
+                                       else
+                                               halfPadSize = padSizeY;
+                                       
+                                       fIdToEntry[idManuChannel] = iEntry+1;
+                       
+                                       lut.fDetElemId = detElemId;
+                                       lut.fIX = iX;
+                                       lut.fIY = iY;
+                                       lut.fRealX = realX;
+                                       lut.fRealY = realY;
+                                       lut.fRealZ = realZ;
+                                       lut.fHalfPadSize = halfPadSize;
+                                       lut.fPlane = plane;
+                                       lut.fPed = pedestal;
+                                       lut.fSigma = sigma;
+                                       lut.fA0 = calibA0Coeff;
+                                       lut.fA1 = calibA1Coeff;
+                                       lut.fThres = thresold;
+                                       lut.fSat = saturation;
+                                       
+                                       lutList.push_back(lut);
+                                       iEntry++;
+                               } // iX, iY loop
+                       } // iCath loop
+               } // detElemId loop
+       } // ichamber loop
+
+       try
+       {
+               // Use iEntry+1 since we add one extra LUT line for the first element
+               // which is used as a sentinel value.
+               fLut = new AliHLTMUONHitRecoLutRow[iEntry+1];
+               fLutSize = iEntry+1;
+       }
+       catch (const std::bad_alloc&)
+       {
+               HLTError("Could not allocate more memory for the lookuptable.");
+               return -ENOMEM;
+       }
+       
+       // Initialise the sentinel value.
+       fLut[0].fDetElemId = 0;
+       fLut[0].fIX = 0;
+       fLut[0].fIY = 0;
+       fLut[0].fRealX = 0.0;
+       fLut[0].fRealY = 0.0;
+       fLut[0].fRealZ = 0.0;
+       fLut[0].fHalfPadSize = 0.0;
+       fLut[0].fPlane = -1;
+       fLut[0].fPed = -1;
+       fLut[0].fSigma = -1;
+       fLut[0].fA0 = -1;
+       fLut[0].fA1 = -1;
+       fLut[0].fThres = -1;
+       fLut[0].fSat = -1;
+       
+       for (AliHLTUInt32_t i = 0; i < iEntry; i++)
+               fLut[i+1] = lutList[i];
+       
+       return 0;
 }
 
 
-bool AliHLTMUONHitReconstructorComponent::ReadCDB(
-               AliHLTMUONHitRecoLutRow*& lookupTable,
+bool AliHLTMUONHitReconstructorComponent::GenerateLookupTable(
+               AliHLTInt32_t ddl, const char* filename,
                const char* cdbPath, Int_t run
        )
 {
-  // Reads LUT from CDB.
-  // TODO: merge this with CreateHitRecoLookupTables.C, make this static and use in the macro for example.
-
-  vector<AliHLTMUONHitRecoLutRow> lutList;
-  lutList.clear();
-  AliHLTMUONHitRecoLutRow lut;
-  int iEntry = 0;
-
-  Bool_t warn = kTRUE;
-
-  AliCDBManager* cdbManager = AliCDBManager::Instance();
-  if (cdbPath != NULL) cdbManager->SetDefaultStorage(cdbPath);
-  if (run != -1) cdbManager->SetRun(run);
-
-  if (! AliMpCDB::LoadDDLStore(warn)){
-    HLTError("Failed to Load DDLStore specified for CDBPath '%s', and Run : '%d'",cdbPath,run);
-    return false;
-  }
-
-  AliMpSegmentation *mpSegFactory = AliMpSegmentation::Instance();
-  AliGeomManager::LoadGeometry();
-  AliMUONGeometryTransformer* chamberGeometryTransformer = new AliMUONGeometryTransformer();
-  if(! chamberGeometryTransformer->LoadGeometryData()){
-    HLTError("Failed to Load Geomerty Data ");
-    return false;
-  }
-  
-  AliMUONCalibrationData calibData(run);
-
-  int totMaxIX = -1;
-  int totMaxIY = -1;
-  Int_t chamberId;
-
-  for(Int_t iCh = 6; iCh < 10; iCh++){ // max 4
-
-    chamberId = iCh ;
-
-    AliMpDEIterator it;
-    for ( it.First(chamberId); ! it.IsDone(); it.Next() ) {
-    
-      Int_t detElemId = it.CurrentDEId();
-      int iDDL = AliMpDDLStore::Instance()->GetDetElement(detElemId)->GetDdlId() + 1;
-      if(iDDL == fDDL){
-
-       for(Int_t iCath = 0 ; iCath <= 1 ; iCath++){
-       
-         AliMp::CathodType cath;
-         
-         if(iCath == 0)
-           cath = AliMp::kCath0 ;
-         else
-         cath = AliMp::kCath1 ;
-         
-         const AliMpVSegmentation* seg = mpSegFactory->GetMpSegmentation(detElemId, cath);
-         AliMp::PlaneType plane = seg->PlaneType(); 
-         Int_t maxIX = seg->MaxPadIndexX();  
-         Int_t maxIY = seg->MaxPadIndexY(); 
-         if(maxIX > totMaxIX)
-           totMaxIX = maxIX;
-         if(maxIY > totMaxIY)
-           totMaxIY = maxIY;
-         
-         Int_t idManuChannel, manuId, channelId, buspatchId;
-         float padSizeX, padSizeY;
-         float halfPadSize ;
-         Double_t realX, realY, realZ;
-         Double_t localX, localY, localZ;
-         Float_t calibA0Coeff,calibA1Coeff,pedestal,sigma;
-         Int_t thresold,saturation;
-         
-         //    cout<<"Running for detElemId :"<<detElemId<<", and plane : "<<plane<<endl;
-         //Pad Info of a segment to print in lookuptable
-         for(Int_t iX = 0; iX<= maxIX ; iX++){
-           for(Int_t iY = 0; iY<= maxIY ; iY++){
-             if(seg->HasPad(AliMpIntPair(iX,iY))){
-               AliMpPad pad = seg->PadByIndices(AliMpIntPair(iX,iY),kFALSE);
-               
-               // Getting Manu id
-               manuId = pad.GetLocation().GetFirst();
-               manuId &= 0x7FF; // 11 bits 
-
-               buspatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId,manuId);
-               
-               // Getting channel id
-               channelId =  pad.GetLocation().GetSecond();
-               channelId &= 0x3F; // 6 bits
-               
-               idManuChannel &= 0x0;
-               idManuChannel = (idManuChannel|buspatchId)<<11;  
-               idManuChannel = (idManuChannel|manuId)<<6 ;
-               idManuChannel |= channelId ;
-               
-               localX = pad.Position().X();
-               localY = pad.Position().Y();
-               localZ = 0.0;
-               
-               chamberGeometryTransformer->Local2Global(detElemId,localX,localY,localZ,
-                                                      realX,realY,realZ);
-               
-               padSizeX = pad.Dimensions().X();
-               padSizeY = pad.Dimensions().Y();
-               
-               calibA0Coeff = (calibData.Gains(detElemId,manuId))->ValueAsFloat(channelId,0) ;
-               calibA1Coeff = (calibData.Gains(detElemId,manuId))->ValueAsFloat(channelId,1) ;
-               thresold = (calibData.Gains(detElemId,manuId))->ValueAsInt(channelId,2) ;
-               saturation = (calibData.Gains(detElemId,manuId))->ValueAsInt(channelId,4) ;
-               
-               pedestal = (calibData.Pedestals(detElemId,manuId))->ValueAsFloat(channelId,0);
-               sigma = (calibData.Pedestals(detElemId,manuId))->ValueAsFloat(channelId,1);
+       /// Generates a ASCII text file containing the lookup table (LUT) from
+       /// the CDB, which can be used for the hit reconstructor component later.
+       /// @param ddl  Must be the DDL for which to generate the DDL,
+       ///             in the range [13..20].
+       /// @param filename  The name of the LUT file to generate.
+       /// @param cdbPath  The CDB path to use.
+       /// @param run  The run number to use for the CDB.
+       /// @return  True if the generation of the LUT file succeeded.
+       
+       AliHLTMUONHitReconstructorComponent comp;
+       
+       if (ddl < 12 or 19 < ddl)
+       {
+               std::cerr << "ERROR: the DDL number must be in the range [12..19]." << std::endl;
+               return false;
+       }
+       
+       comp.fDDL = ddl;
+       if (comp.ReadCDB(cdbPath, run) != 0) return false;
+       
+       char str[1024*4];
+       std::fstream file(filename, std::ios::out);
+       if (not file)
+       {
+               std::cerr << "ERROR: could not open file: " << filename << std::endl;
+               return false;
+       }
+       
+       assert( comp.fLut != NULL );
+       
+       for (IdManuChannelToEntry::iterator id = comp.fIdToEntry.begin();
+            id != comp.fIdToEntry.end();
+            id++
+           )
+       {
+               AliHLTInt32_t idManuChannel = id->first;
+               AliHLTInt32_t row = id->second;
                
-               if(plane==0)
-                 halfPadSize = padSizeX;
-               else
-                 halfPadSize = padSizeY;
+               assert( row < comp.fLutSize );
                
-               fIdToEntry[idManuChannel] = iEntry+1;
-
-               lut.fDetElemId = detElemId;
-               lut.fIX = iX;
-               lut.fIY = iY;
-               lut.fRealX = realX;
-               lut.fRealY = realY;
-               lut.fRealZ = realZ;
-               lut.fHalfPadSize = halfPadSize;
-               lut.fPlane = plane;
-               lut.fPed = pedestal;
-               lut.fSigma = sigma;
-               lut.fA0 = calibA0Coeff;
-               lut.fA1 = calibA1Coeff;
-               lut.fThres = thresold;
-               lut.fSat = saturation;
+               sprintf(str, "%d\t%d\t%d\t%d\t%.15e\t%.15e\t%.15e\t%.15e\t%d\t%.15e\t%.15e\t%.15e\t%.15e\t%d\t%d",
+                       idManuChannel, comp.fLut[row].fDetElemId, comp.fLut[row].fIX,
+                       comp.fLut[row].fIY, comp.fLut[row].fRealX,
+                       comp.fLut[row].fRealY, comp.fLut[row].fRealZ,
+                       comp.fLut[row].fHalfPadSize, comp.fLut[row].fPlane,
+                       comp.fLut[row].fPed, comp.fLut[row].fSigma, comp.fLut[row].fA0,
+                       comp.fLut[row].fA1, comp.fLut[row].fThres, comp.fLut[row].fSat
+               );
                
-               lutList.push_back(lut);
-               iEntry++;
-             }// HasPad Condn
-           }// iY loop
-         }// iX loop
-       
-       }// iPlane
-      }// iDDL
-    } // detElemId loop
-
-  }// ichamber loop
-
-  AliHLTMUONHitRecoLutRow *temp;
-
-  try{
-    temp = new AliHLTMUONHitRecoLutRow[iEntry];
-  }
-  catch(const std::bad_alloc&){
-    HLTError("Dynamic memory allocation failed for temp");
-
-    return false;
-  }
-  
-  for(int iterm = 0; iterm < iEntry ;iterm++)
-    temp[iterm] = lutList.at(iterm);
-  
-  lookupTable = temp;
-
-  return true;
+               file << str << endl;
+               if (file.fail())
+               {
+                       std::cerr << "ERROR: There was an I/O error when writing to the file: "
+                               << filename << std::endl;
+                       return false;
+               }
+       }
+       
+       return true;
 }
index 7e487be..dcb8942 100644 (file)
 ///
 
 #include "AliHLTProcessor.h"
+#include "AliHLTMUONHitReconstructor.h"
 
 #if __GNUC__ && __GNUC__ < 3
 #define std
 #endif
 
-// TODO: see if we can remove the following header somehow.
-#include "AliHLTMUONHitReconstructor.h"
-//class AliHLTMUONHitReconstructor;
 
 extern "C" struct AliHLTMUONHitRecoLutRow;
 
@@ -41,6 +39,21 @@ public:
        virtual void GetOutputDataSize( unsigned long& constBase, double& inputMultiplier );
        virtual AliHLTComponent* Spawn();
        
+       /**
+        * Generates a ASCII text file containing the lookup table (LUT) from
+        * the CDB, which can be used for the hit reconstructor component later.
+        * @param ddl  Must be the DDL for which to generate the DDL,
+        *             in the range [12..19].
+        * @param filename  The name of the LUT file to generate.
+        * @param cdbPath  The CDB path to use.
+        * @param run  The run number to use for the CDB.
+        * @return  True if the generation of the LUT file succeeded.
+        */
+       static bool GenerateLookupTable(
+                       AliHLTInt32_t ddl, const char* filename,
+                       const char* cdbPath, Int_t run
+               );
+       
 protected:
        
        // Protected functions to implement AliHLTComponent's interface.
@@ -67,12 +80,13 @@ private:
        AliHLTMUONHitReconstructorComponent& operator = (const AliHLTMUONHitReconstructorComponent& /*obj*/);
        
        void FreeMemory();
-       bool ReadLookUpTable(AliHLTMUONHitRecoLutRow* lookupTable, const char* lutpath);
-       bool ReadCDB(AliHLTMUONHitRecoLutRow*& lookupTable, const char* cdbpath, Int_t run);
-       bool GetLutLine(const char* lutPath, AliHLTUInt32_t& iLine); // To count the nof lines in lookuptable
+       int ReadLookUpTable(const char* lutpath);
+       int ReadCDB(const char* cdbpath, Int_t run);
+       
        AliHLTMUONHitReconstructor* fHitRec;  // Internal class instance implementing the hit reconstruction algorithm.
-       AliHLTInt32_t fDDL;  // DDL number in the range [13..20]. Set to -1 for invalid/unspecified value.
+       AliHLTInt32_t fDDL;  // DDL number in the range [12..19]. Set to -1 for invalid/unspecified value.
+       AliHLTUInt32_t fLutSize;  // The number of rows / entries in the LUT.
+       AliHLTMUONHitRecoLutRow* fLut;  // The lookup table used by the hit reconstruction algorithm (Owned by this component however).
        IdManuChannelToEntry fIdToEntry; // id to line mapping.
        bool fWarnForUnexpecedBlock;  // Flag indicating if we should log a warning if we got a block of an unexpected type.
        
index a78b4b0..70a178a 100644 (file)
@@ -1,5 +1,5 @@
 /**************************************************************************
- * This file is property of and copyright by the ALICE HLT Project        * 
+ * This file is property of and copyright by the ALICE HLT Project        *
  * All rights reserved.                                                   *
  *                                                                        *
  * Primary Authors:                                                       *
  * without fee, provided that the above copyright notice appears in all   *
  * copies and that both the copyright notice and this permission notice   *
  * appear in the supporting documentation. The authors make no claims     *
- * about the suitability of this software for any purpose. It is          * 
+ * about the suitability of this software for any purpose. It is          *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/*********************************************
+/* $Id$ */
+
+/**
+ * \ingroup macros
+ * \file CreateHitRecoLookupTables.C
+ * \brief Macro used to generate lookup tables for the hit reconstructor components.
+ *
+ * This macro is used to generate the lookup tables for the hit reconstructor
+ * component. All alignment and geometry data is taken from the CDB.
+ *
+ * \note The LUT files must be generated on the same platform / machine on which
+ * they will be used, since they may not be binary compatible across platforms.
+ *
+ * To run this macro copy "rootlogon.C" from $ALICE_ROOT/HLT/MUON/macros
+ * into the current directory, then from the shell command prompt run one of
+ * the following commands:
+ * \code
+ *   > aliroot $ALICE_ROOT/HLT/MUON/macros/CreateHitRecoLookupTables.C
+ * \endcode
+ * or
+ * \code
+ *   > aliroot -b -q -l $ALICE_ROOT/HLT/MUON/macros/CreateHitRecoLookupTables.C+
+ * \endcode
+ *
+ * \author Indranil Das <indra.das@saha.ac.in>
+ */
+
+/*
 Purpose:  A macro to generate LookupTable
           in the following form
 buspatchId+manuid+channelId  buspatchId Ix  IY  X  Y  B/NB
@@ -25,173 +52,47 @@ Modified: 09/02/2006
 Modified: 09/04/2007
 Modified: 24/08/2007 (To adopt to AliRoot v4-06-Release)
 
-Run Info: To run this code copy "rootlogon.C" 
-          in the current directory from $ALICE_ROOT/MUON 
-           then compile and run using
-          .L CreateHitRecoLookupTables.C+
+Run Info: To run this macro copy "rootlogon.C" from $ALICE_ROOT/HLT/MUON/macros
+  into the current directory then compile and run from inside AliRoot using
+      root [0] .x CreateHitRecoLookupTables.C+
 
 Author:   Indranil Das, HEP, SINP, Kolkata
 Email:    indra.das@saha.ac.in
-***********************************************/
 
-#include <iostream> 
-
-//STEER 
-#include "AliCDBManager.h"
-#include "AliGeomManager.h"
-
-//MUON
-#include "AliMUONGeometryTransformer.h"
-#include "AliMUONCalibrationData.h"
-#include "AliMUONVCalibParam.h"
-
-//MUON/mapping 
-#include "AliMpCDB.h"
-#include "AliMpPad.h"
-#include "AliMpSegmentation.h"
-#include "AliMpDDLStore.h"
-#include "AliMpDEIterator.h"
-#include "AliMpVSegmentation.h"
-#include "AliMpDEManager.h"
-#include <AliMpDetElement.h>
-
-using namespace std;
-
-Bool_t CreateHitRecoLookupTables(TString CDBPath = "local://$ALICE_ROOT", Int_t run = 0, Bool_t warn = kTRUE)
+18 Apr 2008: Moved lookup table generation code to the AliHLTMUONHitReconstructorComponent
+component since it is required there anyway and we want to avoid code duplication.
+This also makes this macro much cleaner.
+    -- Artur Szostak <artursz@iafrica.com>
+*/
+
+#if !defined(__CINT__) || defined(__MAKECINT__)
+#include "Riostream.h"
+#include "AliHLTMUONHitReconstructorComponent.h"
+#include "TSystem.h"
+#endif
+
+/**
+ * Generates the ASCII lookup tables for the AliHLTMUONHitReconstructorComponent
+ * components. The tables are generated from the CDB database information.
+ * \param CDBPath  This is the CDB path to use as the DB storage.
+ *                 (Default = local://$ALICE_ROOT)
+ * \param run  This is the run number to use for the CDB (Default = 0).
+ */
+void CreateHitRecoLookupTables(const char* CDBPath = "local://$ALICE_ROOT", Int_t run = 0)
 {
-  Char_t filename1[50];
-  Int_t chamberId;
-  
-  AliCDBManager* cdbManager = AliCDBManager::Instance();
-  cdbManager->SetDefaultStorage(CDBPath.Data());
-  cdbManager->SetRun(run);
-
-  if (! AliMpCDB::LoadDDLStore(warn)){
-    cerr<<__FILE__<<": Failed to Load DDLStore specified for CDBPath "<<CDBPath<<", and Run : "<<run<<endl;
-    return kFALSE;
-  }
-
-  AliMpSegmentation *mpSegFactory = AliMpSegmentation::Instance(); 
-  AliGeomManager::LoadGeometry();
-  AliMUONGeometryTransformer* chamberGeometryTransformer = new AliMUONGeometryTransformer();
-  if(! chamberGeometryTransformer->LoadGeometryData()){
-    cerr<<__FILE__<<": Failed to Load Geomerty Data "<<endl;
-    return kFALSE;
-  }
-  
-  int maxDDL = 8;
-  FILE *fout[maxDDL];
-  for(int iDDL = 0;iDDL<maxDDL; iDDL++){
-    sprintf(filename1,"Lut%d.dat",iDDL+13);
-    fout[iDDL] = fopen(filename1,"w");
-  }
-  
-  AliMUONCalibrationData calibData(run);
-
-  int totMaxIX = -1;
-  int totMaxIY = -1;
-
-  for(Int_t iCh = 6; iCh < 10; iCh++){ // max 4
-
-    chamberId = iCh ;
-
-    AliMpDEIterator it;
-    for ( it.First(chamberId); ! it.IsDone(); it.Next() ) {
-    
-      Int_t detElemId = it.CurrentDEId();
-      int iDDL = AliMpDDLStore::Instance()->GetDetElement(detElemId)->GetDdlId() - 12 ;
-      for(Int_t iCath = 0 ; iCath <= 1 ; iCath++){
-       
-       AliMp::CathodType cath;
-
-       if(iCath == 0)
-         cath = AliMp::kCath0 ;
-       else
-         cath = AliMp::kCath1 ;
-
-       const AliMpVSegmentation* seg = mpSegFactory->GetMpSegmentation(detElemId, cath);
-       AliMp::PlaneType plane = seg->PlaneType(); 
-       Int_t maxIX = seg->MaxPadIndexX();  
-       Int_t maxIY = seg->MaxPadIndexY(); 
-       if(maxIX > totMaxIX)
-         totMaxIX = maxIX;
-       if(maxIY > totMaxIY)
-         totMaxIY = maxIY;
-
-       Int_t idManuChannel, manuId, channelId, buspatchId;
-       float padSizeX, padSizeY;
-       float halfPadSize ;
-       Double_t realX, realY, realZ;
-       Double_t localX, localY, localZ;
-       Float_t calibA0Coeff,calibA1Coeff,pedestal,sigma;
-       Int_t thresold,saturation;
-
-//     cout<<"Running for detElemId :"<<detElemId<<", and plane : "<<plane<<endl;
-       //Pad Info of a segment to print in lookuptable
-       for(Int_t iX = 0; iX<= maxIX ; iX++){
-         for(Int_t iY = 0; iY<= maxIY ; iY++){
-           if(seg->HasPad(AliMpIntPair(iX,iY))){
-             AliMpPad pad = seg->PadByIndices(AliMpIntPair(iX,iY),kFALSE);
-
-             // Getting Manu id
-             manuId = pad.GetLocation().GetFirst();
-             manuId &= 0x7FF; // 11 bits 
-
-             buspatchId = AliMpDDLStore::Instance()->GetBusPatchId(detElemId,manuId);
-             
-             // Getting channel id
-             channelId =  pad.GetLocation().GetSecond();
-             channelId &= 0x3F; // 6 bits
-             
-             idManuChannel &= 0x0;
-             idManuChannel = (idManuChannel|buspatchId)<<11;  
-             idManuChannel = (idManuChannel|manuId)<<6 ;
-             idManuChannel |= channelId ;
-             
-             localX = pad.Position().X();
-             localY = pad.Position().Y();
-             localZ = 0.0;
-
-             chamberGeometryTransformer->Local2Global(detElemId,localX,localY,localZ,
-                                                      realX,realY,realZ);
-
-             padSizeX = pad.Dimensions().X();
-             padSizeY = pad.Dimensions().Y();
-
-             calibA0Coeff = (calibData.Gains(detElemId,manuId))->ValueAsFloat(channelId,0) ;
-             calibA1Coeff = (calibData.Gains(detElemId,manuId))->ValueAsFloat(channelId,1) ;
-             thresold = (calibData.Gains(detElemId,manuId))->ValueAsInt(channelId,2) ;
-             saturation = (calibData.Gains(detElemId,manuId))->ValueAsInt(channelId,4) ;
-
-             pedestal = (calibData.Pedestals(detElemId,manuId))->ValueAsFloat(channelId,0);
-             sigma = (calibData.Pedestals(detElemId,manuId))->ValueAsFloat(channelId,1);
-
-             if(plane==0)
-               halfPadSize = padSizeX;
-             else
-               halfPadSize = padSizeY;
-
-             fprintf(fout[iDDL],"%d\t%d\t%d\t%d\t%f\t%f\t%f\t%f\t%d\t%f\t%f\t%f\t%f\t%d\t%d\n",
-                     idManuChannel,detElemId,iX,iY,realX,realY,realZ,
-                     halfPadSize,plane,pedestal,sigma,calibA0Coeff,calibA1Coeff,thresold,saturation);
-
-           }// HasPad Condn
-         }// iY loop
-       }// iX loop
+       gSystem->Load("libAliHLTMUON.so");
+
+       for (Int_t ddl = 12; ddl < 20; ddl++)
+       {
+               Char_t filename[64];
+               sprintf(filename, "Lut%d.dat", ddl+1);
+               cout << "Generating LUT for DDL " << ddl+1
+                       << " and writing output to file " << filename << endl;
+               bool ok = AliHLTMUONHitReconstructorComponent::GenerateLookupTable(
+                               ddl, filename, CDBPath, run
+                       );
+               if (! ok) return;
+       }
        
-      }// iPlane
-
-    } // detElemId loop
-
-//     fclose(fout1);
-
-  }// ichamber loop
-
-  for(int iDDL = 0;iDDL<maxDDL; iDDL++){
-    fclose(fout[iDDL]);
-  }
-
-//   cout<<"TotMaxIX : "<<totMaxIX<<", and totMaxIY : "<<totMaxIY<<endl;
-  
-  return kTRUE;
+       cout << "Lookup tables have been generated successfully." << endl;
 }