]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/MUONTRKPEDda.cxx
PED and GAIN DAs update
[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: 104540
5   Run Type: PEDESTAL
6   DA Type: LDC
7   Number of events needed: 400 events for pedestal run
8   Input Files: /alice/cern.ch/user/j/jcharvet/mutrkpedvalues and /alice/cern.ch/user/j/jcharvet/config_ldc-MTRK-S0-0 
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-01-13 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
69 //ROOT
70 #include "TFile.h"
71 #include "TSystem.h"
72 #include "TTree.h"
73 #include "TH1F.h"
74 #include "TString.h"
75 #include "TStopwatch.h"
76 #include "TMath.h"
77 #include "TTimeStamp.h"
78 #include "TGraphErrors.h"
79 #include "TF1.h"
80 #include "TROOT.h"
81 #include "TPluginManager.h"
82 #include "TFitter.h"
83 #include "TObjString.h"
84 #include "THashTable.h"
85 #include <THashList.h>
86 //
87 //AMORE
88 //
89 #ifdef ALI_AMORE
90 #include <AmoreDA.h>
91 #endif
92
93 #include "AliMUONPedestal.h"
94 #include "AliMUONErrorCounter.h"
95
96
97 // main routine
98 int main(Int_t argc, const char **argv) 
99 {
100   Int_t status=0;
101   TStopwatch timers;
102   timers.Start(kTRUE); 
103
104   const char* prefixDA = "MUONTRKPEDda"; // program prefix
105   printf(" ######## Begin execution : %s ######## \n\n",prefixDA); 
106
107   // needed for streamer application
108   gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
109                                         "*",
110                                         "TStreamerInfo",
111                                         "RIO",
112                                         "TStreamerInfo()"); 
113   // needed for Minuit plugin
114   gROOT->GetPluginManager()->AddHandler("ROOT::Math::Minimizer",
115                                         "Minuit",
116                                         "TMinuitMinimizer",
117                                         "Minuit",
118                                         "TMinuitMinimizer(const char*)");
119 //   cout << argv[0];
120  
121   Int_t skipEvents = 0;
122   Int_t maxEvents  = 1000000;
123   Int_t maxDateEvents  = 1000000;
124   TString inputFile;
125
126   Int_t  nDateEvents = 0;
127   Int_t nGlitchErrors= 0;
128   Int_t nParityErrors= 0;
129   Int_t nPaddingErrors= 0;
130   Int_t recoverParityErrors = 1;
131
132   TString logOutputFile;
133
134   Char_t flatFile[256]="";
135   TString shuttleFile;
136
137   Int_t nEventsRecovered = 0;
138   Int_t nEvents = 0;
139   UInt_t runNumber   = 0;
140   Int_t nConfig = 1, writeConfig=0; 
141   ofstream filcout;
142
143   // decode the input line
144   for (Int_t i = 1; i < argc; i++) // argument 0 is the executable name
145     {
146       const char* arg = argv[i];
147
148       arg = argv[i];
149       if (arg[0] != '-') 
150         {
151           // If only one argument and no "-" => DA calling from ECS
152           if (argc == 2)
153             {
154         inputFile=argv[i];
155             }
156           continue;
157         }
158       switch (arg[1])
159         {
160         case 'f' : 
161           i++;
162       inputFile=argv[i];
163           nConfig=0;
164           break;
165         case 'a' : 
166           i++;
167           shuttleFile = argv[i];
168           break;
169         case 's' :
170           i++; 
171           skipEvents=atoi(argv[i]);
172           break;
173         case 'm' :
174           i++; 
175           sscanf(argv[i],"%d",&maxDateEvents);
176           break;
177         case 'n' :
178           i++; 
179           sscanf(argv[i],"%d",&maxEvents);
180           break;
181         case 'h' :
182           i++;
183           printf("\n******************* %s usage **********************",argv[0]);
184           printf("\nOnline (called from ECS) : %s <raw data file> (no inline options)\n",argv[0]);
185           printf("\n%s can be used locally only with options (without DiMuon configuration file)",argv[0]);
186           printf("\n%s -options, the available options are :",argv[0]);
187           printf("\n-h help                    (this screen)");
188           printf("\n");
189           printf("\n Input");
190           printf("\n-f <raw data file>         (default = %s)",inputFile.Data()); 
191           printf("\n");
192           printf("\n Output");
193           printf("\n-a <Flat ASCII file>       (default = %s)",shuttleFile.Data()); 
194           printf("\n");
195           printf("\n Options");
196           printf("\n-m <max date events>       (default = %d)",maxDateEvents);
197           printf("\n-s <skip events>           (default = %d)",skipEvents);
198           printf("\n-n <max events>            (default = %d)",maxEvents);
199
200           printf("\n\n");
201           exit(-1);
202         default :
203           printf("%s : bad argument %s (please check %s -h)\n",argv[0],argv[i],argv[0]);
204           argc = 2; exit(-1); // exit if error
205         } // end of switch  
206     } // end of for i  
207
208   // decoding the events
209
210   UShort_t manuId;  
211   UChar_t channelId;
212   UShort_t charge;
213
214   //Pedestal object
215   AliMUONPedestal* muonPedestal = new AliMUONPedestal();
216   muonPedestal->SetprefixDA(prefixDA);
217
218   Char_t dbfile[256]="";
219   // nConfig=1 : Reading configuration (or not) status via "mutrkpedvalues" file located in DetDB
220   if(nConfig)
221     { 
222       sprintf(dbfile,"mutrkpedvalues");
223       status=daqDA_DB_getFile(dbfile,dbfile);
224       if(status) {printf(" !!! Failed  : input file %s is missing, status = %d\n",dbfile,status); return -1; } 
225       ifstream filein(dbfile,ios::in);
226       filein >> nConfig;
227       filein >> writeConfig; // default=0, if 1 : current configuration file written in the Det.DataBase at the end of the DA
228       printf(" *** Copy: %s from DetDB to working directory  ***  Config= %d   writeConfig=%d\n",dbfile,nConfig,writeConfig);
229     }
230   else  printf(" ***  Config= %d: no configuration ascii file is used \n",nConfig); 
231   muonPedestal->SetconfigDA(nConfig);
232
233   // nConfig=1: configuration ascii file read from DetDB
234   if(nConfig)
235     {
236       // MuonTrk Configuration ascii file (initCROCUS.dat -> ascii file = config_$DATE_ROLE_NAME)
237       sprintf(dbfile,"config_%s",getenv("DATE_ROLE_NAME"));
238       status=daqDA_DB_getFile(dbfile,dbfile);
239       if(status) {printf(" !!! Failed  : Configuration file %s is missing, status = %d\n",dbfile,status); return -1; }
240       else printf(" *** Copy ascii config file: %s from DetDB to working directory and reading ...*** \n",dbfile);
241       muonPedestal->LoadConfig(dbfile);  
242     } 
243
244   // Rawdeader, RawStreamHP
245   AliRawReader* rawReader = AliRawReader::Create(inputFile);
246   AliMUONRawStreamTrackerHP* rawStream  = new AliMUONRawStreamTrackerHP(rawReader);    
247   rawStream->DisableWarnings();
248   rawStream->EnabbleErrorLogger();
249
250   printf("\n %s : Reading data from file %s\n",prefixDA,inputFile.Data());
251
252   while (rawReader->NextEvent())
253     {
254       if (nDateEvents >= maxDateEvents) break;
255       if (nEvents >= maxEvents) break;
256       if (nDateEvents>0 &&  nDateEvents % 100 == 0)     
257         cout<<"Cumulated:  DATE events = " << nDateEvents << "   Used events = " << nEvents << endl;
258
259       // check shutdown condition 
260       if (daqDA_checkShutdown()) 
261         break;
262
263       //Skip events
264       while (skipEvents)
265         {
266           rawReader->NextEvent();
267           skipEvents--;
268         }
269
270       Int_t eventType = rawReader->GetType();
271       runNumber = rawReader->GetRunNumber();
272
273       // Output log file initialisations
274       if(nDateEvents==0)
275         {
276           sprintf(flatFile,"%s.log",prefixDA);
277           logOutputFile=flatFile;
278
279           filcout.open(logOutputFile.Data());
280           filcout<<"//=================================================" << endl;
281           filcout<<"//       " << prefixDA << " for run = " << runNumber << endl;
282           filcout<<"//=================================================" << endl;
283           filcout<<"//   * Date          : " << muonPedestal->GetDate()->AsString("l") << "\n" << endl;
284           cout<<"\n ********  " << prefixDA << " for run = " << runNumber << " ********\n" << endl;
285           cout<<" * Date          : " << muonPedestal->GetDate()->AsString("l") << "\n" << endl;
286
287         }
288
289       muonPedestal->SetAlifilcout(&filcout);
290
291       nDateEvents++;
292       if (eventType != PHYSICS_EVENT)
293         continue; // for the moment
294
295       // First lopp over DDL's to find good events
296       // Error counters per event (counters in the decoding lib are for each DDL)
297       Bool_t eventIsErrorMessage = kFALSE;
298       int eventGlitchErrors = 0;
299       int eventParityErrors = 0;
300       int eventPaddingErrors = 0;
301       rawStream->First();
302       do
303         {
304           if (rawStream->IsErrorMessage()) eventIsErrorMessage = kTRUE;
305           eventGlitchErrors += rawStream->GetGlitchErrors();
306           eventParityErrors += rawStream->GetParityErrors();
307           eventPaddingErrors += rawStream->GetPaddingErrors();
308         } while(rawStream->NextDDL()); 
309
310       AliMUONRawStreamTrackerHP::AliBusPatch* busPatch;
311       if (!eventIsErrorMessage) 
312         {
313           // Good events (no error) -> compute pedestal for all channels
314           rawStream->First(); 
315           while( (busPatch = (AliMUONRawStreamTrackerHP::AliBusPatch*) rawStream->Next())) 
316             {
317               for(int i = 0; i < busPatch->GetLength(); ++i)
318                 {
319                   busPatch->GetData(i, manuId, channelId, charge);
320                   muonPedestal->MakePed(busPatch->GetBusPatchId(), (Int_t)manuId, (Int_t)channelId, (Int_t)charge);
321                 }
322             }
323           nEvents++;
324         }
325       else
326         {
327           // Events with errors
328           if (recoverParityErrors && eventParityErrors && !eventGlitchErrors&& !eventPaddingErrors)
329             {
330               // Recover parity errors -> compute pedestal for all good buspatches
331               if ( TEST_SYSTEM_ATTRIBUTE( rawReader->GetAttributes(),
332                                           ATTR_ORBIT_BC )) 
333                 {
334                   filcout <<"Event recovered -> Period:"<<EVENT_ID_GET_PERIOD( rawReader->GetEventId() )
335                               <<" Orbit:"<<EVENT_ID_GET_ORBIT( rawReader->GetEventId() )
336                               <<" BunchCrossing:"<<EVENT_ID_GET_BUNCH_CROSSING( rawReader->GetEventId() )<<endl;                                
337                 } 
338               else 
339                 {
340                   filcout <<"Event recovered -> nbInRun:"<<EVENT_ID_GET_NB_IN_RUN( rawReader->GetEventId() )
341                               <<" burstNb:"<<EVENT_ID_GET_BURST_NB( rawReader->GetEventId() )
342                               <<" nbInBurst:"<<EVENT_ID_GET_NB_IN_BURST( rawReader->GetEventId() )<<endl;
343                 }
344               rawStream->First();
345               while( (busPatch = (AliMUONRawStreamTrackerHP::AliBusPatch*) rawStream->Next())) 
346                 {
347                   // Check the buspatch -> if error not use it in the pedestal calculation
348                   int errorCount = 0;
349                   for(int i = 0; i < busPatch->GetLength(); ++i)
350                     {
351                       if (!busPatch->IsParityOk(i)) errorCount++;
352                     }
353                   if (!errorCount) 
354                     {
355                       // Good buspatch
356                       for(int i = 0; i < busPatch->GetLength(); ++i)
357                         {
358                           busPatch->GetData(i, manuId, channelId, charge);
359                           muonPedestal->MakePed(busPatch->GetBusPatchId(), (Int_t)manuId, (Int_t)channelId, (Int_t)charge);
360                         }
361                     }
362                   else
363                     {
364                       AliMUONErrorCounter* errorCounter;
365                       // Bad buspatch -> not used (just print)
366                       filcout<<"bpId "<<busPatch->GetBusPatchId()<<" words "<<busPatch->GetLength()
367                                  <<" parity errors "<<errorCount<<endl;
368                       // Number of events where this buspatch is missing
369                       if (!(errorCounter = (AliMUONErrorCounter*) (muonPedestal->GetErrorBuspatchTable()->FindObject(busPatch->GetBusPatchId()))))
370                         {
371                           // New buspatch
372                           errorCounter = new AliMUONErrorCounter(busPatch->GetBusPatchId());
373                           muonPedestal->GetErrorBuspatchTable()->Add(errorCounter);
374                         }
375                       else
376                         {
377                           // Existing buspatch
378                           errorCounter->Increment();
379                         }       
380                       // errorCounter->Print();                                         
381                     } // end of if (!errorCount)
382                 } // end of while( (busPatch = (AliMUONRawStreamTrackerHP ...
383               nEvents++;
384               nEventsRecovered++;
385             } //end of if (recoverParityErrors && eventParityErrors && !eventGlitchErrors&& !eventPaddingErrors)
386           else
387             {
388               // Fatal errors reject the event
389               if ( TEST_SYSTEM_ATTRIBUTE( rawReader->GetAttributes(),
390                                           ATTR_ORBIT_BC )) 
391                 {
392                   filcout <<"Event rejected -> Period:"<<EVENT_ID_GET_PERIOD( rawReader->GetEventId() )
393                               <<" Orbit:"<<EVENT_ID_GET_ORBIT( rawReader->GetEventId() )
394                               <<" BunchCrossing:"<<EVENT_ID_GET_BUNCH_CROSSING( rawReader->GetEventId() )<<endl;                                
395                 } 
396               else 
397                 {
398                   filcout <<"Event rejected -> nbInRun:"<<EVENT_ID_GET_NB_IN_RUN( rawReader->GetEventId() )
399                               <<" burstNb:"<<EVENT_ID_GET_BURST_NB( rawReader->GetEventId() )
400                               <<" nbInBurst:"<<EVENT_ID_GET_NB_IN_BURST( rawReader->GetEventId() )<<endl;
401
402                 }
403             } // end of if (!rawStream->GetGlitchErrors() && !rawStream->GetPaddingErrors() ...
404           filcout<<"Number of errors : Glitch "<<eventGlitchErrors
405                      <<" Parity "<<eventParityErrors
406                      <<" Padding "<<eventPaddingErrors<<endl;
407           filcout<<endl;                        
408         } // end of if (!rawStream->IsErrorMessage())
409
410       if (eventGlitchErrors)  nGlitchErrors++;
411       if (eventParityErrors)  nParityErrors++;
412       if (eventPaddingErrors) nPaddingErrors++;
413
414     } // while (rawReader->NextEvent())
415   delete rawReader;
416   delete rawStream;
417
418   sprintf(flatFile,"%s.ped",prefixDA);
419   if(shuttleFile.IsNull())shuttleFile=flatFile;
420   muonPedestal->SetAliNEvents(nEvents);
421   muonPedestal->SetAliRunNumber(runNumber);
422   
423   muonPedestal->Finalize();  
424   muonPedestal->MakeControlHistos();  
425   if (!shuttleFile.IsNull())  
426   {
427     ofstream out(shuttleFile.Data());  
428     muonPedestal->MakeASCIIoutput(out);
429     out.close();
430 #ifdef ALI_AMORE
431   //
432   //Send objects to the AMORE DB
433   //
434     ostringstream stringout;
435     muonPedestal->MakeASCIIoutput(stringout);
436     
437     amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
438     TObjString peddata(stringout.str().c_str());
439     Int_t status =0;
440     status = amoreDA.Send("Pedestals",&peddata);
441     if ( status )
442       cout << "Warning: Failed to write Pedestals in the AMORE database : " << status << endl;
443     else 
444       cout << "amoreDA.Send(Pedestals) ok" << endl;  
445 #else
446     cout << "Warning: MCH DA not compiled with AMORE support" << endl;
447 #endif
448     
449   }
450
451   // writing some counters
452   cout << endl;
453   cout << prefixDA << " : Nb of DATE events           = " << nDateEvents    << endl;
454   cout << prefixDA << " : Nb of Glitch errors         = "   << nGlitchErrors  << endl;
455   cout << prefixDA << " : Nb of Parity errors         = "   << nParityErrors  << endl;
456   cout << prefixDA << " : Nb of Padding errors        = "   << nPaddingErrors << endl;          
457   cout << prefixDA << " : Nb of events recovered      = "   << nEventsRecovered<< endl;
458   cout << prefixDA << " : Nb of events without errors = "   << nEvents-nEventsRecovered<< endl;
459   cout << prefixDA << " : Nb of events used           = "   << nEvents        << endl;
460
461   filcout << endl;
462   filcout << prefixDA << " : Nb of DATE events           = " << nDateEvents    << endl;
463   filcout << prefixDA << " : Nb of Glitch errors         = "   << nGlitchErrors << endl;
464   filcout << prefixDA << " : Nb of Parity errors         = "   << nParityErrors << endl;
465   filcout << prefixDA << " : Nb of Padding errors        = "   << nPaddingErrors << endl;
466   filcout << prefixDA << " : Nb of events recovered      = "   << nEventsRecovered<< endl;      
467   filcout << prefixDA << " : Nb of events without errors = "   << nEvents-nEventsRecovered<< endl;
468   filcout << prefixDA << " : Nb of events used           = "   << nEvents        << endl;
469
470   // ouput files
471   cout << endl;
472   cout << prefixDA << " : Output logfile         : " << logOutputFile  << endl;
473   cout << prefixDA << " : Pedestal Histo file    : " << muonPedestal->GetHistoFileName() << endl;
474   cout << prefixDA << " : Ped. file (to SHUTTLE) : " << shuttleFile << endl;   
475
476   filcout << endl;
477   filcout << prefixDA << " : Output logfile         : " << logOutputFile  << endl;
478   filcout << prefixDA << " : Pedestal Histo file    : " << muonPedestal->GetHistoFileName() << endl;
479   filcout << prefixDA << " : Ped. file (to SHUTTLE) : " << shuttleFile << endl;   
480
481  // Copying files to local DB folder defined by DAQ_DETDB_LOCAL
482   Char_t *dir;
483   dir= getenv("DAQ_DETDB_LOCAL");
484   unsigned int nLastVersions=50;
485   cout << "\n ***  Local DataBase: " << dir << " (Max= " << nLastVersions << ") ***" << endl;
486   status = daqDA_localDB_storeFile(muonPedestal->GetHistoFileName(),nLastVersions);
487   if(status)printf(" Store file : %s   status = %d\n",muonPedestal->GetHistoFileName(),status);
488   status = daqDA_localDB_storeFile(shuttleFile.Data(),nLastVersions);
489   if(status)printf(" Store file : %s   status = %d\n",shuttleFile.Data(),status);
490   status = daqDA_localDB_storeFile(logOutputFile.Data(),nLastVersions);
491   if(status)printf(" Store file : %s   status = %d\n",logOutputFile.Data(),status);
492
493   filcout.close();
494
495   // Transferring to OCDB via the SHUTTLE (be sure that env variable DAQDALIB_PATH is set)
496   printf("\n *****  STORE FILE in FES ****** \n");
497   status = daqDA_FES_storeFile(shuttleFile.Data(),"PEDESTALS");
498   if (status) { printf(" !!! Failed to export file : %s , status = %d\n",shuttleFile.Data(),status); return -1; }
499   else printf(" %s successfully exported to FES  \n",shuttleFile.Data());
500
501   // Transferring to DetectorDataBase the configuration file if changed
502   if(writeConfig)
503     {
504       printf("\n *****  New detector configuration : STORE Config FILE in Detector DataBase ****** \n");
505       Char_t DAdbfile[256]="";
506       //      TString DAdbfile=Form("DA_config_%s",getenv("DATE_ROLE_NAME")) ;
507       sprintf(DAdbfile,"DA_config_%s",getenv("DATE_ROLE_NAME"));
508       status=daqDA_DB_storeFile(dbfile,DAdbfile);
509       if(status) {printf(" !!! Failed  : Pb to store config. file %s in DetDB (%s), status = %d\n",dbfile,DAdbfile,status); return -1; }
510       else printf(" Copy ascii current config file: %s to %s in DetDB \n",dbfile,DAdbfile);
511     }
512
513   printf("\n ######## End execution : %s ######## \n",prefixDA); 
514   timers.Stop();
515   printf("\nExecution time : R:%7.2fs C:%7.2fs\n", timers.RealTime(), timers.CpuTime());
516   return status;
517 }