]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/MUONTRGda.cxx
SelectCollisionCandidates added for the task
[u/mrichter/AliRoot.git] / MUON / MUONTRGda.cxx
1 /*
2 MTR DA for online
3
4 Contact: Franck Manso <manso@clermont.in2p3.fr>
5 Link: http://aliceinfo.cern.ch/static/Offline/dimuon/muon_html/README_mtrda.html
6 Reference run: 61898
7 Run Type:  PHYSICS
8 DA Type: MON
9 Number of events needed: 1000 events
10 Input files: MtgGlobalCrate.dat MtgRegionalCrate.dat MtgLocalMask.dat MtgLocalLut.dat MtgCurrent.dat DAConfig.dat
11 Output Files: ExportedFiles.dat MtgGlobalCrate.dat
12 Trigger types used: PHYSICS_EVENT CALIBRATION_EVENT
13 */
14
15 //////////////////////////////////////////////////////////////////////////////
16 // Detector Algorithm for the MUON trigger configuration.                   //
17 //                                                                          //
18 // Calculates masks for the global trigger input, by looking at dead        //
19 // channels in calibration events and at noisy channels in physics events.  //
20 // Transfers trigger configuration files to the File Exchange Server and    //
21 // writes them (if modified) into the trigger configuration data base.      //
22 //                                                                          //
23 // Authors:                                                                 //
24 // Christian Fink (formerly at Subatech, Nantes)                            //
25 // Franck Manso (LPC Clermont-Ferrand, manso@clermont.in2p3.fr)             //
26 // Bogdan Vulpescu (LPC Clermont-Ferrand, vulpescu@clermont.in2p3.fr)       //
27 //                                                                          //
28 //////////////////////////////////////////////////////////////////////////////
29
30 //#define OFFLINE
31
32 extern "C" {
33 #include <daqDA.h>
34 }
35
36 #include "event.h"
37 #include "monitor.h"
38
39 #include <Riostream.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42
43 #include "AliRawReaderDate.h"
44
45 #include "AliMpConstants.h"
46 #include "AliMUONRawStreamTrigger.h"
47 #include "AliMUONRawStreamTriggerHP.h"
48 #include "AliMUONDarcHeader.h"
49 #include "AliMUONRegHeader.h"
50 #include "AliMUONDDLTrigger.h"
51 #include "AliMUONVStore.h"
52 #include "AliMUON1DArray.h"
53 #include "AliMUONTriggerIO.h"
54 #include "AliMUONRegionalTriggerConfig.h"
55 #include "AliMUONGlobalCrateConfig.h"
56 #include "AliMUONVCalibParam.h"
57 #include "AliMUONCalibParamND.h"
58 #include "AliMUONCalibParamNI.h"
59 #include "AliMUONLocalStruct.h"
60
61 #include "TString.h"
62 #include "TSystem.h"
63 #include "TStopwatch.h"
64 #include "TROOT.h"
65 #include "TPluginManager.h"
66 #include "TArrayS.h"
67
68 /// class for DA run parameters and DA working space
69 class AliDAConfig : TObject {
70
71 public:
72
73   AliDAConfig() : 
74     fDAConfigFileName("DAConfig.dat"),
75     fCurrentFileName("MtgCurrent.dat"), 
76     fLastCurrentFileName("MtgLastCurrent.dat"), 
77     fSodName(""),
78     fSodFlag(0),
79     fDAName(""),
80     fDAFlag(0),
81     fDAMode(1),
82     fGlobalFileName(""),
83     fRegionalFileName(""),
84     fLocalMaskFileName(""),
85     fLocalLutFileName(""),
86     fSignatureFileName(""),
87     fGlobalFileVersion(0),
88     fRegionalFileVersion(0),
89     fLocalMaskFileVersion(0),
90     fLocalLutFileVersion(0),
91     fSignatureFileVersion(0),
92     fGlobalFileLastVersion(0),
93     fRegionalFileLastVersion(0),
94     fLocalMaskFileLastVersion(0),
95     fLocalLutFileLastVersion(0),
96     fEventsN(0),
97     fEventsD(0),
98     fPrintLevel(0),
99     fLocalMasks(0x0),
100     fLocalMasksDA(0x0),
101     fRegionalMasks(0x0),
102     fGlobalMasks(0x0),
103     fTriggerIO(new AliMUONTriggerIO),
104     fAlgoNoisyInput(kFALSE),
105     fAlgoDeadcInput(kFALSE),
106     fThrN(0.1),
107     fThrD(0.9),
108     fThrLocN(0.1),
109     fThrLocD(0.9),
110     fMinEvents(10),
111     fSkipEvents(0),
112     fMaxEvents(65535),
113     fWithWarnings(kFALSE),
114     fUseFastDecoder(kFALSE),
115     fNLocalBoard(AliMpConstants::TotalNofLocalBoards()+1),
116     fPatternStoreN(0x0),
117     fPatternStoreD(0x0)
118   {
119     /// default constructor
120     for (Int_t ii = 0; ii < kGlobalInputs; ii++) {
121       for (Int_t il = 0; il < kGlobalInputLength; il++) {
122         fAccGlobalInputN[ii][il] = 0;
123         fAccGlobalInputD[ii][il] = 0;
124       }
125     }
126     fLocalMasks    = new AliMUON1DArray(fNLocalBoard);
127     fLocalMasksDA  = new AliMUON1DArray(fNLocalBoard);
128     fRegionalMasks = new AliMUONRegionalTriggerConfig();
129     fGlobalMasks   = new AliMUONGlobalCrateConfig();
130     fPatternStoreN = new AliMUON1DArray(fNLocalBoard);
131     fPatternStoreD = new AliMUON1DArray(fNLocalBoard);
132
133     // Generate local trigger masks store. All masks are set to FFFF
134     for (Int_t i = 1; i <= AliMpConstants::TotalNofLocalBoards(); i++) {
135       AliMUONVCalibParam* localBoard = new AliMUONCalibParamNI(1,8,i,0,0);
136       for (Int_t x = 0; x < 2; x++) {
137         for (Int_t y = 0; y < 4; y++) {
138           Int_t index = x*4+y;
139           localBoard->SetValueAsInt(index,0,0xFFFF);
140         }
141       }
142       fLocalMasksDA->Add(localBoard);
143     }
144     
145     // Create a default pattern store
146     for (Int_t i = 1; i <= AliMpConstants::TotalNofLocalBoards(); i++) {
147       AliMUONVCalibParam *patN = new AliMUONCalibParamND(2, 64, i, 0, 0.);
148       AliMUONVCalibParam *patD = new AliMUONCalibParamND(2, 64, i, 0, 0.);
149       fPatternStoreN->Add(patN);        
150       fPatternStoreD->Add(patD);        
151     }
152
153   }
154
155   virtual ~AliDAConfig()
156   {
157     /// destructor
158     delete fLocalMasks;
159     delete fLocalMasksDA;
160     delete fRegionalMasks;
161     delete fGlobalMasks; 
162     delete fPatternStoreN;
163     delete fPatternStoreD;
164     delete fTriggerIO;
165   }
166   void PrintConfig()
167   {
168     /// print DA parameters
169     printf("DA config file name: %s \n",GetDAConfigFileName());
170     printf("Current file name: %s \n",GetCurrentFileName());
171     printf("Last current file name: %s \n",GetLastCurrentFileName());
172     printf("Global file name: %s (%d %d)\n",GetGlobalFileName(),GetGlobalFileVersion(),GetGlobalFileLastVersion());
173     printf("Regional file name: %s (%d %d)\n",GetRegionalFileName(),GetRegionalFileVersion(),GetRegionalFileLastVersion());
174     printf("Local mask file name: %s (%d %d)\n",GetLocalMaskFileName(),GetLocalMaskFileVersion(),GetLocalMaskFileLastVersion());
175     printf("Local LUT file name: %s (%d %d)\n",GetLocalLutFileName(),GetLocalLutFileVersion(),GetLocalLutFileLastVersion());
176     printf("Signature file name: %s (%d)\n",GetSignatureFileName(),GetSignatureFileVersion());
177   }
178
179      /// name of the DA configuration file from detector DB
180   const Char_t* GetDAConfigFileName()    { return fDAConfigFileName.Data(); }
181      /// file with current versions of the configuration files, usually MtgCurrent.dat
182   const Char_t* GetCurrentFileName()     { return fCurrentFileName.Data(); }
183      /// last known versions of the configuration files, usually MtgLastCurrent.dat
184   const Char_t* GetLastCurrentFileName() { return fLastCurrentFileName.Data(); }
185
186      /// name of the Start-of-data field in MtgCurrent.dat
187   const Char_t* GetSodName() { return fSodName.Data(); }
188      /// flag value of the Start-of-data field in MtgCurrent.dat
189   Int_t GetSodFlag() const { return fSodFlag; }
190
191      /// name of the Detector Algorithm field in MtgCurrent.dat
192   const Char_t* GetDAName() { return fDAName.Data(); }
193      /// flag value of the Detector Algorithm field in MtgCurrent.dat
194   Int_t GetDAFlag() const { return fDAFlag; }
195      /// DA active mode (GLOBAL or GLOBAL+LOCAL)
196   Int_t GetDAMode() const { return fDAMode; }
197
198      /// global crate configuration file name
199   const Char_t* GetGlobalFileName()    { return fGlobalFileName.Data(); }
200      /// regional crate configuration file name
201   const Char_t* GetRegionalFileName()  { return fRegionalFileName.Data(); }
202      /// masks for the local cards, file name
203   const Char_t* GetLocalMaskFileName() { return fLocalMaskFileName.Data(); }
204      /// transverse momentum Look-Up-Table, file name
205   const Char_t* GetLocalLutFileName()  { return fLocalLutFileName.Data(); }
206      /// signature file name
207   const Char_t* GetSignatureFileName() { return fSignatureFileName.Data(); }
208
209      /// version of the global crate configuration in the detector DB
210   Int_t GetGlobalFileVersion()    const { return fGlobalFileVersion; }
211      /// version of the regional crate configuration in the detector DB
212   Int_t GetRegionalFileVersion()  const { return fRegionalFileVersion; }
213      /// version of the masks for the local cards in the detector DB
214   Int_t GetLocalMaskFileVersion() const { return fLocalMaskFileVersion; }
215      /// version of the transverse momentum Look-Up-Table in the detector DB
216   Int_t GetLocalLutFileVersion()  const { return fLocalLutFileVersion; }
217      /// version of the signature file in the detector DB
218   Int_t GetSignatureFileVersion() const { return fSignatureFileVersion; }
219
220      /// last known version of the global crate configuration
221   Int_t GetGlobalFileLastVersion()    const { return fGlobalFileLastVersion; }
222      /// last known version of the regional crate configuration
223   Int_t GetRegionalFileLastVersion()  const { return fRegionalFileLastVersion; }
224      /// last known version of the masks for the local cards
225   Int_t GetLocalMaskFileLastVersion() const { return fLocalMaskFileLastVersion; }
226      /// last known version of the transverse momentum Look-Up-Table
227   Int_t GetLocalLutFileLastVersion()  const { return fLocalLutFileLastVersion; }
228
229      /// store for the masks for the local cards (own)
230   AliMUONVStore*                GetLocalMasks()    const { return fLocalMasks; }
231      /// store for the DA-calculated masks for the local cards (own)
232   AliMUONVStore*                GetLocalMasksDA()  const { return fLocalMasksDA; }
233      /// configuration object for the regional crate (own)
234   AliMUONRegionalTriggerConfig* GetRegionalMasks() const { return fRegionalMasks; }
235      /// configuration object for the global crate (own)
236   AliMUONGlobalCrateConfig*     GetGlobalMasks()   const { return fGlobalMasks; }
237
238      /// read/write configurations, masks and LUT to/from online files (own)
239   AliMUONTriggerIO* GetTriggerIO() const { return fTriggerIO; }
240
241      /// store for local strips patterns (noisy strips)
242   AliMUONVStore* GetPatternStoreN() const { return fPatternStoreN; }
243      /// store for local strips patterns (dead strips)
244   AliMUONVStore* GetPatternStoreD() const { return fPatternStoreD; }
245
246      /// number of accumulated PHYSICS events for noisy channels analysis
247   Int_t GetEventsN() const { return fEventsN; }
248      /// number of accumulated CALIBRATION events for dead channels analysis
249   Int_t GetEventsD() const { return fEventsD; }
250
251      /// print verbosity of the DA
252   Int_t GetPrintLevel() const { return fPrintLevel; }
253
254      /// select PHYSICS events for noisy channels analysis
255   Bool_t GetAlgoNoisyInput() const { return fAlgoNoisyInput; }
256      /// select CALIBRATION events for dead channels analysis
257   Bool_t GetAlgoDeadcInput() const { return fAlgoDeadcInput; }
258
259      /// threshold for noisy global inputs (fraction of events)
260   Float_t GetThrN() const { return fThrN; }
261      /// threshold for dead global inputs (fraction of events)
262   Float_t GetThrD() const { return fThrD; }
263      /// threshold for noisy local strips (fraction of events)
264   Float_t GetThrLocN() const { return fThrLocN; }
265      /// threshold for dead local strips (fraction of events)
266   Float_t GetThrLocD() const { return fThrLocD; }
267
268      /// minumum nr of events for rate calculation
269   Int_t GetMinEvents()  const { return fMinEvents; }
270      /// maximum number of events to analyze
271   Int_t GetMaxEvents()  const { return fMaxEvents; }
272      /// number of events to skip from start
273   Int_t GetSkipEvents() const { return fSkipEvents; }
274
275      /// show warnings from the raw data decoder
276   Bool_t WithWarnings() const { return fWithWarnings; }
277      /// use the high-performance (HP) decoder
278   Bool_t UseFastDecoder() const { return fUseFastDecoder; }
279
280      /// number of global input words
281   Int_t GetGlobalInputs()      const { return kGlobalInputs; }
282     /// length in bits of a global input word
283   Int_t GetGlobalInputLength() const { return kGlobalInputLength; }
284
285      /// get accumulated values for bit "ib" from global input word "ii", PHYSICS events
286   Int_t GetAccGlobalInputN(Int_t ii, Int_t ib) const { return fAccGlobalInputN[ii][ib]; }
287      /// get accumulated values for bit "ib" from global input word "ii", CALIBRATION events
288   Int_t GetAccGlobalInputD(Int_t ii, Int_t ib) const { return fAccGlobalInputD[ii][ib]; }
289
290      /// set the name of the Start-of-data field in MtgCurrent.dat
291   void SetSodName(Char_t *name) { fSodName = TString(name); }
292      /// set the flag value of the Start-of-data field in MtgCurrent.dat
293   void SetSodFlag(Int_t flag)   { fSodFlag = flag; }
294
295      /// set the name of the Detector Algorithm field in MtgCurrent.dat
296   void SetDAName(Char_t *name) { fDAName = TString(name); }
297      /// set the flag value of the Detector Algorithm field in MtgCurrent.dat
298   void SetDAFlag(Int_t flag)   { fDAFlag = flag; }
299      /// set DA active mode, 1 = GLOBAL (default), 2 = GLOBAL and LOCAL
300   void SetDAMode(Int_t mode)   { fDAMode = mode; }
301
302      /// set the global crate configuration file name
303   void SetGlobalFileName(const Char_t *name)    { fGlobalFileName = TString(name); }
304      /// set the regional crate configuration file name
305   void SetRegionalFileName(const Char_t *name)  { fRegionalFileName = TString(name); }
306      /// set the masks for the local cards, file name
307   void SetLocalMaskFileName(const Char_t *name) { fLocalMaskFileName = TString(name); }
308      /// set the transverse momentum Look-Up-Table, file name
309   void SetLocalLutFileName(const Char_t *name)  { fLocalLutFileName = TString(name); }
310      /// set the signature file name
311   void SetSignatureFileName(const Char_t *name) { fSignatureFileName = TString(name); }
312
313      /// set the version of the global crate configuration in the detector DB
314   void SetGlobalFileVersion(Int_t ver)    { fGlobalFileVersion = ver; }
315      /// set the version of the regional crate configuration in the detector DB
316   void SetRegionalFileVersion(Int_t ver)  { fRegionalFileVersion = ver; }
317      /// set the version of the masks for the local cards in the detector DB
318   void SetLocalMaskFileVersion(Int_t ver) { fLocalMaskFileVersion = ver; }
319      /// set the version of the transverse momentum Look-Up-Table in the detector DB
320   void SetLocalLutFileVersion(Int_t ver)  { fLocalLutFileVersion = ver; }
321      /// set the version of the signature file in the detector DB
322   void SetSignatureFileVersion(Int_t ver) { fSignatureFileVersion = ver; }
323
324      /// set the last known version of the global crate configuration
325   void SetGlobalFileLastVersion(Int_t ver)    { fGlobalFileLastVersion = ver; }
326      /// set the last known version of the regional crate configuration
327   void SetRegionalFileLastVersion(Int_t ver)  { fRegionalFileLastVersion = ver; }
328      /// set the last known version of the masks for the local cards
329   void SetLocalMaskFileLastVersion(Int_t ver) { fLocalMaskFileLastVersion = ver; }
330      /// set the last known version of the transverse momentum Look-Up-Table
331   void SetLocalLutFileLastVersion(Int_t ver)  { fLocalLutFileLastVersion = ver; }
332
333      /// increment the number of selected PHYSICS events
334   void IncNoiseEvent() { fEventsN++; }
335      /// increment the number of selected CALIBRATION events
336   void IncDeadcEvent() { fEventsD++; }
337
338      /// count the value of the bit "ib" of global input word "ii" (PHYSICS events)
339   void AddAccGlobalInputN(Int_t ii, Int_t ib, Int_t val) { fAccGlobalInputN[ii][ib] += val; }
340      /// count the value of the bit "ib" of global input word "ii" (CALIBRATION events)
341   void AddAccGlobalInputD(Int_t ii, Int_t ib, Int_t val) { fAccGlobalInputD[ii][ib] += val; }
342
343      /// set the print verbosity level of the DA
344   void SetPrintLevel(Int_t level) { fPrintLevel = level; }
345
346      /// select PHYSICS events for noisy channels analysis
347   void SetAlgoNoisyInput(Bool_t val) { fAlgoNoisyInput = val; }
348      /// select CALIBRATION events for dead channels analysis
349   void SetAlgoDeadcInput(Bool_t val) { fAlgoDeadcInput = val; }
350
351      /// set the threshold for noisy global inputs (fraction of events)
352   void SetThrN(Float_t val) { fThrN = val; }
353      /// set the threshold for dead global inputs (fraction of events)
354   void SetThrD(Float_t val) { fThrD = val; }
355      /// set the threshold for noisy local strips (fraction of events)
356   void SetThrLocN(Float_t val) { fThrLocN = val; }
357      /// set the threshold for dead local strips (fraction of events)
358   void SetThrLocD(Float_t val) { fThrLocD = val; }
359
360      /// set the minumum nr of events for rate calculation
361   void SetMinEvents(Int_t val)  { fMinEvents = val; }
362      /// set the maximum number of events to analyze
363   void SetMaxEvents(Int_t val)  { fMaxEvents = val; }
364      /// set the number of events to skip from start
365   void SetSkipEvents(Int_t val) { fSkipEvents = val; }
366
367      /// set/unset to show warnings from the raw data decoder
368   void SetWithWarnings() { fWithWarnings = kTRUE; }
369      /// set/unset the use of the high-performance (HP) decoder
370   void SetUseFastDecoder() { fUseFastDecoder = kTRUE; }
371
372     /// increment version of the global crate configuration file
373   void IncGlobalFileVersion() { fGlobalFileVersion++; }
374     /// increment version of the local mask configuration file
375   void IncLocalMaskFileVersion() { fLocalMaskFileVersion++; }
376     /// count skipped events
377   void DecSkipEvents() { fSkipEvents--; }
378
379 private:
380
381   /// copy constructor, not implemented
382   AliDAConfig (const AliDAConfig& cfg);
383   /// assignment operator, not implemented
384   AliDAConfig& operator=(const AliDAConfig& cfg);
385
386   const TString fDAConfigFileName;    //!< name of the DA configuration file from detector DB
387   const TString fCurrentFileName;     //!< usually MtgCurrent.dat
388   const TString fLastCurrentFileName; //!< usually MtgLastCurrent.dat
389
390   TString fSodName; //!< name of the Start-of-data field in MtgCurrent.dat
391   Int_t   fSodFlag; //!< flag value of the Start-of-data field in MtgCurrent.dat
392
393   TString fDAName;  //!< name of the Detector Algorithm field in MtgCurrent.dat 
394   Int_t   fDAFlag;  //!< flag value of the Detector Algorithm field in MtgCurrent.dat (enabled/disabled)
395   Int_t   fDAMode;  //!< DA active mode, GLOBAL or GLOBAL+LOCAL
396
397   TString fGlobalFileName;      //!< global crate configuration, file name
398   TString fRegionalFileName;    //!< regional crate configuration, file name
399   TString fLocalMaskFileName;   //!< masks for the local cards, file name
400   TString fLocalLutFileName;    //!< transverse momentum Look-Up-Table, file name
401   TString fSignatureFileName;   //!< signature file name
402
403   Int_t   fGlobalFileVersion;    //!< version of the global crate configuration in the detector DB
404   Int_t   fRegionalFileVersion;  //!< version of the regional crate configuration in the detector DB
405   Int_t   fLocalMaskFileVersion; //!< version of the masks for the local cards in the detector DB
406   Int_t   fLocalLutFileVersion;  //!< version of the transverse momentum Look-Up-Table in the detector DB
407   Int_t   fSignatureFileVersion; //!< version of the signature file in the detector DB
408   
409   Int_t   fGlobalFileLastVersion;    //!< last known version of the global crate configuration
410   Int_t   fRegionalFileLastVersion;  //!< last known version of the regional crate configuration
411   Int_t   fLocalMaskFileLastVersion; //!< last known version of the masks for the local cards
412   Int_t   fLocalLutFileLastVersion;  //!< last known version of the transverse momentum Look-Up-Table
413
414   Int_t   fEventsN; //!< number of accumulated PHYSICS events
415   Int_t   fEventsD; //!< number of accumulated CALIBRATION events
416
417   Int_t   fPrintLevel;  //!< print verbosity of the DA
418
419   AliMUONVStore*                fLocalMasks;    //!< store for the masks for the local cards
420   AliMUONVStore*                fLocalMasksDA;  //!< store for the DA-calculated masks for the local cards
421   AliMUONRegionalTriggerConfig* fRegionalMasks; //!< configuration object for the regional crate
422   AliMUONGlobalCrateConfig*     fGlobalMasks;   //!< configuration object for the global crate
423
424   AliMUONTriggerIO *fTriggerIO;  //!< read/write masks and LUT to/from online files
425
426   Bool_t fAlgoNoisyInput; //!< select PHYSICS events for noisy channels analysis
427   Bool_t fAlgoDeadcInput; //!< select CALIBRATION events for dead channels analysis
428
429   Float_t fThrN;           //!< threshold for noisy global inputs (fraction of events)
430   Float_t fThrD;           //!< threshold for dead global inputs (fraction of events)
431   Float_t fThrLocN;        //!< threshold for noisy local strips (fraction of events)
432   Float_t fThrLocD;        //!< threshold for dead local strips (fraction of events)
433   Int_t   fMinEvents;      //!< minumum nr of events for rate calculation
434   Int_t   fSkipEvents;     //!< number of events to skip from start
435   Int_t   fMaxEvents;      //!< maximum number of events to analyze
436   Bool_t  fWithWarnings;   //!< show warnings from the raw data decoder
437   Bool_t  fUseFastDecoder; //!< use the high-performance (HP) decoder
438
439   const Int_t fNLocalBoard; //!< number of local boards
440
441   enum { kGlobalInputs = 4,         //!< number of global input words
442          kGlobalInputLength = 32    //!< length in bits of a global input word
443   };
444
445   AliMUONVStore *fPatternStoreN; //! store for local strips patterns
446   AliMUONVStore *fPatternStoreD; //! store for local strips patterns
447
448   Int_t fAccGlobalInputN[kGlobalInputs][kGlobalInputLength]; //!< storage for global input (PHYSICS events)
449   Int_t fAccGlobalInputD[kGlobalInputs][kGlobalInputLength]; //!< storage for global input (CALIBRATION events)
450
451 };
452
453 //__________________________________________________________________
454 Bool_t ReadDAConfig(AliDAConfig& cfg)
455 {
456     /// read run parameters for the DA
457
458     char line[80];
459
460     TString file;
461     file = cfg.GetDAConfigFileName();
462     std::ifstream in(gSystem->ExpandPathName(file.Data()));
463     if (!in.good()) {
464       printf("Cannot open DA configuration file %s ; use default values.\n",file.Data());
465       return kTRUE;
466     }
467
468     TString tmp;
469     Int_t pos;
470     
471     in.getline(line,80);  
472     tmp = line;
473     pos = tmp.First(" ");
474     tmp = tmp(0,pos);
475     cfg.SetPrintLevel(tmp.Atoi());
476     
477     in.getline(line,80);  
478     tmp = line;
479     pos = tmp.First(" ");
480     tmp = tmp(0,pos);
481     cfg.SetThrN(tmp.Atof());
482
483     in.getline(line,80);  
484     tmp = line;
485     pos = tmp.First(" ");
486     tmp = tmp(0,pos);
487     cfg.SetThrD(tmp.Atof());
488
489     in.getline(line,80);  
490     tmp = line;
491     pos = tmp.First(" ");
492     tmp = tmp(0,pos);
493     cfg.SetMinEvents(tmp.Atoi());
494
495     in.getline(line,80);  
496     tmp = line;
497     pos = tmp.First(" ");
498     tmp = tmp(0,pos);
499     cfg.SetSkipEvents(tmp.Atoi());
500
501     in.getline(line,80);  
502     tmp = line;
503     pos = tmp.First(" ");
504     tmp = tmp(0,pos);
505     cfg.SetMaxEvents(tmp.Atoi());
506
507     in.getline(line,80);  
508     tmp = line;
509     pos = tmp.First(" ");
510     tmp = tmp(0,pos);
511     if (tmp.Atoi() != 0) cfg.SetWithWarnings();
512     
513     in.getline(line,80);  
514     tmp = line;
515     pos = tmp.First(" ");
516     tmp = tmp(0,pos);
517     if (tmp.Atoi() != 0) cfg.SetUseFastDecoder();
518     
519     in.getline(line,80);  
520     tmp = line;
521     pos = tmp.First(" ");
522     tmp = tmp(0,pos);
523     cfg.SetThrLocN(tmp.Atof());
524
525     in.getline(line,80);  
526     tmp = line;
527     pos = tmp.First(" ");
528     tmp = tmp(0,pos);
529     cfg.SetThrLocD(tmp.Atof());
530
531     in.getline(line,80);  
532     tmp = line;
533     pos = tmp.First(" ");
534     tmp = tmp(0,pos);
535     cfg.SetDAMode(tmp.Atoi());
536
537     return kTRUE;
538
539 }
540
541 //__________________________________________________________________
542 void WriteLastCurrentFile(AliDAConfig& cfg, TString currentFile)
543 {
544     /// write last current file
545
546     ofstream out;
547     TString file;
548     file = currentFile;
549     out.open(file.Data());
550     out << cfg.GetSodName() << " " << cfg.GetSodFlag() << endl;
551     out << cfg.GetDAName()  << " " << cfg.GetDAFlag()  << endl;
552
553     out << cfg.GetGlobalFileName()    << " " << cfg.GetGlobalFileVersion()    << endl;
554     out << cfg.GetRegionalFileName()  << " " << cfg.GetRegionalFileVersion()  << endl;
555     out << cfg.GetLocalMaskFileName() << " " << cfg.GetLocalMaskFileVersion() << endl;
556     out << cfg.GetLocalLutFileName()  << " " << cfg.GetLocalLutFileVersion()  << endl;
557     out << cfg.GetSignatureFileName() << " " << cfg.GetSignatureFileVersion() << endl;
558
559     out.close();
560 }
561
562 //___________________________________________________________________________________________
563 Bool_t ReadCurrentFile(AliDAConfig& cfg, TString currentFile, Bool_t lastCurrentFlag = kFALSE)
564 {
565     /// read last current file name and version
566
567     char line[80];
568     char name[80];
569     Int_t flag;
570
571     TString file;
572     file = currentFile;
573     std::ifstream in(gSystem->ExpandPathName(file.Data()));
574     if (!in.good()) {
575       printf("Cannot open last current file %s\n",currentFile.Data());
576       return kFALSE;
577     }
578     
579     // read SOD 
580     in.getline(line,80);  
581     sscanf(line, "%s %d", name, &flag);
582     cfg.SetSodName(name);
583     cfg.SetSodFlag(flag);
584     if (cfg.GetPrintLevel()) printf("Sod Flag %d\n", cfg.GetSodFlag());
585
586     //read DA
587     in.getline(line,80);    
588     sscanf(line, "%s %d", name, &flag);
589     cfg.SetDAName(name);
590     cfg.SetDAFlag(flag);
591     if (cfg.GetPrintLevel()) printf("DA Flag: %d\n", cfg.GetDAFlag());
592
593     // read global
594     in.getline(line,80);    
595     TString tmp(line);
596     Int_t pos =  tmp.First(" ");
597     TString tmp1 = tmp(0, pos);
598     cfg.SetGlobalFileName(tmp1.Data());
599     
600     if (!lastCurrentFlag) {
601       cfg.SetGlobalFileVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
602       if (cfg.GetPrintLevel()) printf("Global File Name: %s version: %d\n", 
603                                       cfg.GetGlobalFileName(), cfg.GetGlobalFileVersion());
604     } else {
605       cfg.SetGlobalFileLastVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
606       if (cfg.GetPrintLevel()) printf("Global File Name: %s last version: %d\n", 
607                                       cfg.GetGlobalFileName(), cfg.GetGlobalFileLastVersion());
608     }
609
610     // read regional
611     in.getline(line,80);
612     tmp = line;
613     pos = tmp.First(" ");
614     tmp1 = tmp(0, pos);
615     cfg.SetRegionalFileName(tmp1.Data());
616
617     if (!lastCurrentFlag) {
618       cfg.SetRegionalFileVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
619       if (cfg.GetPrintLevel()) printf("Regional File Name: %s version: %d\n", 
620                                       cfg.GetRegionalFileName(), cfg.GetRegionalFileVersion());
621
622     } else {
623       cfg.SetRegionalFileLastVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
624       if (cfg.GetPrintLevel()) printf("Regional File Name: %s last version: %d\n", 
625                                       cfg.GetRegionalFileName(), cfg.GetRegionalFileLastVersion());
626     }
627
628     // read mask
629     in.getline(line,80);    
630     tmp = line;
631     pos = tmp.First(" ");
632     tmp1 = tmp(0, pos);
633     cfg.SetLocalMaskFileName(tmp1.Data());
634
635     if (!lastCurrentFlag) {
636       cfg.SetLocalMaskFileVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
637       if (cfg.GetPrintLevel()) printf("Mask File Name: %s version: %d\n", 
638                                       cfg.GetLocalMaskFileName(), cfg.GetLocalMaskFileVersion());
639     } else {
640       cfg.SetLocalMaskFileLastVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
641       if (cfg.GetPrintLevel()) printf("Mask File Name: %s last version: %d\n", 
642                                       cfg.GetLocalMaskFileName(), cfg.GetLocalMaskFileLastVersion());
643     }
644     // read Lut
645     in.getline(line,80);    
646     tmp = line;
647     pos = tmp.First(" ");
648     tmp1 = tmp(0, pos);
649     cfg.SetLocalLutFileName(tmp1.Data());
650
651     if (!lastCurrentFlag) {
652       cfg.SetLocalLutFileVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
653       if (cfg.GetPrintLevel()) printf("Lut File Name: %s version: %d\n", 
654                                       cfg.GetLocalLutFileName(), cfg.GetLocalLutFileVersion());
655     } else {
656       cfg.SetLocalLutFileLastVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
657       if (cfg.GetPrintLevel()) printf("Lut File Name: %s last version: %d\n", 
658                                       cfg.GetLocalLutFileName(), cfg.GetLocalLutFileLastVersion());
659     }
660
661     in.getline(line,80);    
662     tmp = line;
663     pos = tmp.First(" ");
664     tmp1 = tmp(0, pos);
665     cfg.SetSignatureFileName(tmp1.Data());
666     cfg.SetSignatureFileVersion(atoi(tmp(pos+1, tmp.Length()-pos).Data()));
667     if (cfg.GetPrintLevel()) printf("Lut File Name: %s version: %d\n", 
668                                     cfg.GetSignatureFileName(), cfg.GetSignatureFileVersion());
669
670     return kTRUE;
671 }
672
673 //_____________
674 void ReadFileNames(AliDAConfig& cfg)
675 {
676   /// if last current file does not exist than read current file
677
678   if (!ReadCurrentFile(cfg,cfg.GetLastCurrentFileName(), kTRUE)) 
679     {
680       ReadCurrentFile(cfg,cfg.GetCurrentFileName(), kTRUE);
681     } 
682   
683   // any case read current file
684   ReadCurrentFile(cfg,cfg.GetCurrentFileName());
685   
686 }
687
688 //__________________
689 Bool_t ExportFiles(AliDAConfig& cfg)
690 {
691     /// Export files to FES
692
693     // env variables have to be set (suppose by ECS ?)
694     // setenv DATE_FES_PATH
695     // setenv DATE_RUN_NUMBER
696     // setenv DATE_ROLE_NAME
697     // setenv DATE_DETECTOR_CODE
698
699 #ifdef OFFLINE
700     gSystem->Setenv("DAQDALIB_PATH", "$DATE_SITE/infoLogger");
701     gSystem->Setenv("DAQDA_TEST_DIR", "/alisoft/FES");
702 #endif
703
704     // update files
705     Int_t status = 0;
706
707     Bool_t modified = kFALSE;
708     Bool_t globalExported = kFALSE;
709
710     ofstream out;
711     TString fileExp("ExportedFiles.dat");
712     TString file;
713
714     out.open(fileExp.Data());
715     if (!out.good()) {
716         printf("Failed to create file: %s\n",file.Data());
717         return kFALSE;
718     }      
719
720     // check if MtgLastCurrent.dat exists
721     // if not, do initial export of all files
722     Bool_t initFES = kFALSE;
723     if (gSystem->AccessPathName("MtgLastCurrent.dat"))
724       initFES = kTRUE;
725     if (initFES) printf("Copy all configuration files to the FES.\n");
726
727     file = cfg.GetLocalMaskFileName();  
728     if ((cfg.GetLocalMaskFileLastVersion() != cfg.GetLocalMaskFileVersion()) || initFES) {
729       modified = kTRUE;
730       status = daqDA_FES_storeFile(file.Data(), "LOCAL");
731       if (status) {
732         printf("Failed to export file: %s\n",cfg.GetLocalMaskFileName());
733         return kFALSE;
734       }
735       if(cfg.GetPrintLevel()) printf("Export file: %s\n",cfg.GetLocalMaskFileName());
736       out << cfg.GetLocalMaskFileName() << endl;
737     }
738
739     file = cfg.GetLocalLutFileName();
740     if ((cfg.GetLocalLutFileLastVersion() != cfg.GetLocalLutFileVersion()) || initFES) {
741       modified = kTRUE;
742       status = daqDA_FES_storeFile(file.Data(), "LUT");
743       if (status) {
744         printf("Failed to export file: %s\n",cfg.GetLocalLutFileName());
745         return kFALSE;
746       }
747       if(cfg.GetPrintLevel()) printf("Export file: %s\n",cfg.GetLocalLutFileName());
748       out << cfg.GetLocalLutFileName() << endl;
749
750     }
751
752     file = cfg.GetGlobalFileName();
753     if ((cfg.GetGlobalFileLastVersion() != cfg.GetGlobalFileVersion()) || modified || initFES) {
754       modified = kTRUE;
755       globalExported = kTRUE;
756       status = daqDA_FES_storeFile(file.Data(), "GLOBAL");
757       if (status) {
758         printf("Failed to export file: %s\n",cfg.GetGlobalFileName());
759         return kFALSE;
760       }
761       if(cfg.GetPrintLevel()) printf("Export file: %s\n",cfg.GetGlobalFileName());
762       out << cfg.GetGlobalFileName() << endl;
763     }
764
765     file = cfg.GetRegionalFileName();
766     if ( (cfg.GetRegionalFileLastVersion() != cfg.GetRegionalFileVersion()) || modified || initFES) {
767       status = daqDA_FES_storeFile(file.Data(), "REGIONAL");
768       if (status) {
769         printf("Failed to export file: %s\n",cfg.GetRegionalFileName());
770         return kFALSE;
771       }
772       if(cfg.GetPrintLevel()) printf("Export file: %s\n",cfg.GetRegionalFileName());
773       out << cfg.GetRegionalFileName() << endl;
774
775       // needed for the initialisation of the mapping
776       if (!globalExported) {
777         file = cfg.GetGlobalFileName();
778         status = daqDA_FES_storeFile(file.Data(), "GLOBAL");
779         if (status) {
780           printf("Failed to export file: %s\n",cfg.GetGlobalFileName());
781           return kFALSE;
782         }
783         if(cfg.GetPrintLevel()) printf("Export file: %s\n",cfg.GetGlobalFileName());
784         out << cfg.GetGlobalFileName() << endl;
785       }
786
787     }
788
789     out.close();
790
791     // export Exported file to FES anyway
792     status = daqDA_FES_storeFile(fileExp.Data(), "EXPORTED");
793     if (status) {
794       printf("Failed to export file: %s\n", fileExp.Data());
795       return kFALSE;
796     }
797     if(cfg.GetPrintLevel()) printf("Export file: %s\n",fileExp.Data());
798
799     // write last current file
800     WriteLastCurrentFile(cfg,cfg.GetLastCurrentFileName());
801
802     return kTRUE;
803 }
804
805 //__________________
806 Bool_t ImportFiles(AliDAConfig& cfg)
807 {
808     /// copy locally a file from daq detector config db 
809     /// The current detector is identified by detector code in variable
810     /// DATE_DETECTOR_CODE. It must be defined.
811     /// If environment variable DAQDA_TEST_DIR is defined, files are copied from 
812     /// DAQDA_TEST_DIR instead of the database. 
813     /// The usual environment variables are not needed.
814
815     Int_t status = 0;
816
817 #ifdef OFFLINE
818     gSystem->Setenv("DAQDALIB_PATH", "$DATE_SITE/db");
819 #endif
820
821     status = daqDA_DB_getFile(cfg.GetDAConfigFileName(), cfg.GetDAConfigFileName());
822     if (status) {
823       printf("Failed to get DA config file from DB: %s\n",cfg.GetDAConfigFileName());
824       return kFALSE;
825     }
826  
827     ReadDAConfig(cfg);
828     
829     status = daqDA_DB_getFile(cfg.GetCurrentFileName(), cfg.GetCurrentFileName());
830     if (status) {
831       printf("Failed to get current config file from DB: %s\n",cfg.GetCurrentFileName());
832       return kFALSE;
833     }
834     
835     ReadFileNames(cfg);
836
837     status = daqDA_DB_getFile(cfg.GetGlobalFileName(), cfg.GetGlobalFileName());
838     if (status) {
839       printf("Failed to get current config file from DB: %s\n", cfg.GetGlobalFileName());
840       return kFALSE;
841     }
842
843     status = daqDA_DB_getFile(cfg.GetRegionalFileName(), cfg.GetRegionalFileName());
844     if (status) {
845       printf("Failed to get current config file from DB: %s\n",cfg.GetRegionalFileName());
846       return kFALSE;
847     }
848
849     status = daqDA_DB_getFile(cfg.GetLocalMaskFileName(), cfg.GetLocalMaskFileName());
850     if (status) {
851       printf("Failed to get current config file from DB: %s\n",cfg.GetLocalMaskFileName());
852       return kFALSE;
853     }
854
855     status = daqDA_DB_getFile(cfg.GetLocalLutFileName(), cfg.GetLocalLutFileName());
856     if (status) {
857       printf("Failed to get current config file from DB: %s\n",cfg.GetLocalLutFileName());
858       return kFALSE;
859     }
860  
861     return kTRUE;
862 }
863
864 //_____________
865 void ReadMaskFiles(AliDAConfig& cfg)
866 {
867     /// read mask files
868
869     const Char_t* localFile    = cfg.GetLocalMaskFileName();
870     const Char_t* regionalFile = cfg.GetRegionalFileName();
871     const Char_t* globalFile   = cfg.GetGlobalFileName();
872
873     cfg.GetTriggerIO()->ReadConfig(localFile, regionalFile, globalFile, cfg.GetLocalMasks(), cfg.GetRegionalMasks(), cfg.GetGlobalMasks());                     
874 }
875
876 //______________________________________________________________
877 UInt_t GetFetMode(const AliDAConfig & cfg)
878 {
879   /// FET mode = 3 to run algorithm for dead global inputs
880   /// 0x3 prepulse
881   /// 0x0 internal
882
883   return cfg.GetGlobalMasks()->GetFetRegister(3);
884
885 }
886
887 //______________________________________________________________
888 void StoreGlobalInput(AliDAConfig& cfg, const UInt_t * const globalInput) 
889 {
890   /// accumulate and build statistics of global input values
891   
892   for (Int_t ii = 0; ii < cfg.GetGlobalInputs(); ii++) {
893     for (Int_t ib = 0; ib < cfg.GetGlobalInputLength(); ib++) {
894       // lsb -> msb
895       if (cfg.GetAlgoNoisyInput())
896         cfg.AddAccGlobalInputN(ii,ib,((globalInput[ii] >> ib) & 0x1));
897       if (cfg.GetAlgoDeadcInput())
898         cfg.AddAccGlobalInputD(ii,ib,((globalInput[ii] >> ib) & 0x1));
899     }
900   }
901
902 }
903
904 //______________________________________________________________
905 void UpdateGlobalMasks(AliDAConfig& cfg) 
906 {
907   /// update the global masks
908   
909 #ifdef OFFLINE
910   gSystem->Setenv("DAQDALIB_PATH", "$DATE_SITE/db");
911 #endif
912
913   Float_t rateN = 0.0, rateD = 0.0;
914   UInt_t gmask[4], omask;
915   Bool_t noise, deadc, withEvN, withEvD, updated = kFALSE;
916
917   for (Int_t ii = 0; ii < cfg.GetGlobalInputs(); ii++) {
918     gmask[ii] = 0;
919
920     for (Int_t ib = 0; ib < cfg.GetGlobalInputLength(); ib++) {
921       // lsb -> msb
922       noise = kFALSE;
923       deadc = kFALSE;
924       withEvN = kFALSE;
925       withEvD = kFALSE;
926       if (cfg.GetEventsN() > cfg.GetMinEvents()) {
927         rateN = (Float_t)cfg.GetAccGlobalInputN(ii,ib)/(Float_t)cfg.GetEventsN();
928         noise = (rateN > cfg.GetThrN());        
929         withEvN = kTRUE;
930       }
931       if (cfg.GetEventsD() > cfg.GetMinEvents()) {
932         rateD = (Float_t)cfg.GetAccGlobalInputD(ii,ib)/(Float_t)cfg.GetEventsD();
933         deadc = (rateD < cfg.GetThrD());
934         withEvD = kTRUE;
935       }
936       if (!withEvN && !withEvD) {
937         // - copy the bit from the old mask
938         gmask[ii] |= ((cfg.GetGlobalMasks()->GetGlobalMask(ii) >> ib) & 0x1) << ib;
939         if (cfg.GetPrintLevel()) 
940           printf("Mask not changed (just copy the old values)\n");
941       }
942       if (!withEvN && withEvD) {
943         if (!deadc) {
944           // - create a new mask, set the bit to 1
945           //   not allowed!
946           //gmask[ii] |= 0x1 << ib;
947           // - copy the bit from the old mask
948           gmask[ii] |= ((cfg.GetGlobalMasks()->GetGlobalMask(ii) >> ib) & 0x1) << ib;
949         } else {
950           // - create a new mask, set the bit to 0
951           gmask[ii] |= 0x0 << ib;
952           if (cfg.GetPrintLevel()) 
953             printf("Found dead  channel %1d:%02d (%4.2f) \n",ii,ib,rateD);
954         }
955       }
956       if (withEvN && !withEvD) {
957         if (!noise) {
958           // - create a new mask, set the bit to 1
959           //   not allowed!
960           //gmask[ii] |= 0x1 << ib;
961           // - copy the bit from the old mask
962           gmask[ii] |= ((cfg.GetGlobalMasks()->GetGlobalMask(ii) >> ib) & 0x1) << ib;
963         } else {
964           // - create a new mask, set the bit to 0
965           gmask[ii] |= 0x0 << ib;
966           if (cfg.GetPrintLevel()) 
967             printf("Found noisy channel %1d:%02d (%4.2f) \n",ii,ib,rateN);
968         }
969       }
970       if (withEvN && withEvD) {
971         if (!noise && !deadc) {
972           // - create a new mask, set the bit to 1
973           //   not allowed!
974           //gmask[ii] |= 0x1 << ib;
975           // - copy the bit from the old mask
976           gmask[ii] |= ((cfg.GetGlobalMasks()->GetGlobalMask(ii) >> ib) & 0x1) << ib;
977         } else {
978           // - create a new mask, set the bit to 0
979           gmask[ii] |= 0x0 << ib;
980           if (cfg.GetPrintLevel()) {
981             if (noise)
982               printf("Found noisy channel %1d:%02d (%4.2f) \n",ii,ib,rateN);
983             if (deadc)
984               printf("Found dead  channel %1d:%02d (%4.2f) \n",ii,ib,rateD);
985           }
986         }
987       }
988     }
989   }
990
991   // check if at least one mask value has been changed from previous version
992   for (Int_t ii = 0; ii < cfg.GetGlobalInputs(); ii++) {
993     printf("Global mask [%1d] %08x \n",ii,gmask[ii]);
994     omask = cfg.GetGlobalMasks()->GetGlobalMask(ii);
995     if (gmask[ii] != omask) {
996       updated = kTRUE;
997       cfg.GetGlobalMasks()->SetGlobalMask(ii,gmask[ii]);
998     }
999   }
1000
1001   Int_t status = 0;
1002   if (updated) {
1003     
1004     // update version
1005     cfg.IncGlobalFileVersion();
1006     
1007     // don't change the file version ("-x.dat")
1008     
1009     cfg.GetTriggerIO()->WriteGlobalConfig(cfg.GetGlobalFileName(),cfg.GetGlobalMasks());
1010     
1011     // write last current file
1012     WriteLastCurrentFile(cfg,cfg.GetCurrentFileName());
1013
1014     status = daqDA_DB_storeFile(cfg.GetGlobalFileName(), cfg.GetGlobalFileName());
1015     if (status) {
1016       printf("Failed to export file to DB: %s\n",cfg.GetGlobalFileName());
1017       return;
1018     }
1019     
1020     status = daqDA_DB_storeFile(cfg.GetCurrentFileName(), cfg.GetCurrentFileName());
1021     if (status) {
1022       printf("Failed to export file to DB: %s\n",cfg.GetCurrentFileName());
1023       return;
1024     }
1025
1026   }
1027   
1028 }
1029
1030 //______________________________________________________________
1031 void UpdateLocalMask(AliDAConfig& cfg, Int_t localBoardId, Int_t connector, Int_t strip) 
1032 {
1033
1034   /// update local strip mask
1035
1036   AliMUONVCalibParam* localMask = 
1037     static_cast<AliMUONVCalibParam*>(cfg.GetLocalMasksDA()->FindObject(localBoardId));
1038   
1039   UShort_t mask = static_cast<UShort_t>(localMask->ValueAsInt(connector,0)); 
1040   
1041   mask &= ~(0x1 << strip); // set strip mask to zero
1042   
1043   localMask->SetValueAsInt(connector, 0, mask);  
1044
1045 }
1046
1047 //______________________________________________________________
1048 void MakePattern(AliDAConfig& cfg, Int_t localBoardId, const TArrayS& xPattern, const TArrayS& yPattern) 
1049 {
1050   /// calculate the hit map for each strip in x and y direction
1051   
1052   AliMUONVCalibParam* pat = 0x0;
1053
1054   if (cfg.GetAlgoNoisyInput())
1055     pat = static_cast<AliMUONVCalibParam*>(cfg.GetPatternStoreN()->FindObject(localBoardId));
1056   if (cfg.GetAlgoDeadcInput())
1057     pat = static_cast<AliMUONVCalibParam*>(cfg.GetPatternStoreD()->FindObject(localBoardId));
1058
1059   if (!pat) {
1060     pat = new AliMUONCalibParamND(2, 64, localBoardId, 0, 0.);
1061     if (cfg.GetAlgoNoisyInput())
1062       cfg.GetPatternStoreN()->Add(pat); 
1063     if (cfg.GetAlgoDeadcInput())
1064       cfg.GetPatternStoreD()->Add(pat); 
1065   }
1066
1067   for (Int_t i = 0; i < 4; ++i) {
1068     for (Int_t j = 0; j < 16; ++j) {
1069         
1070       Int_t xMask = xPattern[i];
1071       Int_t yMask = yPattern[i];
1072       
1073       Int_t index = 16*i + j;
1074       Double_t patOcc = 0.;
1075       
1076       if ( (xMask >> j ) & 0x1 ) {
1077         patOcc  = pat->ValueAsDouble(index, 0) + 1.;
1078         pat->SetValueAsDouble(index, 0, patOcc);
1079       }
1080       if ( (yMask >> j ) & 0x1 ) {
1081         patOcc  = pat->ValueAsDouble(index, 1) + 1.;
1082         pat->SetValueAsDouble(index, 1, patOcc);
1083       }
1084     }
1085   }
1086
1087 }
1088
1089 //______________________________________________________________
1090 void MakePatternStore(AliDAConfig& cfg) 
1091 {
1092   /// analyse patterns for local strips (calculate occupancy)
1093   
1094 #ifdef OFFLINE
1095   gSystem->Setenv("DAQDALIB_PATH", "$DATE_SITE/db");
1096 #endif
1097
1098   AliMUONVCalibParam* pat;
1099   Int_t localBoardId = 0;
1100   Int_t nEventsN = 0, nEventsD = 0;  
1101   UShort_t strip = 0;
1102   Int_t connector = 0;
1103   Bool_t updated = kFALSE;
1104   
1105   if (cfg.GetEventsN() > cfg.GetMinEvents()) {
1106     nEventsN = cfg.GetEventsN();
1107   }
1108   if (cfg.GetEventsD() > cfg.GetMinEvents()) {
1109     nEventsD = cfg.GetEventsD();
1110   }
1111
1112   // noisy strips
1113   if (nEventsN > 0) {
1114
1115     TIter next(cfg.GetPatternStoreN()->CreateIterator());
1116
1117     while ( ( pat = dynamic_cast<AliMUONVCalibParam*>(next() ) ) ) {
1118       
1119       localBoardId  = pat->ID0();
1120       
1121       for (Int_t index = 0; index < pat->Size(); index++) {
1122         
1123         Double_t patXOcc  = pat->ValueAsDouble(index, 0)/(Double_t)nEventsN;
1124         Double_t patYOcc  = pat->ValueAsDouble(index, 1)/(Double_t)nEventsN;
1125         
1126         pat->SetValueAsDouble(index, 0, patXOcc);
1127         pat->SetValueAsDouble(index, 1, patYOcc);
1128         
1129         // check for x strip
1130         if (patXOcc > cfg.GetThrLocN()) {
1131           strip  = index % 16;
1132           connector = index/16;
1133           UpdateLocalMask(cfg, localBoardId, connector, strip);
1134         }
1135         // check for y strip
1136         if (patYOcc > cfg.GetThrLocN()) {
1137           strip  = index % 16;
1138           connector = index/16 + 4;
1139           UpdateLocalMask(cfg, localBoardId, connector, strip);
1140         }
1141         
1142       }
1143     }
1144     
1145   }
1146   
1147   // dead strips
1148   if (nEventsD > 0) {
1149
1150     TIter next(cfg.GetPatternStoreD()->CreateIterator());
1151
1152     while ( ( pat = dynamic_cast<AliMUONVCalibParam*>(next() ) ) ) {
1153       
1154       localBoardId  = pat->ID0();
1155       
1156       for (Int_t index = 0; index < pat->Size(); index++) {
1157         
1158         Double_t patXOcc  = pat->ValueAsDouble(index, 0)/(Double_t)nEventsD;
1159         Double_t patYOcc  = pat->ValueAsDouble(index, 1)/(Double_t)nEventsD;
1160         
1161         pat->SetValueAsDouble(index, 0, patXOcc);
1162         pat->SetValueAsDouble(index, 1, patYOcc);
1163         
1164         // check for x strip
1165         if (patXOcc < cfg.GetThrLocD()) {
1166           strip  = index % 16;
1167           connector = index/16;
1168           UpdateLocalMask(cfg, localBoardId, connector, strip);
1169         }
1170         // check for y strip
1171         if (patYOcc < cfg.GetThrLocD()) {
1172           strip  = index % 16;
1173           connector = index/16 + 4;
1174           UpdateLocalMask(cfg, localBoardId, connector, strip);
1175         }
1176         
1177       }
1178     }
1179     
1180   }
1181   
1182   // make and AND with the previous version of the mask and
1183   // check if the mask has changed
1184   UShort_t maskDA, mask;
1185   Int_t nMaskBits = AliMpConstants::TotalNofLocalBoards()*8*16;
1186   Int_t nMaskBitsChanged = 0;
1187   for (localBoardId = 1; localBoardId <= AliMpConstants::TotalNofLocalBoards(); localBoardId++) {
1188     AliMUONVCalibParam* localMaskDA = static_cast<AliMUONVCalibParam*>(cfg.GetLocalMasksDA()->FindObject(localBoardId));
1189     AliMUONVCalibParam* localMask = static_cast<AliMUONVCalibParam*>(cfg.GetLocalMasks()->FindObject(localBoardId));
1190     for (connector = 0; connector < 8; connector++) {
1191       maskDA = static_cast<UShort_t>(localMaskDA->ValueAsInt(connector,0)); 
1192       mask = static_cast<UShort_t>(localMask->ValueAsInt(connector,0));
1193       maskDA &= mask; 
1194       localMaskDA->SetValueAsInt(connector, 0, maskDA);  
1195       if (maskDA != mask) {
1196         updated = kTRUE;
1197         // calculated percentage of mask bits changed
1198         for (Int_t iBit = 0; iBit < 16; iBit++) {
1199           if (((maskDA >> iBit) & 0x1) != ((mask >> iBit) &0x1)) {
1200             nMaskBitsChanged++;
1201           }
1202         }
1203       }
1204     }
1205   }
1206
1207   printf("LOCAL mask bits changed = %5d (%7.3f %%) \n",nMaskBitsChanged,100*(Float_t)nMaskBitsChanged/(Float_t)nMaskBits);
1208
1209   Int_t status = 0;
1210   if (updated) {
1211
1212     // update version
1213     cfg.IncLocalMaskFileVersion();
1214     
1215     // don't change the file version ("-x.dat")
1216     
1217     cfg.GetTriggerIO()->WriteLocalMasks(cfg.GetLocalMaskFileName(),*cfg.GetLocalMasksDA());
1218
1219     // write last current file
1220     WriteLastCurrentFile(cfg,cfg.GetCurrentFileName());
1221
1222     status = daqDA_DB_storeFile(cfg.GetLocalMaskFileName(), cfg.GetLocalMaskFileName());
1223     if (status) {
1224       printf("Failed to export file to DB: %s\n",cfg.GetLocalMaskFileName());
1225       return;
1226     }
1227     
1228     status = daqDA_DB_storeFile(cfg.GetCurrentFileName(), cfg.GetCurrentFileName());
1229     if (status) {
1230       printf("Failed to export file to DB: %s\n",cfg.GetCurrentFileName());
1231       return;
1232     }
1233
1234   }
1235
1236 }
1237
1238 //*************************************************************//
1239 int main(Int_t argc, Char_t **argv) 
1240 {
1241     /// main routine
1242   
1243     // needed for streamer application
1244     gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo", "*", "TStreamerInfo", "RIO", "TStreamerInfo()"); 
1245
1246     /* check that we got some arguments = list of files */
1247     if (argc<2) {
1248       printf("Wrong number of arguments\n");
1249       return -1;
1250     }
1251
1252     AliDAConfig cfg;
1253
1254     Char_t inputFile[256] = "";
1255     inputFile[0] = 0;
1256     if (argc > 1)
1257       if (argv[1] != NULL)
1258         strncpy(inputFile, argv[1], 256);
1259       else {
1260         printf("MUONTRGda : No input File !\n");
1261         return -1;
1262       }
1263
1264     // decoding the events
1265   
1266     Int_t status = 0;
1267     Int_t nDateEvents = 0;
1268
1269     void* event;
1270
1271     // containers
1272     // old decoder
1273     AliMUONDDLTrigger*       ddlTrigger     = 0x0;
1274     AliMUONDarcHeader*       darcHeader     = 0x0;
1275     AliMUONRegHeader*        regHeader   = 0x0;
1276     AliMUONLocalStruct*      localStruct = 0x0;
1277     // new (fast) decoder
1278     const AliMUONRawStreamTriggerHP::AliHeader*      darcHeaderHP  = 0x0;
1279     const AliMUONRawStreamTriggerHP::AliLocalStruct* localStructHP = 0x0;
1280
1281     TArrayS xPattern(4);
1282     TArrayS yPattern(4);
1283     Int_t localBoardId = 0;
1284
1285     TStopwatch timers;
1286
1287     timers.Start(kTRUE); 
1288
1289     // comment out, since we do not retrieve files from database
1290     if (!ImportFiles(cfg)) {
1291       printf("Import from DB failed\n");
1292       printf("For local test set DAQDA_TEST_DIR to the local directory where the Mtg files are located \n");
1293       return -1;
1294     }
1295     
1296     ReadMaskFiles(cfg);
1297
1298 #ifdef OFFLINE
1299     // the run number extracted from the file name
1300     TString tmp(inputFile);
1301     Int_t pos1 = tmp.First('d');
1302     Int_t pos2 = tmp.Last('.');
1303     Int_t len  = pos2 - (pos1+3);
1304     tmp = tmp(pos1+3,len);
1305     gSystem->Setenv("DATE_RUN_NUMBER",tmp.Data());
1306     gSystem->Exec("echo \"DATE_RUN_NUMBER = \" $DATE_RUN_NUMBER");
1307 #endif
1308
1309     if(!ExportFiles(cfg)) {
1310       printf("ExportFiles failed\n");
1311       return -1;
1312     }
1313
1314     if (!cfg.GetDAFlag()) {
1315
1316       cout << "MUONTRGda: DA enable: " << cfg.GetDAFlag() << endl;
1317       cout << "MUONTRGda: Print level: " << cfg.GetPrintLevel() << endl;
1318       
1319       printf("MUONTRGda: Execution time : R:%7.2fs C:%7.2fs\n", timers.RealTime(), timers.CpuTime());
1320
1321       return status;
1322
1323     }
1324
1325     // FET is triggered by CTP
1326     Bool_t modeFET3 = kTRUE;
1327     if (GetFetMode(cfg) != 3) {
1328       printf("FET is not in mode 3. Only PHYSICS events will be analysed (noisy channels)\n");
1329       modeFET3 = kFALSE;
1330     }
1331
1332     // All 5 global cards are controlled by the Mts proxy
1333     if (cfg.GetGlobalMasks()->GetGlobalCrateEnable() != 0x1F) {
1334       printf("The MTS proxy does not control all global cards\n");
1335       return -1;
1336     }
1337
1338     // The global cards are ON (active on the global inputs)
1339     if (!cfg.GetGlobalMasks()->GetMasksOn()) {
1340       printf("Global masks are not ON\n");
1341       return -1;
1342     }
1343   
1344     // make sure to catch the "rare" calib events (1 every 50s in physics)
1345     const Char_t* tableSOD[]  = {"ALL", "yes", "CAL", "all", NULL, NULL};
1346     monitorDeclareTable(const_cast<char**>(tableSOD));
1347
1348     status = monitorSetDataSource(inputFile);
1349     if (status) {
1350       cerr << "ERROR : monitorSetDataSource status (hex) = " << hex << status
1351            << " " << monitorDecodeError(status) << endl;
1352       return -1;
1353     }
1354     status = monitorDeclareMp("MUON Trigger monitoring");
1355     if (status) {
1356       cerr << "ERROR : monitorDeclareMp status (hex) = " << hex << status
1357            << " " << monitorDecodeError(status) << endl;
1358       return -1;
1359     }
1360
1361     /* define wait event timeout - 1s max */
1362     monitorSetNowait();
1363     monitorSetNoWaitNetworkTimeout(1000);
1364
1365     cout << "MUONTRGda : Reading data from file " << inputFile <<endl;
1366
1367     UInt_t *globalInput = new UInt_t[4];
1368     Bool_t doUpdate = kFALSE;
1369     Int_t runNumber = 0;
1370     Int_t nEvents = 0;
1371
1372     while(1) 
1373     {
1374       if (nEvents >= cfg.GetMaxEvents()) break;
1375       if (cfg.GetPrintLevel()) {
1376         if (nEvents && nEvents % 1000 == 0)     
1377           cout<<"Cumulated events " << nEvents << endl;
1378       }
1379       // check shutdown condition 
1380       if (daqDA_checkShutdown()) 
1381           break;
1382
1383       // Skip Events if needed
1384       while (cfg.GetSkipEvents()) {
1385         status = monitorGetEventDynamic(&event);
1386         cfg.DecSkipEvents();
1387       }
1388
1389       // starts reading
1390       status = monitorGetEventDynamic(&event);
1391       if (status < 0)  {
1392         cout << "MUONTRGda : EOF found" << endl;
1393         break;
1394       }
1395
1396       nDateEvents++;
1397
1398       // decoding rawdata headers
1399       AliRawReader *rawReader = new AliRawReaderDate(event);
1400  
1401       Int_t eventType = rawReader->GetType();
1402       runNumber = rawReader->GetRunNumber();
1403     
1404       // L1Swc1
1405       // CALIBRATION_EVENT 
1406       // SYSTEM_SOFTWARE_TRIGGER_EVENT
1407       // DETECTOR_SOFTWARE_TRIGGER_EVENT
1408       cfg.SetAlgoNoisyInput(kFALSE);
1409       cfg.SetAlgoDeadcInput(kFALSE);
1410       if (eventType == PHYSICS_EVENT) {
1411         cfg.SetAlgoNoisyInput(kTRUE);
1412         doUpdate = kTRUE;
1413         cfg.IncNoiseEvent();
1414       } else if (modeFET3 && eventType == CALIBRATION_EVENT) {
1415         cfg.SetAlgoDeadcInput(kTRUE);
1416         doUpdate = kTRUE;
1417         cfg.IncDeadcEvent();
1418       } else {
1419         continue;
1420       }
1421       
1422       nEvents++;
1423       if (cfg.GetPrintLevel() == 2) printf("\nEvent # %d\n",nEvents);
1424
1425       // decoding MUON payload
1426       AliMUONVRawStreamTrigger   *rawStream   = 0x0;
1427       if (cfg.UseFastDecoder()) {
1428         rawStream = new AliMUONRawStreamTriggerHP(rawReader);
1429       } else {
1430         rawStream = new AliMUONRawStreamTrigger(rawReader);
1431       }
1432
1433       // ... without warnings from the decoder !!!
1434       if (!cfg.WithWarnings())
1435         rawStream->DisableWarnings();
1436
1437       // loops over DDL 
1438       while((status = rawStream->NextDDL())) {
1439
1440         if (cfg.GetPrintLevel() == 2) printf("iDDL %d\n", rawStream->GetDDL());
1441
1442         if (cfg.UseFastDecoder()) {
1443           darcHeaderHP = static_cast<AliMUONRawStreamTriggerHP*>(rawStream)->GetHeaders();
1444           if (cfg.GetPrintLevel() == 2) printf("Global output (fast decoder) %x\n", (Int_t)darcHeaderHP->GetGlobalOutput());
1445           for (Int_t ig = 0; ig < cfg.GetGlobalInputs(); ig++) {
1446             globalInput[ig] = darcHeaderHP->GetGlobalInput(ig);
1447           }
1448           // loop over regional structure
1449           Int_t nReg = (Int_t)static_cast<AliMUONRawStreamTriggerHP*>(rawStream)->GetRegionalHeaderCount();
1450           for(Int_t iReg = 0; iReg < nReg; iReg++) {
1451             // loop over local structures
1452             Int_t nLoc = (Int_t)static_cast<AliMUONRawStreamTriggerHP*>(rawStream)->GetLocalStructCount(iReg);
1453             for(Int_t iLoc = 0; iLoc < nLoc; iLoc++) {
1454               localStructHP = static_cast<AliMUONRawStreamTriggerHP*>(rawStream)->GetLocalStruct(iReg, iLoc);
1455               localBoardId = cfg.GetTriggerIO()->LocalBoardId(rawStream->GetDDL(),iReg,localStructHP->GetId());
1456               if (localBoardId > 0) {
1457                 localStructHP->GetXPattern(xPattern);
1458                 localStructHP->GetYPattern(yPattern);
1459                 MakePattern(cfg,localBoardId,xPattern,yPattern);
1460               }
1461             }
1462           }
1463         } else {
1464           ddlTrigger = rawStream->GetDDLTrigger();
1465           darcHeader = ddlTrigger->GetDarcHeader();
1466           if (cfg.GetPrintLevel() == 2) printf("Global output %x\n", (Int_t)darcHeader->GetGlobalOutput());
1467           globalInput = darcHeader->GetGlobalInput();
1468           // loop over regional structure
1469           Int_t nReg = darcHeader->GetRegHeaderEntries();
1470           for(Int_t iReg = 0; iReg < nReg; iReg++) {
1471             regHeader = darcHeader->GetRegHeaderEntry(iReg);
1472             // loop over local structures
1473             Int_t nLoc = regHeader->GetLocalEntries();
1474             for(Int_t iLoc = 0; iLoc < nLoc; iLoc++) {  
1475               localStruct = regHeader->GetLocalEntry(iLoc);
1476               localBoardId = cfg.GetTriggerIO()->LocalBoardId(rawStream->GetDDL(),iReg,localStruct->GetId());
1477               if (localBoardId > 0) {
1478                 localStruct->GetXPattern(xPattern);
1479                 localStruct->GetYPattern(yPattern);
1480                 MakePattern(cfg,localBoardId,xPattern,yPattern);
1481               }
1482             }
1483           }
1484         }
1485         if (rawStream->GetDDL() == 0) {
1486           StoreGlobalInput(cfg,globalInput);
1487         }
1488         
1489       } // NextDDL
1490
1491       delete rawReader;
1492       delete rawStream;
1493
1494     } // while (1)
1495
1496     // update configuration files ifrequested event types were found
1497     if (doUpdate) {
1498       if (cfg.GetDAMode() > 0) UpdateGlobalMasks(cfg);
1499       if (cfg.GetDAMode() > 1) MakePatternStore(cfg);
1500     }
1501
1502     timers.Stop();
1503
1504     cout << "MUONTRGda: DA enable: " << cfg.GetDAFlag() << endl;
1505     cout << "MUONTRGda: Run number: " << runNumber << endl;
1506     cout << "MUONTRGda: Nb of DATE events: " << nDateEvents << endl;
1507     cout << "MUONTRGda: Nb of events used: " << nEvents << endl;
1508     cout << "MUONTRGda: Nb of events used (noise): " << cfg.GetEventsN() << endl;
1509     cout << "MUONTRGda: Nb of events used (deadc): " << cfg.GetEventsD() << endl;
1510     cout << "MUONTRGda: Minumum nr of events for rate calculation: " << cfg.GetMinEvents() << endl;
1511     cout << "MUONTRGda: Maximum nr of analyzed events: " << cfg.GetMaxEvents() << endl;
1512     cout << "MUONTRGda: Skip events from start: " << cfg.GetSkipEvents() << endl;
1513     cout << "MUONTRGda: Threshold for global noisy inputs: " << 100*cfg.GetThrN() << "%" << endl;
1514     cout << "MUONTRGda: Threshold for global dead inputs: " << 100*cfg.GetThrD() << "%" << endl;
1515     cout << "MUONTRGda: Threshold for local noisy inputs: " << 100*cfg.GetThrLocN() << "%" << endl;
1516     cout << "MUONTRGda: Threshold for local dead inputs: " << 100*cfg.GetThrLocD() << "%" << endl;
1517     cout << "MUONTRGda: Print level: " << cfg.GetPrintLevel() << endl;
1518     cout << "MUONTRGda: Show decoder warnings: " << cfg.WithWarnings() << endl;
1519     cout << "MUONTRGda: Use the fast decoder: " << cfg.UseFastDecoder() << endl;
1520     cout << "MUONTRGda: DA mode (1=GLOBAL, 2=GLOBAL+LOCAL): " << cfg.GetDAMode() << endl;
1521
1522     printf("MUONTRGda: Execution time : R:%7.2fs C:%7.2fs\n", timers.RealTime(), timers.CpuTime());
1523
1524     return status;
1525
1526 }
1527