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