]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliAODHandler.cxx
Patch for the AOD filters (Laurent)
[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 #include "AliCodeTimer.h"
46 #include "AliAODBranchReplicator.h"
47 #include "Riostream.h"
48
49 ClassImp(AliAODHandler)
50
51 //______________________________________________________________________________
52 AliAODHandler::AliAODHandler() :
53     AliVEventHandler(),
54     fIsStandard(kTRUE),
55     fFillAOD(kTRUE),
56     fFillAODRun(kTRUE),
57     fNeedsHeaderReplication(kFALSE),
58     fNeedsTracksBranchReplication(kFALSE),
59     fNeedsVerticesBranchReplication(kFALSE),
60     fNeedsV0sBranchReplication(kFALSE),
61     fNeedsCascadesBranchReplication(kFALSE),
62     fNeedsTrackletsBranchReplication(kFALSE),
63     fNeedsPMDClustersBranchReplication(kFALSE),
64     fNeedsJetsBranchReplication(kFALSE),
65     fNeedsFMDClustersBranchReplication(kFALSE),
66     fNeedsCaloClustersBranchReplication(kFALSE),
67     fNeedsMCParticlesBranchReplication(kFALSE),
68     fNeedsDimuonsBranchReplication(kFALSE),
69     fAODIsReplicated(kFALSE),
70     fAODEvent(NULL),
71     fMCEventH(NULL),
72     fTreeA(NULL),
73     fFileA(NULL),
74     fFileName(""),
75     fExtensions(NULL),
76     fFilters(NULL)
77 {
78   // default constructor
79 }
80
81 //______________________________________________________________________________
82 AliAODHandler::AliAODHandler(const char* name, const char* title):
83     AliVEventHandler(name, title),
84     fIsStandard(kTRUE),
85     fFillAOD(kTRUE),
86     fFillAODRun(kTRUE),
87     fNeedsHeaderReplication(kFALSE),
88     fNeedsTracksBranchReplication(kFALSE),
89     fNeedsVerticesBranchReplication(kFALSE),
90     fNeedsV0sBranchReplication(kFALSE),
91     fNeedsCascadesBranchReplication(kFALSE),
92     fNeedsTrackletsBranchReplication(kFALSE),
93     fNeedsPMDClustersBranchReplication(kFALSE),
94     fNeedsJetsBranchReplication(kFALSE),
95     fNeedsFMDClustersBranchReplication(kFALSE),
96     fNeedsCaloClustersBranchReplication(kFALSE),
97     fNeedsMCParticlesBranchReplication(kFALSE),
98     fNeedsDimuonsBranchReplication(kFALSE),
99     fAODIsReplicated(kFALSE),
100     fAODEvent(NULL),
101     fMCEventH(NULL),
102     fTreeA(NULL),
103     fFileA(NULL),
104     fFileName(""),
105     fExtensions(NULL),
106     fFilters(NULL)
107 {
108 // Normal constructor.
109 }
110
111 //______________________________________________________________________________
112 AliAODHandler::~AliAODHandler() 
113 {
114  // Destructor.
115   if (fAODEvent) delete fAODEvent;
116   if(fFileA){
117     // is already handled in TerminateIO
118     fFileA->Close();
119     delete fFileA;
120     fTreeA = 0;
121   }
122   if (fTreeA) delete fTreeA;
123   if (fExtensions) {fExtensions->Delete(); delete fExtensions;}
124   if (fFilters)    {fFilters->Delete();    delete fFilters;}
125 }
126
127 //______________________________________________________________________________
128 Bool_t AliAODHandler::Init(Option_t* opt)
129 {
130   // Initialize IO
131   //
132   // Create the AODevent object
133     
134   Bool_t createStdAOD = fIsStandard || fFillAOD;
135   if(!fAODEvent && createStdAOD){
136     fAODEvent = new AliAODEvent();
137     if (fIsStandard) 
138       fAODEvent->CreateStdContent();
139   }
140   //
141   // File opening according to execution mode
142   TString option(opt);
143   option.ToLower();
144   if (createStdAOD) {
145     TDirectory *owd = gDirectory;
146     if (option.Contains("proof")) {
147       // proof
148       // Merging via files. Need to access analysis manager via interpreter.
149       gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
150       gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\");"));
151       fFileA = gFile;
152     } else {
153       // local and grid
154       fFileA = new TFile(fFileName.Data(), "RECREATE");
155     }
156     CreateTree(1);
157     owd->cd();
158   }  
159   if (fExtensions) {
160      TIter next(fExtensions);
161      AliAODExtension *ext;
162      while ((ext=(AliAODExtension*)next())) ext->Init(option);
163   }   
164   if (fFilters) {
165      TIter nextf(fFilters);
166      AliAODExtension *filteredAOD;
167      while ((filteredAOD=(AliAODExtension*)nextf())) {
168         filteredAOD->SetEvent(fAODEvent);
169         filteredAOD->Init(option);
170      }   
171   }   
172   return kTRUE;
173 }
174
175 //______________________________________________________________________________
176 void AliAODHandler::Print(Option_t* opt) const
177 {
178   // Print info about this object
179
180   cout << opt << Form("IsStandard %d filename=%s",fIsStandard,fFileName.Data()) << endl;
181   
182   if ( fExtensions ) 
183   {
184     cout << opt << fExtensions->GetEntries() << " extensions :" << endl;
185     PrintExtensions(*fExtensions);    
186   }
187   if ( fFilters ) 
188   {
189     cout << opt << fFilters->GetEntries() << " filters :" << endl;
190     PrintExtensions(*fFilters);      
191   }
192 }
193
194 //______________________________________________________________________________
195 void AliAODHandler::PrintExtensions(const TObjArray& array) const
196 {
197   // Show the list of aod extensions
198   TIter next(&array);
199   AliAODExtension* ext(0x0);
200   while ( ( ext = static_cast<AliAODExtension*>(next()) ) )
201   {
202     ext->Print("   ");
203   }
204 }
205
206 //______________________________________________________________________________
207 void AliAODHandler::StoreMCParticles(){
208
209   // 
210   // Remap the labels from ESD stack and store
211   // the AODMCParticles, makes only sense if we have
212   // the mcparticles branch
213   // has to be done here since we cannot know in advance 
214   // which particles are needed (e.g. by the tracks etc.)
215   //
216   // Particles have been selected by AliMCEventhanlder->SelectParticle()
217   // To use the MCEventhandler here we need to set it from the outside
218   // can vanish when Handler go to the ANALYSISalice library
219   //
220   // The Branch booking for mcParticles and mcHeader has to happen 
221   // in an external task for now since the AODHandler does not have access
222   // the AnalysisManager. For the same reason the pointer t o the MCEventH
223   // has to passed to the AOD Handler by this task 
224   // (doing this in the steering macro would not work on PROOF)
225
226   if (!fAODEvent) return;
227   TClonesArray *mcarray = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); 
228   if(!mcarray)return;
229
230   AliAODMCHeader *mcHeader = (AliAODMCHeader*)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName()); 
231   if(!mcHeader)return;
232
233   // Get the MC Infos.. Handler needs to be set before 
234   // while adding the branch
235   // This needs to be done, not to depend on the AnalysisManager
236
237   if(!fMCEventH)return;
238   if(!fMCEventH->MCEvent())return;
239   AliStack *pStack = fMCEventH->MCEvent()->Stack();
240   if(!pStack)return;
241
242   fMCEventH->CreateLabelMap();
243
244   //
245   // Get the Event Header 
246   // 
247
248   AliHeader* header = fMCEventH->MCEvent()->Header();
249    // get the MC vertex
250   AliGenEventHeader* genHeader = 0;
251   if (header) genHeader = header->GenEventHeader();
252   if (genHeader) {
253       TArrayF vtxMC(3);
254       genHeader->PrimaryVertex(vtxMC);
255       mcHeader->SetVertex(vtxMC[0],vtxMC[1],vtxMC[2]);
256
257       // we search the MCEventHeaders first 
258       // Two cases, cocktail or not...
259       AliGenCocktailEventHeader* genCocktailHeader = dynamic_cast<AliGenCocktailEventHeader*>(genHeader);
260       if(genCocktailHeader){
261           // we have a coktail header
262           mcHeader->AddGeneratorName(genHeader->GetName());
263           // Loop from the back so that the first one sets the process type
264           TList* headerList = genCocktailHeader->GetHeaders();
265           for(int i = headerList->GetEntries()-1;i>=0;--i){
266               AliGenEventHeader *headerEntry = dynamic_cast<AliGenEventHeader*>(headerList->At(i));
267               SetMCHeaderInfo(mcHeader,headerEntry);
268           }
269       }
270       else{
271           // No Cocktail just take the first one
272           SetMCHeaderInfo(mcHeader,genHeader);
273       }
274   }
275   
276
277
278
279
280   // Store the AliAODParticlesMC
281   AliMCEvent* mcEvent = fMCEventH->MCEvent();
282   
283   Int_t np    = mcEvent->GetNumberOfTracks();
284   Int_t nprim = mcEvent->GetNumberOfPrimaries();
285
286
287   Int_t j = 0;
288   TClonesArray& l = *mcarray;
289
290   for(int i = 0; i < np; ++i){
291       if(fMCEventH->IsParticleSelected(i)){
292           Int_t flag = 0;
293           AliMCParticle* mcpart =  (AliMCParticle*) mcEvent->GetTrack(i);
294           if(i<nprim)flag |= AliAODMCParticle::kPrimary;
295           
296           if(mcEvent->IsPhysicalPrimary(i))flag |= AliAODMCParticle::kPhysicalPrim;
297           
298           if(fMCEventH->GetNewLabel(i)!=j){
299               AliError(Form("MISMATCH New label %d j: %d",fMCEventH->GetNewLabel(i),j));
300           }
301
302           AliAODMCParticle mcpart_tmp(mcpart,i,flag);
303           
304           mcpart_tmp.SetStatus(mcpart->Particle()->GetStatusCode());
305           // 
306           Int_t d0 =  mcpart_tmp.GetDaughter(0);
307           Int_t d1 =  mcpart_tmp.GetDaughter(1);
308           Int_t m =   mcpart_tmp.GetMother();
309           
310           // other than for the track labels, negative values mean
311           // no daughter/mother so preserve it
312           
313           if(d0<0 && d1<0){
314               // no first daughter -> no second daughter
315               // nothing to be done
316               // second condition not needed just for sanity check at the end
317               mcpart_tmp.SetDaughter(0,d0);
318               mcpart_tmp.SetDaughter(1,d1);
319           } else if(d1 < 0 && d0 >= 0) {
320               // Only one daughter
321               // second condition not needed just for sanity check at the end
322               if(fMCEventH->IsParticleSelected(d0)){
323                   mcpart_tmp.SetDaughter(0,fMCEventH->GetNewLabel(d0));
324               } else {
325                   mcpart_tmp.SetDaughter(0,-1);
326               }
327               mcpart_tmp.SetDaughter(1,d1);
328           }
329           else if (d0 > 0 && d1 > 0 ){
330               // we have two or more daughters loop on the stack to see if they are
331               // selected
332               Int_t d0_tmp = -1;
333               Int_t d1_tmp = -1;
334               for(int id = d0; id<=d1;++id){
335                   if(fMCEventH->IsParticleSelected(id)){
336                       if(d0_tmp==-1){
337                           // first time
338                           d0_tmp = fMCEventH->GetNewLabel(id);
339                           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 
340                       }
341                       else d1_tmp = fMCEventH->GetNewLabel(id);
342                   }
343               }
344               mcpart_tmp.SetDaughter(0,d0_tmp);
345               mcpart_tmp.SetDaughter(1,d1_tmp);
346           } else {
347               AliError(Form("Unxpected indices %d %d",d0,d1));
348           }
349           
350           if(m<0){
351               mcpart_tmp.SetMother(m);
352           } else {
353               if(fMCEventH->IsParticleSelected(m))mcpart_tmp.SetMother(fMCEventH->GetNewLabel(m));
354               else AliError(Form("PROBLEM Mother not selected %d \n", m));
355           }
356
357           new (l[j++]) AliAODMCParticle(mcpart_tmp);
358           
359       }
360   }
361   AliInfo(Form("AliAODHandler::StoreMCParticles: Selected %d (Primaries %d / total %d) after validation \n",
362                j,nprim,np));
363   
364   // Set the labels in the AOD output...
365   // Remapping
366
367   // AODTracks
368   TClonesArray* tracks = fAODEvent->GetTracks();
369   if(tracks){
370     for(int it = 0; it < fAODEvent->GetNTracks();++it){
371       AliAODTrack *track = fAODEvent->GetTrack(it);
372       
373       Int_t sign = 1;
374       Int_t label = track->GetLabel();
375       if(label<0){ // preserve the sign for later usage
376         label *= -1;
377         sign  = -1;
378       }
379
380       if (label >= AliMCEvent::BgLabelOffset()) label =  mcEvent->BgLabelToIndex(label);
381       if(label > np || track->GetLabel() == 0){
382         AliWarning(Form("Wrong ESD track label %5d (%5d)",track->GetLabel(), label));
383       }
384       if(fMCEventH->GetNewLabel(label) == 0){
385         AliWarning(Form("New label not found for %5d (%5d)",track->GetLabel(), label));
386       }
387       track->SetLabel(sign*fMCEventH->GetNewLabel(label));
388     }
389   }
390   
391   // AOD calo cluster
392   TClonesArray *clusters = fAODEvent->GetCaloClusters();
393   if(clusters){
394     for (Int_t iClust = 0;iClust < fAODEvent->GetNumberOfCaloClusters(); ++iClust) {
395       AliAODCaloCluster * cluster = fAODEvent->GetCaloCluster(iClust);
396       UInt_t nLabel    = cluster->GetNLabels();
397       // Ugly but do not want to fragment memory by creating 
398       // new Int_t (nLabel)
399       Int_t* labels    = const_cast<Int_t*>(cluster->GetLabels());
400       if (labels){
401         for(UInt_t i = 0;i < nLabel;++i){
402           labels[i] = fMCEventH->GetNewLabel(cluster->GetLabelAt(i));
403         }
404       }
405       //      cluster->SetLabels(labels,nLabel);
406     }// iClust
407   }// clusters
408
409   // AOD tracklets
410   AliAODTracklets *tracklets = fAODEvent->GetTracklets();
411   if(tracklets){
412     for(int it = 0;it < tracklets->GetNumberOfTracklets();++it){
413       int label0 = tracklets->GetLabel(it,0);
414       int label1 = tracklets->GetLabel(it,1);
415       if(label0>=0)label0 = fMCEventH->GetNewLabel(label0);      
416       if(label1>=0)label1 = fMCEventH->GetNewLabel(label1);
417       tracklets->SetLabel(it,0,label0);
418       tracklets->SetLabel(it,1,label1);
419     }
420   }
421
422 }
423
424 //______________________________________________________________________________
425 Bool_t AliAODHandler::FinishEvent()
426 {
427   // Fill data structures
428   if(fFillAOD && fFillAODRun && fAODEvent){
429       fAODEvent->MakeEntriesReferencable();
430       fTreeA->BranchRef();
431       FillTree();
432   }
433
434   if (fFillAOD && fFillAODRun) {      
435       if (fExtensions) {
436           TIter next(fExtensions);
437           AliAODExtension *ext;
438           while ((ext=(AliAODExtension*)next())) ext->FinishEvent();
439       }
440       if (fFilters) {   
441           TIter nextf(fFilters);
442           AliAODExtension *ext;
443           while ((ext=(AliAODExtension*)nextf())) {
444               ext->FinishEvent();
445           }  
446       }       
447   }  
448   if (fIsStandard) fAODEvent->ResetStd();
449   if (fAODEvent) {
450     TClonesArray *mcarray = (TClonesArray*)fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()); 
451     if(mcarray) mcarray->Delete();
452     
453     AliAODMCHeader *mcHeader = (AliAODMCHeader*)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName()); 
454     if(mcHeader) mcHeader->Reset();
455   }
456   // Reset AOD replication flag
457   fAODIsReplicated = kFALSE;
458   return kTRUE;
459 }
460
461 //______________________________________________________________________________
462 Bool_t AliAODHandler::Terminate()
463 {
464   // Terminate 
465   AddAODtoTreeUserInfo();
466   if (fExtensions) {
467     TIter next(fExtensions);
468     AliAODExtension *ext;
469     while ((ext=(AliAODExtension*)next())) ext->GetTree()->GetUserInfo()->Add(ext->GetAOD());
470   }  
471   return kTRUE;
472 }
473
474 //______________________________________________________________________________
475 Bool_t AliAODHandler::TerminateIO()
476 {
477   // Terminate IO
478   if (fFileA) {
479     fFileA->Write();
480     fFileA->Close();
481     delete fFileA;
482     fFileA = 0;
483     // When closing the file, the tree is also deleted.
484     fTreeA = 0;
485   }
486   if (fExtensions) {
487     TIter next(fExtensions);
488     AliAODExtension *ext;
489     while ((ext=(AliAODExtension*)next())) ext->TerminateIO();
490   }  
491   if (fFilters) {
492     TIter nextf(fFilters);
493     AliAODExtension *ext;
494     while ((ext=(AliAODExtension*)nextf())) ext->TerminateIO();
495   }  
496   return kTRUE;
497 }
498
499 //______________________________________________________________________________
500 void AliAODHandler::CreateTree(Int_t flag)
501 {
502     // Creates the AOD Tree
503     fTreeA = new TTree("aodTree", "AliAOD tree");
504     fTreeA->Branch(fAODEvent->GetList());
505     if (flag == 0) fTreeA->SetDirectory(0);
506 }
507
508 //______________________________________________________________________________
509 void AliAODHandler::FillTree()
510 {
511  
512     // Fill the AOD Tree
513     fTreeA->Fill();
514 }
515
516 //______________________________________________________________________________
517 void AliAODHandler::AddAODtoTreeUserInfo()
518 {
519   // Add aod event to tree user info
520   if (fTreeA) fTreeA->GetUserInfo()->Add(fAODEvent);
521   // Now the tree owns our fAODEvent...
522   fAODEvent = 0;
523 }
524
525 //______________________________________________________________________________
526 void AliAODHandler::AddBranch(const char* cname, void* addobj, const char* filename)
527 {
528     // Add a new branch to the aod. Added optional filename parameter if the
529     // branch should be written to a separate file.
530     if (strlen(filename)) {
531        AliAODExtension *ext = AddExtension(filename);
532        ext->AddBranch(cname, addobj);
533        return;
534     } else {
535        // Add branch to all filters
536       if (fFilters) {
537          TIter next(fFilters);
538          AliAODExtension *ext;
539          while ((ext=(AliAODExtension*)next())) ext->AddBranch(cname, addobj);
540       }
541     }
542     TDirectory *owd = gDirectory;
543     if (fFileA) {
544       fFileA->cd();
545     }
546     char** apointer = (char**) addobj;
547     TObject* obj = (TObject*) *apointer;
548
549     fAODEvent->AddObject(obj);
550  
551     const Int_t kSplitlevel = 99; // default value in TTree::Branch()
552     const Int_t kBufsize = 32000; // default value in TTree::Branch()
553
554     if (!fTreeA->FindBranch(obj->GetName())) {
555       // Do the same as if we book via 
556       // TTree::Branch(TCollection*)
557       
558       fTreeA->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
559                      kBufsize, kSplitlevel - 1);
560     }
561     owd->cd();
562 }
563
564 //______________________________________________________________________________
565 AliAODExtension *AliAODHandler::AddExtension(const char *filename, const char *title)
566 {
567 // Add an AOD extension with some branches in a different file.
568   
569    TString fname(filename);
570    if (!fname.EndsWith(".root")) fname += ".root";
571    if (!fExtensions) {
572       fExtensions = new TObjArray();
573       fExtensions->SetOwner();
574    }   
575    AliAODExtension *ext = (AliAODExtension*)fExtensions->FindObject(fname);
576    if (!ext) {
577       ext = new AliAODExtension(fname, title);
578       fExtensions->Add(ext);
579    }   
580    return ext;
581 }
582
583 //______________________________________________________________________________
584 AliAODExtension *AliAODHandler::GetExtension(const char *filename) const
585 {
586 // Getter for AOD extensions via file name.
587    if (!fExtensions) return NULL;
588    return (AliAODExtension*)fExtensions->FindObject(filename);
589 }   
590
591 //______________________________________________________________________________
592 AliAODExtension *AliAODHandler::AddFilteredAOD(const char *filename, const char *filtername)
593 {
594 // Add an AOD extension that can write only AOD events that pass a user filter.
595    if (!fFilters) {
596       fFilters = new TObjArray();
597       fFilters->SetOwner();
598    } 
599    AliAODExtension *filter = (AliAODExtension*)fFilters->FindObject(filename);
600    if (!filter) {
601       filter = new AliAODExtension(filename, filtername, kTRUE);
602       fFilters->Add(filter);
603    }
604    return filter;
605 }      
606
607 //______________________________________________________________________________
608 AliAODExtension *AliAODHandler::GetFilteredAOD(const char *filename) const
609 {
610 // Getter for AOD filters via file name.
611    if (!fFilters) return NULL;
612    return (AliAODExtension*)fFilters->FindObject(filename);
613 }   
614    
615 //______________________________________________________________________________
616 void AliAODHandler::SetOutputFileName(const char* fname)
617 {
618 // Set file name.
619    fFileName = fname;
620 }
621
622 //______________________________________________________________________________
623 const char *AliAODHandler::GetOutputFileName()
624 {
625 // Get file name.
626    return fFileName.Data();
627 }
628
629 //______________________________________________________________________________
630 const char *AliAODHandler::GetExtraOutputs() const
631 {
632 // Get extra outputs as a string separated by commas.
633    static TString eoutputs;
634    eoutputs = "";
635    TObject *obj;
636    if (fExtensions) {
637       TIter next1(fExtensions);
638       while ((obj=next1())) {
639          if (!eoutputs.IsNull()) eoutputs += ",";
640          eoutputs += obj->GetName();
641       }
642    }
643    if (fFilters) {
644       TIter next2(fFilters);
645       while ((obj=next2())) {
646          if (!eoutputs.IsNull()) eoutputs += ",";
647          eoutputs += obj->GetName();
648       }
649    }
650    return eoutputs.Data();
651 }
652
653 //______________________________________________________________________________
654 void  AliAODHandler::SetMCHeaderInfo(AliAODMCHeader *mcHeader,AliGenEventHeader *genHeader){
655
656
657   // Utility function to cover different cases for the AliGenEventHeader
658   // Needed since different ProcessType and ImpactParamter are not 
659   // in the base class...
660   // We don't encode process types for event cocktails yet
661   // could be done e.g. by adding offsets depnding on the generator
662
663   mcHeader->AddGeneratorName(genHeader->GetName());
664   if(!genHeader)return;
665   AliGenPythiaEventHeader *pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(genHeader);
666     if (pythiaGenHeader) {
667       mcHeader->SetEventType(pythiaGenHeader->ProcessType());
668       mcHeader->SetPtHard(pythiaGenHeader->GetPtHard());
669       return;
670     }
671     
672     AliGenDPMjetEventHeader* dpmJetGenHeader = dynamic_cast<AliGenDPMjetEventHeader*>(genHeader);
673
674   if (dpmJetGenHeader){
675     mcHeader->SetEventType(dpmJetGenHeader->ProcessType());
676     return;
677   } 
678
679   AliGenHijingEventHeader* hijingGenHeader = dynamic_cast<AliGenHijingEventHeader*>(genHeader);
680   if(hijingGenHeader){
681     mcHeader->SetImpactParameter(hijingGenHeader->ImpactParameter());
682     return;
683   }
684   
685   AliWarning(Form("MC Eventheader not known: %s",genHeader->GetName()));
686
687 }
688
689 ClassImp(AliAODExtension)
690
691 //-------------------------------------------------------------------------
692 //     Support class for AOD extensions. This is created by the user analysis
693 //     that requires a separate file for some AOD branches. The name of the 
694 //     AliAODExtension object is the file name where the AOD branches will be
695 //     stored.
696 //-------------------------------------------------------------------------
697
698 //______________________________________________________________________________
699 AliAODExtension::AliAODExtension() : TNamed(), 
700 fAODEvent(0), fTreeE(0), fFileE(0), fNtotal(0), fNpassed(0), 
701 fSelected(kFALSE), fRepFiMap(0x0), fRepFiList(0x0), fEnableReferences(kTRUE), fObjectList(0x0)
702 {
703   // default ctor
704 }
705
706 //______________________________________________________________________________
707 AliAODExtension::AliAODExtension(const char* name, const char* title, Bool_t isfilter)
708                 :TNamed(name,title), 
709                  fAODEvent(0), 
710                  fTreeE(0), 
711                  fFileE(0), 
712                  fNtotal(0), 
713                  fNpassed(0),
714                  fSelected(kFALSE),
715 fRepFiMap(0x0),
716 fRepFiList(0x0),
717 fEnableReferences(kTRUE),
718 fObjectList(0x0)
719 {
720 // Constructor.
721   if (isfilter) {
722     TObject::SetBit(kFilteredAOD);
723     printf("####### Added AOD filter %s\n", name);
724   } else printf("####### Added AOD extension %s\n", name);
725 }   
726
727 //______________________________________________________________________________
728 AliAODExtension::~AliAODExtension()
729 {
730 // Destructor.
731   if(fFileE){
732     // is already handled in TerminateIO
733     fFileE->Close();
734     delete fFileE;
735     fTreeE = 0;
736     fAODEvent = 0;
737   }
738   if (fTreeE) delete fTreeE;
739   if (fRepFiMap) fRepFiMap->DeleteAll();
740   delete fRepFiMap; // the map is owner
741   delete fRepFiList; // the list is not
742   delete fObjectList; // not owner
743 }
744
745 //______________________________________________________________________________
746 void AliAODExtension::AddBranch(const char* cname, void* addobj)
747 {
748     // Add a new branch to the aod 
749 //    if (IsFilteredAOD()) {
750 //       Error("AddBranch", "Not allowed to add branched to filtered AOD's.");
751 //       return;
752 //    }   
753   AliCodeTimerAuto(GetName(),0);
754
755     if (!fAODEvent) {
756        char type[20];
757        gROOT->ProcessLine(Form("TString s_tmp; AliAnalysisManager::GetAnalysisManager()->GetAnalysisTypeString(s_tmp); sprintf((char*)%p, \"%%s\", s_tmp.Data());", type));
758        Init(type);
759     }
760     TDirectory *owd = gDirectory;
761     if (fFileE) {
762       fFileE->cd();
763     }
764     char** apointer = (char**) addobj;
765     TObject* obj = (TObject*) *apointer;
766
767     fAODEvent->AddObject(obj);
768  
769     const Int_t kSplitlevel = 99; // default value in TTree::Branch()
770     const Int_t kBufsize = 32000; // default value in TTree::Branch()
771
772     if (!fTreeE->FindBranch(obj->GetName())) {
773       // Do the same as if we book via 
774       // TTree::Branch(TCollection*)
775       fTreeE->Bronch(obj->GetName(), cname, fAODEvent->GetList()->GetObjectRef(obj),
776                      kBufsize, kSplitlevel - 1);
777     }
778     owd->cd();
779 }
780
781 //______________________________________________________________________________
782 Bool_t AliAODExtension::FinishEvent()
783 {
784 // Fill current event.
785   fNtotal++;
786   if (!IsFilteredAOD()) {
787     fAODEvent->MakeEntriesReferencable();
788     fTreeE->Fill();
789     return kTRUE;
790   }  
791   // Filtered AOD. Fill only if event is selected.
792   if (!fSelected) return kTRUE;
793
794   TIter next(fRepFiList);
795   
796   AliAODBranchReplicator* repfi;
797
798   while ( ( repfi = static_cast<AliAODBranchReplicator*>(next()) ) )
799   {
800     repfi->ReplicateAndFilter(*fAODEvent);
801   }
802   fNpassed++;
803   fTreeE->Fill();
804   fSelected = kFALSE; // so that next event will not be selected unless demanded
805   return kTRUE;
806 }  
807
808 //______________________________________________________________________________
809 Bool_t AliAODExtension::Init(Option_t *option)
810 {
811 // Initialize IO.
812   AliCodeTimerAuto(GetName(),0);
813   
814   if(!fAODEvent) 
815   {
816     fAODEvent = new AliAODEvent();    
817   }
818   
819   TDirectory *owd = gDirectory;
820   TString opt(option);
821   opt.ToLower();
822   if (opt.Contains("proof")) {
823     // proof
824     // Merging via files. Need to access analysis manager via interpreter.
825     gROOT->ProcessLine(Form("AliAnalysisDataContainer *c_common_out = AliAnalysisManager::GetAnalysisManager()->GetCommonOutputContainer();"));
826     gROOT->ProcessLine(Form("AliAnalysisManager::GetAnalysisManager()->OpenProofFile(c_common_out, \"RECREATE\", \"%s\");", fName.Data()));
827     fFileE = gFile;
828   } else {
829     fFileE = new TFile(GetName(), "RECREATE");
830   }  
831   fTreeE = new TTree("aodTree", "AliAOD tree");
832   
833   delete fObjectList;
834   fObjectList = new TList;
835   fObjectList->SetOwner(kFALSE); // be explicit we're not the owner...
836   TIter next(fAODEvent->GetList());
837   TObject* o;
838   
839   while ( ( o = next() ) )
840   {
841     if ( fRepFiMap )
842     {
843       TObject* specified = fRepFiMap->FindObject(o->GetName());
844       if (specified)
845       {
846         AliAODBranchReplicator* repfi = dynamic_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(o->GetName()));
847         if ( repfi ) 
848         {        
849           TList* replicatedList = repfi->GetList();
850           if (replicatedList)
851           {
852             AliAODEvent::AssignIDtoCollection(replicatedList);
853             TIter nextRep(replicatedList);
854             TObject* objRep;
855             while ( ( objRep = nextRep() ) )
856             {
857               if (!fObjectList->FindObject(objRep))
858               {
859                 fObjectList->Add(objRep);
860               }
861             }
862           }
863           else
864           {
865             AliError(Form("replicatedList from %s is null !",repfi->GetName()));
866           }
867         }
868       }
869       else
870       {
871         fObjectList->Add(o);
872       }
873     } 
874     else
875     {
876       // no replicator / filter map created, so works as before, i.e. 
877       // assume we copy everything.
878       fObjectList->Add(o);
879     }
880   }
881
882   next.Reset();
883   
884   while ( ( o = next() ) )
885   {
886     TObject* out = fObjectList->FindObject(o->GetName());
887     AliInfo(Form("OBJECT IN %20s %p -> OUT %p %s",o->GetName(),o,out,((out!=o && out) ? "REPLICATED":"-")));
888   }
889
890   if (fEnableReferences) fTreeE->BranchRef();
891
892   fTreeE->Branch(fObjectList);
893     
894   owd->cd();
895   
896   return kTRUE;
897 }
898
899 //______________________________________________________________________________
900 void AliAODExtension::Print(Option_t* opt) const
901 {
902   // Print info about this extension
903   
904   cout << opt << Form("AliAODExtension - %s - %s",GetName(),GetTitle()) << endl;
905   cout << opt << opt << Form("References are %s enabled",fEnableReferences ? "" : "not") << endl;
906   
907   TIter next(fRepFiMap);
908   TObjString* s;
909   
910   TString skipped;
911   
912   while ( ( s = static_cast<TObjString*>(next()) ) )
913   {
914     AliAODBranchReplicator* br = static_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(s->String().Data()));
915     if ( !br ) 
916     {
917       skipped += s->String();
918       skipped += ' ';
919     }
920   }
921   
922   if ( skipped.Length() )
923   {
924     cout << opt << opt << "Branches that will be skipped altogether : " << skipped.Data() << endl;
925   }
926   
927   next.Reset();
928   
929   while ( ( s = static_cast<TObjString*>(next()) ) )
930   {
931     AliAODBranchReplicator* br = static_cast<AliAODBranchReplicator*>(fRepFiMap->GetValue(s->String().Data()));
932     
933     if (br)
934     {
935       cout << opt << opt << "Branch " << s->String() 
936       << " will be filtered by class " << br->ClassName() << endl;
937     }
938   }
939 }
940
941 //______________________________________________________________________________
942 void AliAODExtension::SetEvent(AliAODEvent *event)
943 {
944 // Connects to an external event
945    if (!IsFilteredAOD()) {
946       Error("SetEvent", "Not allowed to set external event for filtered AOD's");   
947       return;
948    }
949    // Use the copy constructor or assignment operator to synchronize with external event.
950 //   AliAODEvent &other = *event;
951 //   if (!fAODEvent)     fAODEvent = new AliAODEvent(other);
952 //   else if (fSelected) *fAODEvent = other;
953    fAODEvent = event;
954 }
955    
956 //______________________________________________________________________________
957 Bool_t AliAODExtension::TerminateIO()
958 {
959   // Terminate IO
960   if (TObject::TestBit(kFilteredAOD))
961     printf("AOD Filter %s: events processed: %d   passed: %d\n", GetName(), fNtotal, fNpassed);
962   else
963     printf("AOD extension %s: events processed: %d\n", GetName(), fNtotal);
964   if (fFileE) {
965     fFileE->Write();
966     fFileE->Close();
967     delete fFileE;
968     fFileE = 0;
969     fTreeE = 0;
970     fAODEvent = 0;
971   }
972   return kTRUE;
973 }
974
975 //______________________________________________________________________________
976 void AliAODExtension::FilterBranch(const char* branchName, AliAODBranchReplicator* repfi)
977 {
978   // Specify a filter/replicator for a given branch
979   //
980   // If repfi=0x0, this will disable the branch (in the output) completely.
981   //
982   // repfi is adopted by this class, i.e. user should not delete it.
983   //
984   // WARNING : branch name must be exact.
985   //
986   // See also the documentation for AliAODBranchReplicator class.
987   //
988   
989   if (!fRepFiMap)
990   {
991     fRepFiMap = new TMap;
992     fRepFiMap->SetOwnerKeyValue(kTRUE,kTRUE);
993     fRepFiList = new TList;
994     fRepFiList->SetOwner(kFALSE);
995   }
996   
997   fRepFiMap->Add(new TObjString(branchName),repfi);
998   
999   if (repfi && !fRepFiList->FindObject(repfi))
1000   {
1001     // insure we get unique and non-null replicators in this list
1002     fRepFiList->Add(repfi);
1003   }
1004 }