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