]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/MUONTRKPEDda.cxx
Changing once more (hopefully we get it correct this time...) the logic to trig the...
[u/mrichter/AliRoot.git] / MUON / MUONTRKPEDda.cxx
1 /*
2   Contact: Jean-Luc Charvet <jean-luc.charvet@cern.ch>  
3   Link: http://aliceinfo.cern.ch/static/Offline/dimuon/muon_html/README_mchda.html
4   Reference Run: 109302 (station 3 only)
5   Run Type: PEDESTAL
6   DA Type: LDC
7   Number of events needed: 400 events for pedestal run
8   Input Files: mutrkpedvalues and config_ldc-MTRK-S3-0 in path : /afs/cern.ch/user/j/jcharvet/public/DA_validation 
9   Output Files: local dir (not persistent) -> MUONTRKPEDda.ped  FXS -> run<#>_MCH_<ldc>_PEDESTALS
10   Trigger types used:
11 */
12
13 /**************************************************************************
14  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
15  *                                                                        *
16  * Author: The ALICE Off-line Project.                                    *
17  * Contributors are mentioned in the code where appropriate.              *
18  *                                                                        *
19  * Permission to use, copy, modify and distribute this software and its   *
20  * documentation strictly for non-commercial purposes is hereby granted   *
21  * without fee, provided that the above copyright notice appears in all   *
22  * copies and that both the copyright notice and this permission notice   *
23  * appear in the supporting documentation. The authors make no claims     *
24  * about the suitability of this software for any purpose. It is          *
25  * provided "as is" without express or implied warranty.                  *
26  **************************************************************************/
27
28 /* $Id$ */
29
30 /*
31         -------------------------------------------------------------------------
32         2010-02-15 New version: MUONTRKPEDda.cxx,v 1.5
33         -------------------------------------------------------------------------
34
35         Version for MUONTRKPEDda MUON tracking
36         (A. Baldisseri, J.-L. Charvet)
37
38
39  Rem:  AliMUON2DMap stores all channels, even those which are not connected
40  if pedMean == -1, channel not connected to a pad  
41
42 &
43
44 */
45 extern "C" {
46 #include <daqDA.h>
47 }
48
49 #include "event.h"
50 #include "monitor.h"
51
52 #include <Riostream.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <sstream>
56 #include <math.h> 
57
58 //AliRoot
59 #include "AliMUONRawStreamTrackerHP.h"
60 #include "AliRawReader.h"
61 #include "AliMUONVStore.h"
62 #include "AliMUON2DMap.h"
63 #include "AliMUONCalibParamND.h"
64 #include "AliMpIntPair.h"
65 #include "AliMpConstants.h"
66 #include "AliRawDataErrorLog.h"
67 #include "AliMUONTrackerIO.h"
68 #include "AliLog.h"
69
70 //ROOT
71 #include "TFile.h"
72 #include "TSystem.h"
73 #include "TTree.h"
74 #include "TH1F.h"
75 #include "TString.h"
76 #include "TStopwatch.h"
77 #include "TMath.h"
78 #include "TTimeStamp.h"
79 #include "TGraphErrors.h"
80 #include "TF1.h"
81 #include "TROOT.h"
82 #include "TPluginManager.h"
83 #include "TFitter.h"
84 #include "TObjString.h"
85 #include "THashTable.h"
86 #include <THashList.h>
87 //
88 //AMORE
89 //
90 #ifdef ALI_AMORE
91 #include <AmoreDA.h>
92 #endif
93
94 #include "AliMUONPedestal.h"
95 #include "AliMUONErrorCounter.h"
96
97  
98 // main routine
99 int main(Int_t argc, const char **argv) 
100 {
101   Int_t status=0;
102   TStopwatch timers;
103   timers.Start(kTRUE); 
104
105   const char* prefixDA = "MUONTRKPEDda"; // program prefix
106   printf(" ######## Begin execution : %s ######## \n\n",prefixDA); 
107
108   // needed for streamer application
109   gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
110                                         "*",
111                                         "TStreamerInfo",
112                                         "RIO",
113                                         "TStreamerInfo()"); 
114   // needed for Minuit plugin
115   gROOT->GetPluginManager()->AddHandler("ROOT::Math::Minimizer",
116                                         "Minuit",
117                                         "TMinuitMinimizer",
118                                         "Minuit",
119                                         "TMinuitMinimizer(const char*)");
120 //   cout << argv[0];
121  
122   Int_t skipEvents = 0;
123   Int_t maxEvents  = 1000000;
124   Int_t maxDateEvents  = 1000000;
125   TString inputFile;
126
127   Int_t  nDateEvents = 0;
128   Int_t nGlitchErrors= 0;
129   Int_t nParityErrors= 0;
130   Int_t nPaddingErrors= 0;
131   Int_t nTokenlostErrors= 0;
132   Int_t recoverParityErrors = 1;
133
134   TString logOutputFile;
135
136   Char_t flatFile[256]="";
137   TString shuttleFile;
138
139   Int_t nEventsRecovered = 0;
140   Int_t nEvents = 0;
141   UInt_t runNumber   = 0;
142   Int_t nConfig = 1, writeConfig=0; 
143   ofstream filcout;
144
145   // decode the input line
146   for (Int_t i = 1; i < argc; i++) // argument 0 is the executable name
147     {
148       const char* arg = argv[i];
149
150       arg = argv[i];
151       if (arg[0] != '-') 
152         {
153           // If only one argument and no "-" => DA calling from ECS
154           if (argc == 2)
155             {
156         inputFile=argv[i];
157             }
158           continue;
159         }
160       switch (arg[1])
161         {
162         case 'f' : 
163           i++;
164       inputFile=argv[i];
165           nConfig=0;
166           break;
167         case 'a' : 
168           i++;
169           shuttleFile = argv[i];
170           break;
171         case 's' :
172           i++; 
173           skipEvents=atoi(argv[i]);
174           break;
175         case 'm' :
176           i++; 
177           sscanf(argv[i],"%d",&maxDateEvents);
178           break;
179         case 'n' :
180           i++; 
181           sscanf(argv[i],"%d",&maxEvents);
182           break;
183         case 'h' :
184           i++;
185           printf("\n******************* %s usage **********************",argv[0]);
186           printf("\nOnline (called from ECS) : %s <raw data file> (no inline options)\n",argv[0]);
187           printf("\n%s can be used locally only with options (without DiMuon configuration file)",argv[0]);
188           printf("\n%s -options, the available options are :",argv[0]);
189           printf("\n-h help                    (this screen)");
190           printf("\n");
191           printf("\n Input");
192           printf("\n-f <raw data file>         (default = %s)",inputFile.Data()); 
193           printf("\n");
194           printf("\n Output");
195           printf("\n-a <Flat ASCII file>       (default = %s)",shuttleFile.Data()); 
196           printf("\n");
197           printf("\n Options");
198           printf("\n-m <max date events>       (default = %d)",maxDateEvents);
199           printf("\n-s <skip events>           (default = %d)",skipEvents);
200           printf("\n-n <max events>            (default = %d)",maxEvents);
201
202           printf("\n\n");
203           exit(-1);
204         default :
205           printf("%s : bad argument %s (please check %s -h)\n",argv[0],argv[i],argv[0]);
206           argc = 2; exit(-1); // exit if error
207         } // end of switch  
208     } // end of for i  
209
210   // decoding the events
211
212   UShort_t manuId;  
213   UChar_t channelId;
214   UShort_t charge;
215
216   //Pedestal object
217   AliMUONPedestal* muonPedestal = new AliMUONPedestal();
218   muonPedestal->SetprefixDA(prefixDA);
219
220   Char_t dbfile[256]="";
221   // nConfig=1 : Reading configuration (or not) status via "mutrkpedvalues" file located in DetDB
222   if(nConfig)
223     { 
224       sprintf(dbfile,"mutrkpedvalues");
225       status=daqDA_DB_getFile(dbfile,dbfile);
226       if(status) {printf(" !!! Failed  : input file %s is missing, status = %d\n",dbfile,status); return -1; } 
227       ifstream filein(dbfile,ios::in);
228       filein >> nConfig;
229       filein >> writeConfig; // default=0, if 1 : current configuration file written in the Det.DataBase at the end of the DA
230       printf(" *** Copy: %s from DetDB to working directory  ***  Config= %d   writeConfig=%d\n",dbfile,nConfig,writeConfig);
231     }
232   else  printf(" ***  Config= %d: no configuration ascii file is used \n",nConfig); 
233   muonPedestal->SetconfigDA(nConfig);
234
235   // nConfig=1: configuration ascii file read from DetDB
236   if(nConfig)
237     {
238       // MuonTrk Configuration ascii file (initCROCUS.dat -> ascii file = config_$DATE_ROLE_NAME)
239       sprintf(dbfile,"config_%s",getenv("DATE_ROLE_NAME"));
240       status=daqDA_DB_getFile(dbfile,dbfile);
241       if(status) {printf(" !!! Failed  : Configuration file %s is missing, status = %d\n",dbfile,status); return -1; }
242       else printf(" *** Copy ascii config file: %s from DetDB to working directory and reading ...*** \n",dbfile);
243       muonPedestal->LoadConfig(dbfile);  
244     } 
245
246   // Rawdeader, RawStreamHP
247   AliRawReader* rawReader = AliRawReader::Create(inputFile);
248   AliMUONRawStreamTrackerHP* rawStream  = new AliMUONRawStreamTrackerHP(rawReader);    
249 //      rawStream->DisableWarnings();
250   rawStream->EnabbleErrorLogger();
251   //
252   // kLowErrorDetail,     /// Logs minimal information in the error messages.
253   // kMediumErrorDetail,  /// Logs a medium level of detail in the error messages.
254   // kHighErrorDetail     /// Logs maximum information in the error messages.
255   //  rawStream->SetLoggingDetailLevel(AliMUONRawStreamTrackerHP::kLowErrorDetail);
256    rawStream->SetLoggingDetailLevel(AliMUONRawStreamTrackerHP::kHighErrorDetail);
257
258   printf("\n %s : Reading data from file %s\n",prefixDA,inputFile.Data());
259
260   while (rawReader->NextEvent())
261     {
262       if (nDateEvents >= maxDateEvents) break;
263       if (nEvents >= maxEvents) break;
264       if (nDateEvents>0 &&  nDateEvents % 100 == 0)     
265         cout<<"Cumulated:  DATE events = " << nDateEvents << "   Used events = " << nEvents << endl;
266
267       // check shutdown condition 
268       if (daqDA_checkShutdown()) 
269         break;
270
271       //Skip events
272       while (skipEvents)
273         {
274           rawReader->NextEvent();
275           skipEvents--;
276         }
277
278       Int_t eventType = rawReader->GetType();
279       runNumber = rawReader->GetRunNumber();
280
281       // Output log file initialisations
282       if(nDateEvents==0)
283         {
284           sprintf(flatFile,"%s.log",prefixDA);
285           logOutputFile=flatFile;
286                 AliLog::SetStreamOutput(&filcout); // Print details on logfile
287           filcout.open(logOutputFile.Data());
288           filcout<<"//=================================================" << endl;
289           filcout<<"//       " << prefixDA << " for run = " << runNumber << endl;
290           filcout<<"//=================================================" << endl;
291           filcout<<"//   * Date          : " << muonPedestal->GetDate()->AsString("l") << "\n" << endl;
292           cout<<"\n ********  " << prefixDA << " for run = " << runNumber << " ********\n" << endl;
293           cout<<" * Date          : " << muonPedestal->GetDate()->AsString("l") << "\n" << endl;
294
295         }
296
297       muonPedestal->SetAlifilcout(&filcout);
298
299       nDateEvents++;
300       if (eventType != PHYSICS_EVENT)
301         continue; // for the moment
302
303       // First lopp over DDL's to find good events
304       // Error counters per event (counters in the decoding lib are for each DDL)
305       Bool_t eventIsErrorMessage = kFALSE;
306       int eventGlitchErrors = 0;
307       int eventParityErrors = 0;
308       int eventPaddingErrors = 0;
309       int eventTokenlostErrors = 0;
310       rawStream->First();
311       do
312         {
313           if (rawStream->IsErrorMessage()) eventIsErrorMessage = kTRUE;
314           eventGlitchErrors += rawStream->GetGlitchErrors();
315           eventParityErrors += rawStream->GetParityErrors();
316           eventPaddingErrors += rawStream->GetPaddingErrors();
317           eventTokenlostErrors += rawStream->GetTokenLostErrors();
318         } while(rawStream->NextDDL()); 
319
320       AliMUONRawStreamTrackerHP::AliBusPatch* busPatch;
321       if (!eventIsErrorMessage) 
322         {
323           // Good events (no error) -> compute pedestal for all channels
324           rawStream->First(); 
325           while( (busPatch = (AliMUONRawStreamTrackerHP::AliBusPatch*) rawStream->Next())) 
326             {
327               for(int i = 0; i < busPatch->GetLength(); ++i)
328                 {
329                   busPatch->GetData(i, manuId, channelId, charge);
330                   muonPedestal->MakePed(busPatch->GetBusPatchId(), (Int_t)manuId, (Int_t)channelId, (Int_t)charge);
331                 }
332             }
333           nEvents++;
334         }
335       else
336         {
337           // Events with errors
338           if (recoverParityErrors && eventParityErrors && !eventGlitchErrors&& !eventPaddingErrors)
339             {
340               filcout << " ----------- Date Event recovered = " << nDateEvents <<  " ----------------" << endl;
341               // Recover parity errors -> compute pedestal for all good buspatches
342               if ( TEST_SYSTEM_ATTRIBUTE( rawReader->GetAttributes(),
343                                           ATTR_ORBIT_BC )) 
344                 {
345                   filcout <<"Event recovered -> Period:"<<EVENT_ID_GET_PERIOD( rawReader->GetEventId() )
346                               <<" Orbit:"<<EVENT_ID_GET_ORBIT( rawReader->GetEventId() )
347                               <<" BunchCrossing:"<<EVENT_ID_GET_BUNCH_CROSSING( rawReader->GetEventId() )<<endl;                                
348                 } 
349               else 
350                 {
351                   filcout <<"Event recovered -> nbInRun:"<<EVENT_ID_GET_NB_IN_RUN( rawReader->GetEventId() )
352                               <<" burstNb:"<<EVENT_ID_GET_BURST_NB( rawReader->GetEventId() )
353                               <<" nbInBurst:"<<EVENT_ID_GET_NB_IN_BURST( rawReader->GetEventId() )<<endl;
354                 }
355               rawStream->First();
356               while( (busPatch = (AliMUONRawStreamTrackerHP::AliBusPatch*) rawStream->Next())) 
357                 {
358                   // Check the buspatch -> if error not use it in the pedestal calculation
359                   int errorCount = 0;
360                   for(int i = 0; i < busPatch->GetLength(); ++i)
361                     {
362                       if (!busPatch->IsParityOk(i)) errorCount++;
363                     }
364                   if (!errorCount) 
365                     {
366                       // Good buspatch
367                       for(int i = 0; i < busPatch->GetLength(); ++i)
368                         {
369                           busPatch->GetData(i, manuId, channelId, charge);
370                           muonPedestal->MakePed(busPatch->GetBusPatchId(), (Int_t)manuId, (Int_t)channelId, (Int_t)charge);
371                         }
372                     }
373                   else
374                     {
375                       AliMUONErrorCounter* errorCounter;
376                       // Bad buspatch -> not used (just print)
377                       filcout<<"bpId "<<busPatch->GetBusPatchId()<<" words "<<busPatch->GetLength()
378                                  <<" parity errors "<<errorCount<<endl;
379                       // Number of events where this buspatch is missing
380                       if (!(errorCounter = (AliMUONErrorCounter*) (muonPedestal->GetErrorBuspatchTable()->FindObject(busPatch->GetBusPatchId()))))
381                         {
382                           // New buspatch
383                           errorCounter = new AliMUONErrorCounter(busPatch->GetBusPatchId());
384                           muonPedestal->GetErrorBuspatchTable()->Add(errorCounter);
385                         }
386                       else
387                         {
388                           // Existing buspatch
389                           errorCounter->Increment();
390                         }       
391                       // errorCounter->Print();                                         
392                     } // end of if (!errorCount)
393                 } // end of while( (busPatch = (AliMUONRawStreamTrackerHP ...
394               nEvents++;
395               nEventsRecovered++;
396             } //end of if (recoverParityErrors && eventParityErrors && !eventGlitchErrors&& !eventPaddingErrors)
397           else
398             {
399               filcout << " ----------- Date Event rejected = " << nDateEvents <<  " ----------------" << endl;
400               // Fatal errors reject the event
401               if ( TEST_SYSTEM_ATTRIBUTE( rawReader->GetAttributes(),
402                                           ATTR_ORBIT_BC )) 
403                 {
404                   filcout <<"Event rejected -> Period:"<<EVENT_ID_GET_PERIOD( rawReader->GetEventId() )
405                               <<" Orbit:"<<EVENT_ID_GET_ORBIT( rawReader->GetEventId() )
406                               <<" BunchCrossing:"<<EVENT_ID_GET_BUNCH_CROSSING( rawReader->GetEventId() )<<endl;                                
407                 } 
408               else 
409                 {
410                   filcout <<"Event rejected -> nbInRun:"<<EVENT_ID_GET_NB_IN_RUN( rawReader->GetEventId() )
411                               <<" burstNb:"<<EVENT_ID_GET_BURST_NB( rawReader->GetEventId() )
412                               <<" nbInBurst:"<<EVENT_ID_GET_NB_IN_BURST( rawReader->GetEventId() )<<endl;
413
414                 }
415             } // end of if (!rawStream->GetGlitchErrors() && !rawStream->GetPaddingErrors() ...
416           filcout<<"Number of errors : Glitch "<<eventGlitchErrors
417                      <<" Parity "<<eventParityErrors
418                      <<" Padding "<<eventPaddingErrors
419                      <<" Token lost "<<eventTokenlostErrors<<endl;
420           filcout<<endl;                        
421         } // end of if (!rawStream->IsErrorMessage())
422
423       if (eventGlitchErrors)  nGlitchErrors++;
424       if (eventParityErrors)  nParityErrors++;
425       if (eventPaddingErrors) nPaddingErrors++;
426       if (eventTokenlostErrors) nTokenlostErrors++;
427
428     } // while (rawReader->NextEvent())
429   delete rawReader;
430   delete rawStream;
431
432   sprintf(flatFile,"%s.ped",prefixDA);
433   if(shuttleFile.IsNull())shuttleFile=flatFile;
434   muonPedestal->SetAliNEvents(nEvents);
435   muonPedestal->SetAliRunNumber(runNumber);
436   
437   muonPedestal->Finalize();  
438   muonPedestal->MakeControlHistos();  
439   if (!shuttleFile.IsNull())  
440   {
441     ofstream out(shuttleFile.Data());  
442     muonPedestal->MakeASCIIoutput(out);
443     out.close();
444 #ifdef ALI_AMORE
445   //
446   //Send objects to the AMORE DB
447   //
448     ostringstream stringout;
449     muonPedestal->MakeASCIIoutput(stringout);
450     
451     amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
452     TObjString peddata(stringout.str().c_str());
453     Int_t status =0;
454     status = amoreDA.Send("Pedestals",&peddata);
455     if ( status )
456       cout << "Warning: Failed to write Pedestals in the AMORE database : " << status << endl;
457     else 
458       cout << "amoreDA.Send(Pedestals) ok" << endl;  
459 #else
460     cout << "Warning: MCH DA not compiled with AMORE support" << endl;
461 #endif
462     
463   }
464
465   // writing some counters
466   cout << endl;
467   cout << prefixDA << " : Nb of DATE events           = " << nDateEvents    << endl;
468   cout << prefixDA << " : Nb of Glitch errors         = "   << nGlitchErrors  << endl;
469   cout << prefixDA << " : Nb of Parity errors         = "   << nParityErrors  << endl;
470   cout << prefixDA << " : Nb of Padding errors        = "   << nPaddingErrors << endl;  
471   cout << prefixDA << " : Nb of Token lost errors     = "   << nTokenlostErrors << endl;
472   cout << prefixDA << " : Nb of events recovered      = "   << nEventsRecovered<< endl;
473   cout << prefixDA << " : Nb of events without errors = "   << nEvents-nEventsRecovered<< endl;
474   cout << prefixDA << " : Nb of events used           = "   << nEvents        << endl;
475
476   filcout << endl;
477   filcout << prefixDA << " : Nb of DATE events           = " << nDateEvents    << endl;
478   filcout << prefixDA << " : Nb of Glitch errors         = "   << nGlitchErrors << endl;
479   filcout << prefixDA << " : Nb of Parity errors         = "   << nParityErrors << endl;
480   filcout << prefixDA << " : Nb of Padding errors        = "   << nPaddingErrors << endl;
481   filcout << prefixDA << " : Nb of Token lost errors     = "   << nTokenlostErrors << endl;
482   filcout << prefixDA << " : Nb of events recovered      = "   << nEventsRecovered<< endl;      
483   filcout << prefixDA << " : Nb of events without errors = "   << nEvents-nEventsRecovered<< endl;
484   filcout << prefixDA << " : Nb of events used           = "   << nEvents        << endl;
485
486   // ouput files
487   cout << endl;
488   cout << prefixDA << " : Output logfile         : " << logOutputFile  << endl;
489   cout << prefixDA << " : Pedestal Histo file    : " << muonPedestal->GetHistoFileName() << endl;
490   cout << prefixDA << " : Ped. file (to SHUTTLE) : " << shuttleFile << endl;   
491
492   filcout << endl;
493   filcout << prefixDA << " : Output logfile         : " << logOutputFile  << endl;
494   filcout << prefixDA << " : Pedestal Histo file    : " << muonPedestal->GetHistoFileName() << endl;
495   filcout << prefixDA << " : Ped. file (to SHUTTLE) : " << shuttleFile << endl;   
496
497  // Copying files to local DB folder defined by DAQ_DETDB_LOCAL
498   Char_t *dir;
499   dir= getenv("DAQ_DETDB_LOCAL");
500   unsigned int nLastVersions=50;
501   cout << "\n ***  Local DataBase: " << dir << " (Max= " << nLastVersions << ") ***" << endl;
502   status = daqDA_localDB_storeFile(muonPedestal->GetHistoFileName(),nLastVersions);
503   if(status)printf(" Store file : %s   status = %d\n",muonPedestal->GetHistoFileName(),status);
504   status = daqDA_localDB_storeFile(shuttleFile.Data(),nLastVersions);
505   if(status)printf(" Store file : %s   status = %d\n",shuttleFile.Data(),status);
506   status = daqDA_localDB_storeFile(logOutputFile.Data(),nLastVersions);
507   if(status)printf(" Store file : %s   status = %d\n",logOutputFile.Data(),status);
508
509   filcout.close();
510
511   // Transferring to OCDB via the SHUTTLE (be sure that env variable DAQDALIB_PATH is set)
512   printf("\n *****  STORE FILE in FES ****** \n");
513   status = daqDA_FES_storeFile(shuttleFile.Data(),"PEDESTALS");
514   if (status) { printf(" !!! Failed to export file : %s , status = %d\n",shuttleFile.Data(),status); return -1; }
515   else printf(" %s successfully exported to FES  \n",shuttleFile.Data());
516
517   // Transferring to DetectorDataBase the configuration file if changed
518   if(writeConfig)
519     {
520       printf("\n *****  New detector configuration : STORE Config FILE in Detector DataBase ****** \n");
521       Char_t DAdbfile[256]="";
522       //      TString DAdbfile=Form("DA_config_%s",getenv("DATE_ROLE_NAME")) ;
523       sprintf(DAdbfile,"DA_config_%s",getenv("DATE_ROLE_NAME"));
524       status=daqDA_DB_storeFile(dbfile,DAdbfile);
525       if(status) {printf(" !!! Failed  : Pb to store config. file %s in DetDB (%s), status = %d\n",dbfile,DAdbfile,status); return -1; }
526       else printf(" Copy ascii current config file: %s to %s in DetDB \n",dbfile,DAdbfile);
527     }
528
529   printf("\n ######## End execution : %s ######## \n",prefixDA); 
530   timers.Stop();
531   printf("\nExecution time : R:%7.2fs C:%7.2fs\n", timers.RealTime(), timers.CpuTime());
532   return status;
533 }