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