]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliAODHandler.cxx
Bug fixed.
[u/mrichter/AliRoot.git] / STEER / AliAODHandler.cxx
1
2 /**************************************************************************
3  * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
4  *                                                                        *
5  * Author: The ALICE Off-line Project.                                    *
6  * Contributors are mentioned in the code where appropriate.              *
7  *                                                                        *
8  * Permission to use, copy, modify and distribute this software and its   *
9  * documentation strictly for non-commercial purposes is hereby granted   *
10  * without fee, provided that the above copyright notice appears in all   *
11  * copies and that both the copyright notice and this permission notice   *
12  * appear in the supporting documentation. The authors make no claims     *
13  * about the suitability of this software for any purpose. It is          *
14  * provided "as is" without express or implied warranty.                  *
15  **************************************************************************/
16
17 /* $Id$ */
18
19 //-------------------------------------------------------------------------
20 //     Implementation of the Virtual Event Handler Interface for AOD
21 //     Author: Andreas Morsch, CERN
22 //-------------------------------------------------------------------------
23
24
25 #include <TTree.h>
26 #include <TFile.h>
27 #include <TString.h>
28 #include <TList.h>
29 #include <TROOT.h>
30
31 #include "AliLog.h"
32 #include "AliAODHandler.h"
33 #include "AliAODEvent.h"
34 #include "AliAODTracklets.h"
35 #include "AliStack.h"
36 #include "AliAODMCParticle.h"
37 #include "AliAODMCHeader.h"
38 #include "AliMCEventHandler.h"
39 #include "AliMCEvent.h"
40 #include "AliGenEventHeader.h"
41 #include "AliGenHijingEventHeader.h"
42 #include "AliGenDPMjetEventHeader.h"
43 #include "AliGenPythiaEventHeader.h"
44 #include "AliGenCocktailEventHeader.h"
45
46
47
48 ClassImp(AliAODHandler)
49
50 //______________________________________________________________________________
51 AliAODHandler::AliAODHandler() :
52     AliVEventHandler(),
53     fIsStandard(kTRUE),
54     fFillAOD(kTRUE),
55     fNeedsHeaderReplication(kFALSE),
56     fNeedsTracksBranchReplication(kFALSE),
57     fNeedsVerticesBranchReplication(kFALSE),
58     fNeedsV0sBranchReplication(kFALSE),
59     fNeedsTrackletsBranchReplication(kFALSE),
60     fNeedsPMDClustersBranchReplication(kFALSE),
61     fNeedsJetsBranchReplication(kFALSE),
62     fNeedsFMDClustersBranchReplication(kFALSE),
63     fNeedsCaloClustersBranchReplication(kFALSE),
64     fNeedsMCParticlesBranchReplication(kFALSE),
65     fAODIsReplicated(kFALSE),
66     fAODEvent(NULL),
67     fMCEventH(NULL),
68     fTreeA(NULL),
69     fFileA(NULL),
70     fFileName(""),
71     fExtensions(NULL)
72 {
73   // default constructor
74 }
75
76 //______________________________________________________________________________
77 AliAODHandler::AliAODHandler(const char* name, const char* title):
78     AliVEventHandler(name, title),
79     fIsStandard(kTRUE),
80     fFillAOD(kTRUE),
81     fNeedsHeaderReplication(kFALSE),
82     fNeedsTracksBranchReplication(kFALSE),
83     fNeedsVerticesBranchReplication(kFALSE),
84     fNeedsV0sBranchReplication(kFALSE),
85     fNeedsTrackletsBranchReplication(kFALSE),
86     fNeedsPMDClustersBranchReplication(kFALSE),
87     fNeedsJetsBranchReplication(kFALSE),
88     fNeedsFMDClustersBranchReplication(kFALSE),
89     fNeedsCaloClustersBranchReplication(kFALSE),
90     fNeedsMCParticlesBranchReplication(kFALSE),
91     fAODIsReplicated(kFALSE),
92     fAODEvent(NULL),
93     fMCEventH(NULL),
94     fTreeA(NULL),
95     fFileA(NULL),
96     fFileName(""),
97     fExtensions(NULL)
98 {
99 }
100
101 //______________________________________________________________________________
102 AliAODHandler::~AliAODHandler() 
103 {
104  // Destructor.
105   delete fAODEvent;
106   if(fFileA){
107     // is already handled in TerminateIO
108     fFileA->Close();
109     delete fFileA;
110   }
111   delete fTreeA;
112   if (fExtensions) delete fExtensions;
113 }
114
115 //______________________________________________________________________________
116 Bool_t AliAODHandler::Init(Option_t* opt)
117 {
118   // Initialize IO
119   //
120   // Create the AODevent object
121   if(!fAODEvent){
122     fAODEvent = new AliAODEvent();
123     if (fIsStandard) fAODEvent->CreateStdContent();
124   }
125   //
126   // File opening according to execution mode
127   TString option(opt);
128   option.ToLower();
129   TDirectory *owd = gDirectory;
130   if (option.Contains("proof")) {
131     // proof
132     // Merging via files. Need to access analysis manager via interpreter.
133     gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(\"%s\", \"RECREATE\");", fFileName.Data()));
134     gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer()->SetFile((TFile*)0x%lx);", gFile));
135     fFileA = gFile;
136   } else {
137     // local and grid
138     fFileA = new TFile(fFileName.Data(), "RECREATE");
139   }
140   CreateTree(1);
141   owd->cd();
142   if (fExtensions) {
143      TIter next(fExtensions);
144      AliAODExtension *ext;
145      while ((ext=(AliAODExtension*)next())) ext->Init(option);
146   }   
147   return kTRUE;
148 }
149
150 //______________________________________________________________________________
151 void AliAODHandler::StoreMCParticles(){
152
153   // 
154   // Remap the labels from ESD stack and store
155   // the AODMCParticles, makes only sense if we have
156   // the mcparticles branch
157   // has to be done here since we cannot know in advance 
158   // which particles are needed (e.g. by the tracks etc.)
159   //
160   // Particles have been selected by AliMCEventhanlder->SelectParticle()
161   // To use the MCEventhandler here we need to set it from the outside
162   // can vanish when Handler go to the ANALYSISalice library
163   //
164   // The Branch booking for mcParticles and mcHeader has to happen 
165   // in an external task for now since the AODHandler does not have access
166   // the AnalysisManager. For the same reason the pointer t o the MCEventH
167   // has to passed to the AOD Handler by this task 
168   // (doing this in the steering macro would not work on PROOF)
169
170   TClonesArray *mcarray = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); 
171   if(!mcarray)return;
172   mcarray->Delete();
173
174   AliAODMCHeader *mcHeader = (AliAODMCHeader*)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName()); 
175   if(!mcHeader)return;
176
177   mcHeader->Reset();
178
179   // Get the MC Infos.. Handler needs to be set before 
180   // while adding the branch
181   // This needs to be done, not to depend on the AnalysisManager
182
183   if(!fMCEventH)return;
184   if(!fMCEventH->MCEvent())return;
185   AliStack *pStack = fMCEventH->MCEvent()->Stack();
186   if(!pStack)return;
187
188   fMCEventH->CreateLabelMap();
189
190   //
191   // Get the Event Header 
192   // 
193
194   AliHeader* header = fMCEventH->MCEvent()->Header();
195    // get the MC vertex
196   AliGenEventHeader* genHeader = 0;
197   if (header) genHeader = header->GenEventHeader();
198   if (genHeader) {
199       TArrayF vtxMC(3);
200       genHeader->PrimaryVertex(vtxMC);
201       mcHeader->SetVertex(vtxMC[0],vtxMC[1],vtxMC[2]);
202
203       // we search the MCEventHeaders first 
204       // Two cases, cocktail or not...
205       AliGenCocktailEventHeader* genCocktailHeader = dynamic_cast<AliGenCocktailEventHeader*>(genHeader);
206       if(genCocktailHeader){
207           // we have a coktail header
208           mcHeader->AddGeneratorName(genHeader->GetName());
209           // Loop from the back so that the first one sets the process type
210           TList* headerList = genCocktailHeader->GetHeaders();
211           for(int i = headerList->GetEntries()-1;i>=0;--i){
212               AliGenEventHeader *headerEntry = dynamic_cast<AliGenEventHeader*>(headerList->At(i));
213               SetMCHeaderInfo(mcHeader,headerEntry);
214           }
215       }
216       else{
217           // No Cocktail just take the first one
218           SetMCHeaderInfo(mcHeader,genHeader);
219       }
220   }
221   
222
223
224
225
226   // Store the AliAODParticlesMC
227   AliMCEvent* mcEvent = fMCEventH->MCEvent();
228   
229   Int_t np    = mcEvent->GetNumberOfTracks();
230   Int_t nprim = mcEvent->GetNumberOfPrimaries();
231
232
233   Int_t j = 0;
234   TClonesArray& l = *mcarray;
235
236   for(int i = 0; i < np; ++i){
237       if(fMCEventH->IsParticleSelected(i)){
238           Int_t flag = 0;
239           AliMCParticle* mcpart =  (AliMCParticle*) mcEvent->GetTrack(i);
240           if(i<nprim)flag |= AliAODMCParticle::kPrimary;
241           
242           if(mcEvent->IsPhysicalPrimary(i))flag |= AliAODMCParticle::kPhysicalPrim;
243           
244           if(fMCEventH->GetNewLabel(i)!=j){
245               AliError(Form("MISMATCH New label %d j: %d",fMCEventH->GetNewLabel(i),j));
246           }
247
248           AliAODMCParticle mcpart_tmp(mcpart,i,flag);
249           
250           // 
251           Int_t d0 =  mcpart_tmp.GetDaughter(0);
252           Int_t d1 =  mcpart_tmp.GetDaughter(1);
253           Int_t m =   mcpart_tmp.GetMother();
254           
255           // other than for the track labels, negative values mean
256           // no daughter/mother so preserve it
257           
258           if(d0<0 && d1<0){
259               // no first daughter -> no second daughter
260               // nothing to be done
261               // second condition not needed just for sanity check at the end
262               mcpart_tmp.SetDaughter(0,d0);
263               mcpart_tmp.SetDaughter(1,d1);
264           } else if(d1 < 0 && d0 >= 0) {
265               // Only one daughter
266               // second condition not needed just for sanity check at the end
267               if(fMCEventH->IsParticleSelected(d0)){
268                   mcpart_tmp.SetDaughter(0,fMCEventH->GetNewLabel(d0));
269               } else {
270                   mcpart_tmp.SetDaughter(0,-1);
271               }
272               mcpart_tmp.SetDaughter(1,d1);
273           }
274           else if (d0 > 0 && d1 > 0 ){
275               // we have two or more daughters loop on the stack to see if they are
276               // selected
277               Int_t d0_tmp = -1;
278               Int_t d1_tmp = -1;
279               for(int id = d0; id<=d1;++id){
280                   if(fMCEventH->IsParticleSelected(id)){
281                       if(d0_tmp==-1){
282                           // first time
283                           d0_tmp = fMCEventH->GetNewLabel(id);
284                           d1_tmp = d0_tmp; // this is to have the same schema as on the stack i.e. with one daugther d0 and d1 are the same 
285                       }
286                       else d1_tmp = fMCEventH->GetNewLabel(id);
287                   }
288               }
289               mcpart_tmp.SetDaughter(0,d0_tmp);
290               mcpart_tmp.SetDaughter(1,d1_tmp);
291           } else {
292               AliError(Form("Unxpected indices %d %d",d0,d1));
293           }
294           
295           if(m<0){
296               mcpart_tmp.SetMother(m);
297           } else {
298               if(fMCEventH->IsParticleSelected(m))mcpart_tmp.SetMother(fMCEventH->GetNewLabel(m));
299               else AliError(Form("PROBLEM Mother not selected %d \n", m));
300           }
301           
302           new (l[j++]) AliAODMCParticle(mcpart_tmp);
303           
304       }
305   }
306   AliInfo(Form("AliAODHandler::StoreMCParticles: Selected %d (Primaries %d / total %d) after validation \n",
307                j,nprim,np));
308   
309   // Set the labels in the AOD output...
310   // Remapping
311
312   // AODTracks
313   TClonesArray* tracks = fAODEvent->GetTracks();
314   if(tracks){
315     for(int it = 0; it < fAODEvent->GetNTracks();++it){
316       AliAODTrack *track = fAODEvent->GetTrack(it);
317       
318       Int_t sign = 1;
319       Int_t label = track->GetLabel();
320       if(label<0){ // preserve the sign for later usage
321         label *= -1;
322         sign  = -1;
323       }
324
325       if (label >= AliMCEvent::BgLabelOffset()) label =  mcEvent->BgLabelToIndex(label);
326       if(label > np || track->GetLabel() == 0){
327         AliWarning(Form("Wrong ESD track label %5d (%5d)",track->GetLabel(), label));
328       }
329       if(fMCEventH->GetNewLabel(label) == 0){
330         AliWarning(Form("New label not found for %5d (%5d)",track->GetLabel(), label));
331       }
332       track->SetLabel(sign*fMCEventH->GetNewLabel(label));
333     }
334   }
335   
336   // AOD calo cluster
337   TClonesArray *clusters = fAODEvent->GetCaloClusters();
338   if(clusters){
339     for (Int_t iClust = 0;iClust < fAODEvent->GetNCaloClusters(); ++iClust) {
340       AliAODCaloCluster * cluster = fAODEvent->GetCaloCluster(iClust);
341       UInt_t nLabel    = cluster->GetNLabel();
342       // Ugly but do not want to fragment memory by creating 
343       // new Int_t (nLabel)
344       Int_t* labels    = const_cast<Int_t*>(cluster->GetLabels());
345       if (labels){
346         for(UInt_t i = 0;i < nLabel;++i){
347           labels[i] = fMCEventH->GetNewLabel(cluster->GetLabel(i));
348         }
349       }
350       //      cluster->SetLabels(labels,nLabel);
351     }// iClust
352   }// clusters
353
354   // AOD tracklets
355   AliAODTracklets *tracklets = fAODEvent->GetTracklets();
356   if(tracklets){
357     for(int it = 0;it < tracklets->GetNumberOfTracklets();++it){
358       int label0 = tracklets->GetLabel(it,0);
359       int label1 = tracklets->GetLabel(it,1);
360       if(label0>=0)label0 = fMCEventH->GetNewLabel(label0);      
361       if(label1>=0)label1 = fMCEventH->GetNewLabel(label1);
362       tracklets->SetLabel(it,0,label0);
363       tracklets->SetLabel(it,1,label1);
364     }
365   }
366
367 }
368
369 //______________________________________________________________________________
370 Bool_t AliAODHandler::FinishEvent()
371 {
372   // Fill data structures
373   if(fFillAOD){
374     fAODEvent->MakeEntriesReferencable();
375     // StoreMCParticles();
376     FillTree();
377     if (fExtensions) {
378       TIter next(fExtensions);
379       AliAODExtension *ext;
380       while ((ext=(AliAODExtension*)next())) {
381         ext->GetAOD()->MakeEntriesReferencable();
382         ext->GetTree()->Fill();
383       }  
384     }       
385   }
386
387   if (fIsStandard) fAODEvent->ResetStd();
388   // Reset AOD replication flag
389   fAODIsReplicated = kFALSE;
390   return kTRUE;
391 }
392
393 //______________________________________________________________________________
394 Bool_t AliAODHandler::Terminate()
395 {
396   // Terminate 
397   AddAODtoTreeUserInfo();
398   if (fExtensions) {
399     TIter next(fExtensions);
400     AliAODExtension *ext;
401     while ((ext=(AliAODExtension*)next())) ext->GetTree()->GetUserInfo()->Add(ext->GetAOD());
402   }  
403   return kTRUE;
404 }
405
406 //______________________________________________________________________________
407 Bool_t AliAODHandler::TerminateIO()
408 {
409   // Terminate IO
410   if (fFileA) {
411     fFileA->Close();
412     delete fFileA;
413     fFileA = 0;
414   }
415   if (fExtensions) {
416     TIter next(fExtensions);
417     AliAODExtension *ext;
418     while ((ext=(AliAODExtension*)next())) ext->TerminateIO();
419   }  
420   return kTRUE;
421 }
422
423 //______________________________________________________________________________
424 void AliAODHandler::CreateTree(Int_t flag)
425 {
426     // Creates the AOD Tree
427     fTreeA = new TTree("aodTree", "AliAOD tree");
428     fTreeA->Branch(fAODEvent->GetList());
429     if (flag == 0) fTreeA->SetDirectory(0);
430 }
431
432 //______________________________________________________________________________
433 void AliAODHandler::FillTree()
434 {
435     // Fill the AOD Tree
436   fTreeA->Fill();
437 }
438
439 //______________________________________________________________________________
440 void AliAODHandler::AddAODtoTreeUserInfo()
441 {
442   // Add aod event to tree user info
443   fTreeA->GetUserInfo()->Add(fAODEvent);
444 }
445
446 //______________________________________________________________________________
447 void AliAODHandler::AddBranch(const char* cname, void* addobj, const char* filename)
448 {
449     // Add a new branch to the aod. Added optional filename parameter if the
450     // branch should be written to a separate file.
451     if (strlen(filename)) {
452        AliAODExtension *ext = AddExtension(filename);
453        ext->AddBranch(cname, addobj);
454        return;
455     }
456     TDirectory *owd = gDirectory;
457     if (fFileA) {
458       fFileA->cd();
459     }
460     char** apointer = (char**) addobj;
461     TObject* obj = (TObject*) *apointer;
462
463     fAODEvent->AddObject(obj);
464  
465     const Int_t kSplitlevel = 99; // default value in TTree::Branch()
466     const Int_t kBufsize = 32000; // default value in TTree::Branch()
467
468     if (!fTreeA->FindBranch(obj->GetName())) {
469       // Do the same as if we book via 
470       // TTree::Branch(TCollection*)
471       
472       fTreeA->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
473                      kBufsize, kSplitlevel - 1);
474       //    fTreeA->Branch(obj->GetName(), cname, addobj);
475     }
476     owd->cd();
477 }
478
479 //______________________________________________________________________________
480 AliAODExtension *AliAODHandler::AddExtension(const char *filename, const char *title)
481 {
482 // Add an AOD extension with some branches in a different file.
483    TString fname(filename);
484    if (!fname.EndsWith(".root")) fname += ".root";
485    if (!fExtensions) {
486       fExtensions = new TObjArray();
487       fExtensions->SetOwner();
488    }   
489    AliAODExtension *ext = (AliAODExtension*)fExtensions->FindObject(fname);
490    if (!ext) {
491       ext = new AliAODExtension(fname, title);
492       fExtensions->Add(ext);
493    }   
494    return ext;
495 }
496    
497 //______________________________________________________________________________
498 void AliAODHandler::SetOutputFileName(const char* fname)
499 {
500 // Set file name.
501    fFileName = fname;
502 }
503
504 //______________________________________________________________________________
505 const char *AliAODHandler::GetOutputFileName()
506 {
507 // Get file name.
508    return fFileName.Data();
509 }
510
511 //______________________________________________________________________________
512 void  AliAODHandler::SetMCHeaderInfo(AliAODMCHeader *mcHeader,AliGenEventHeader *genHeader){
513
514
515   // Utility function to cover different cases for the AliGenEventHeader
516   // Needed since different ProcessType and ImpactParamter are not 
517   // in the base class...
518   // We don't encode process types for event cocktails yet
519   // could be done e.g. by adding offsets depnding on the generator
520
521   mcHeader->AddGeneratorName(genHeader->GetName());
522   if(!genHeader)return;
523   AliGenPythiaEventHeader *pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(genHeader);
524     if (pythiaGenHeader) {
525       mcHeader->SetEventType(pythiaGenHeader->ProcessType());
526       mcHeader->SetPtHard(pythiaGenHeader->GetPtHard());
527       return;
528     }
529     
530     AliGenDPMjetEventHeader* dpmJetGenHeader = dynamic_cast<AliGenDPMjetEventHeader*>(genHeader);
531
532   if (dpmJetGenHeader){
533     mcHeader->SetEventType(dpmJetGenHeader->ProcessType());
534     return;
535   } 
536
537   AliGenHijingEventHeader* hijingGenHeader = dynamic_cast<AliGenHijingEventHeader*>(genHeader);
538   if(hijingGenHeader){
539     mcHeader->SetImpactParameter(hijingGenHeader->ImpactParameter());
540     return;
541   }
542   
543   AliWarning(Form("MC Eventheader not known: %s",genHeader->GetName()));
544
545 }
546
547 ClassImp(AliAODExtension)
548
549 //-------------------------------------------------------------------------
550 //     Support class for AOD extensions. This is created by the user analysis
551 //     that requires a separate file for some AOD branches. The name of the 
552 //     AliAODExtension object is the file name where the AOD branches will be
553 //     stored.
554 //-------------------------------------------------------------------------
555
556 //______________________________________________________________________________
557 AliAODExtension::~AliAODExtension()
558 {
559 // Destructor.
560   delete fAODEvent;
561   if(fFileE){
562     // is already handled in TerminateIO
563     fFileE->Close();
564     delete fFileE;
565   }
566   delete fTreeE;
567 }
568
569 //______________________________________________________________________________
570 void AliAODExtension::AddBranch(const char* cname, void* addobj)
571 {
572     // Add a new branch to the aod 
573     if (!fAODEvent) {
574        char type[20];
575        gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)0x%lx, \"%%s\", s_tmp.Data());", type));
576        Init(type);
577     }
578     TDirectory *owd = gDirectory;
579     if (fFileE) {
580       fFileE->cd();
581     }
582     char** apointer = (char**) addobj;
583     TObject* obj = (TObject*) *apointer;
584
585     fAODEvent->AddObject(obj);
586  
587     const Int_t kSplitlevel = 99; // default value in TTree::Branch()
588     const Int_t kBufsize = 32000; // default value in TTree::Branch()
589
590     if (!fTreeE->FindBranch(obj->GetName())) {
591       // Do the same as if we book via 
592       // TTree::Branch(TCollection*)
593       
594       fTreeE->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
595                      kBufsize, kSplitlevel - 1);
596       //    fTreeA->Branch(obj->GetName(), cname, addobj);
597     }
598     owd->cd();
599 }
600
601 //______________________________________________________________________________
602 Bool_t AliAODExtension::Init(Option_t *option)
603 {
604 // Initialize IO.
605   if(!fAODEvent) fAODEvent = new AliAODEvent();
606   TDirectory *owd = gDirectory;
607   TString opt(option);
608   opt.ToLower();
609   if (opt.Contains("proof")) {
610     // proof
611     // Merging via files. Need to access analysis manager via interpreter.
612     gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(\"%s\", \"RECREATE\");", fName.Data()));
613     fFileE = gFile;
614   } else {
615     fFileE = new TFile(GetName(), "RECREATE");
616   }  
617   fTreeE = new TTree("aodTree", "AliAOD tree");
618   fTreeE->Branch(fAODEvent->GetList());
619   owd->cd();
620   return kTRUE;
621 }
622
623 //______________________________________________________________________________
624 Bool_t AliAODExtension::TerminateIO()
625 {
626   // Terminate IO
627   if (fFileE) {
628     fFileE->Write();
629     fFileE->Close();
630     delete fFileE;
631     fFileE = 0;
632   }
633   return kTRUE;
634 }