]> git.uio.no Git - u/mrichter/AliRoot.git/blob - ANALYSIS/AliAnalysisTask.cxx
6a588faa530ba3f7714ca1b1c4ae83ad7af0114a
[u/mrichter/AliRoot.git] / ANALYSIS / AliAnalysisTask.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17 // Author: Andrei Gheata, 31/05/2006
18
19 //==============================================================================
20 //   AliAnalysysTask - Class representing a basic analysis task. Any
21 // user-defined task should derive from it and implement the Exec() virtual
22 // method.
23 //==============================================================================
24 //
25 // A specific user analysis task have to derive from this class. The list of
26 // specific input and output slots have to be defined in the derived class ctor:
27 //
28 //   UserTask::UserTask(name, title)
29 //   {
30 //      DefineInput(0, TTree::Class());
31 //      DefineInput(1, TH1::Class());
32 //      ...
33 //      DefineOutput(0, TTree::Class());
34 //      DefineOutput(1, MyObject::Class());
35 //      ...
36 //   }
37 //
38 // An existing data contaner (AliAnalysisDataContainer) can be connected to the
39 // input/output slots of an analysis task. Containers should not be defined and
40 // connected by the derived analysis task, but from the level of AliAnalysisManager:
41 //
42 //   AliAnalysisManager::ConnectInput(AliAnalysisTask *task, Int_t islot,
43 //                                   AliAnalysisDataContainer *cont)
44 //   AliAnalysisManager::ConnectOutput(AliAnalysisTask *task, Int_t islot,
45 //                                    AliAnalysisDataContainer *cont)
46 // To connect a slot to a data container, the data types declared by both must
47 // match.
48 //
49 // The method ConnectInputData() has to be overloaded by the derived class in order to
50 // set the branch address or connect to a branch address in case the input
51 // slots are connected to trees.
52 // Example:
53 // MyAnalysisTask::ConnectInputData(Option_t *)
54 // {
55 //  // One should first check if the branch address was taken by some other task
56 //    char ** address = (char **)GetBranchAddress(0, "ESD");
57 //    if (address) {
58 //      fESD = (AliESD*)(*address);
59 //    } else {
60 //      fESD = new AliESD();
61 //      SetBranchAddress(0, "ESD", &fESD);
62 //    }
63 // }
64 // 
65 // The method LocalInit() may be implemented to call locally (on the client)
66 // all initialization methods of the class. It is not mandatory and was created
67 // in order to minimize the complexity and readability of the analysis macro.
68 // DO NOT create in this method the histigrams or task output objects that will
69 // go in the task output containers. Use CreateOutputObjects for that.
70 //
71 // The method CreateOutputObjects() has to be implemented an will contain the
72 // objects that should be created only once per session (e.g. output
73 // histograms)
74 //
75 // void MyAnalysisTask::CreateOutputObjects()
76 //{
77   // create histograms 
78 //  fhPt = new TH1F("fhPt","This is the Pt distribution",15,0.1,3.1);
79 //  fhPt->SetStats(kTRUE);
80 //  fhPt->GetXaxis()->SetTitle("P_{T} [GeV]");
81 //  fhPt->GetYaxis()->SetTitle("#frac{dN}{dP_{T}}");
82 //  fhPt->GetXaxis()->SetTitleColor(1);
83 //  fhPt->SetMarkerStyle(kFullCircle);
84 // }
85 //
86 // The method Terminate() will be called by the framework once at the end of
87 // data processing. Overload this if needed. DO NOT ASSUME that the pointers
88 // to histograms defined in  CreateOutputObjects() are valid, since this is
89 // not true in case of PROOF. Restore the pointer values like:
90 //
91 //void MyAnalysisTask::Terminate(Option_t *) 
92 //{
93 //  fhPt = (TH1F*)GetOutputData(0);
94 // ...
95 //}
96
97 //
98 //==============================================================================
99
100 #include <Riostream.h>
101 #include <TFile.h>
102 #include <TClass.h>
103
104 #include "AliAnalysisTask.h"
105 #include "AliAnalysisDataSlot.h"
106 #include "AliAnalysisDataContainer.h"
107 #include "AliAnalysisManager.h"
108
109 ClassImp(AliAnalysisTask)
110
111 //______________________________________________________________________________
112 AliAnalysisTask::AliAnalysisTask()
113                 :fReady(kFALSE),
114                  fInitialized(kFALSE),
115                  fNinputs(0),
116                  fNoutputs(0),
117                  fOutputReady(NULL),
118                  fPublishedData(NULL),
119                  fInputs(NULL),
120                  fOutputs(NULL)
121 {
122 // Default constructor.
123    TObject::SetBit(kTaskEvtByEvt, kTRUE);
124 }
125
126 //______________________________________________________________________________
127 AliAnalysisTask::AliAnalysisTask(const char *name, const char *title)
128                 :TTask(name,title),
129                  fReady(kFALSE),
130                  fInitialized(kFALSE),
131                  fNinputs(0),
132                  fNoutputs(0),
133                  fOutputReady(NULL),
134                  fPublishedData(NULL),
135                  fInputs(NULL),
136                  fOutputs(NULL)                 
137 {
138 // Constructor.
139    TObject::SetBit(kTaskEvtByEvt, kTRUE);
140    fInputs      = new TObjArray(2);
141    fOutputs     = new TObjArray(2);
142 }
143
144 //______________________________________________________________________________
145 AliAnalysisTask::AliAnalysisTask(const AliAnalysisTask &task)
146                 :TTask(task),
147                  fReady(task.fReady),
148                  fInitialized(task.fInitialized),
149                  fNinputs(task.fNinputs),
150                  fNoutputs(task.fNoutputs),                 
151                  fOutputReady(NULL),
152                  fPublishedData(NULL),
153                  fInputs(NULL),
154                  fOutputs(NULL)                 
155 {
156 // Copy ctor.
157    fInputs      = new TObjArray((fNinputs)?fNinputs:2);
158    fOutputs     = new TObjArray((fNoutputs)?fNoutputs:2);
159    fPublishedData = 0;
160    Int_t i;
161    for (i=0; i<fNinputs; i++) fInputs->AddAt(task.GetInputSlot(i),i);
162    fOutputReady = new Bool_t[(fNoutputs)?fNoutputs:2];
163    for (i=0; i<fNoutputs; i++) {
164       fOutputReady[i] = IsOutputReady(i);
165       fOutputs->AddAt(task.GetOutputSlot(i),i);
166    }   
167 }
168
169 //______________________________________________________________________________
170 AliAnalysisTask::~AliAnalysisTask()
171 {
172 // Dtor.
173    if (fTasks) fTasks->Clear();
174    if (fInputs)  {fInputs->Delete(); delete fInputs;}
175    if (fOutputs) {fOutputs->Delete(); delete fOutputs;}
176 }   
177   
178 //______________________________________________________________________________
179 AliAnalysisTask& AliAnalysisTask::operator=(const AliAnalysisTask& task)
180 {
181 // Assignment
182    if (&task == this) return *this;
183    TTask::operator=(task);
184    fReady       = task.IsReady();
185    fInitialized = task.IsInitialized();
186    fNinputs     = task.GetNinputs();
187    fNoutputs    = task.GetNoutputs();
188    fInputs      = new TObjArray((fNinputs)?fNinputs:2);
189    fOutputs     = new TObjArray((fNoutputs)?fNoutputs:2);
190    fPublishedData = 0;
191    Int_t i;
192    for (i=0; i<fNinputs; i++) fInputs->AddAt(new AliAnalysisDataSlot(*task.GetInputSlot(i)),i);
193    fOutputReady = new Bool_t[(fNoutputs)?fNoutputs:2];
194    for (i=0; i<fNoutputs; i++) {
195       fOutputReady[i] = IsOutputReady(i);
196       fOutputs->AddAt(new AliAnalysisDataSlot(*task.GetOutputSlot(i)),i);
197    }         
198    return *this;
199 }
200
201 //______________________________________________________________________________
202 Bool_t AliAnalysisTask::AreSlotsConnected()
203 {
204 // Check if all input/output slots are connected. If this is the case fReady=true
205    fReady = kFALSE;
206    if (!fNinputs || !fNoutputs) return kFALSE;
207    Int_t i;
208    AliAnalysisDataSlot *slot;
209    for (i=0; i<fNinputs; i++) {
210       slot = (AliAnalysisDataSlot*)fInputs->At(i);
211       if (!slot) {
212               Error("AreSlotsConnected", "Input slot %d of task %s not defined !",i,GetName());
213          return kFALSE;
214       }   
215       if (!slot->IsConnected()) return kFALSE;
216    }   
217    for (i=0; i<fNoutputs; i++) {
218       slot = (AliAnalysisDataSlot*)fOutputs->At(i);
219       if (!slot) {
220          Error("AreSlotsConnected", "Output slot %d of task %s not defined !",i,GetName());
221          return kFALSE;
222       }   
223       if (!slot->IsConnected()) return kFALSE;
224    } 
225    fReady = kTRUE;  
226    return kTRUE;
227 }
228
229 //______________________________________________________________________________
230 void AliAnalysisTask::CheckNotify(Bool_t init)
231 {
232 // Check if data is available from all inputs. Change the status of the task
233 // accordingly. This method is called automatically for all tasks connected
234 // to a container where the data was published.
235    if (init) fInitialized = kFALSE;
236 //   Bool_t execperevent = IsExecPerEvent();
237    AliAnalysisDataContainer *cinput;
238    for (Int_t islot=0; islot<fNinputs; islot++) {
239       cinput = GetInputSlot(islot)->GetContainer();
240       if (!cinput) return;
241       if (!cinput->GetData()) {
242 //      if (!cinput->GetData() || execperevent!=cinput->IsEventByEvent()) {
243          SetActive(kFALSE);
244          return;
245       }   
246    }   
247    SetActive(kTRUE);
248    if (fInitialized) return;
249    TDirectory *cursav = gDirectory;
250    ConnectInputData();
251    if (cursav) cursav->cd();
252    fInitialized = kTRUE;
253 }
254
255 //______________________________________________________________________________
256 Bool_t AliAnalysisTask::ConnectInput(Int_t islot, AliAnalysisDataContainer *cont)
257 {
258 // Connect an input slot to a data container.
259    AliAnalysisDataSlot *input = GetInputSlot(islot);
260    if (!input) {
261       Error("ConnectInput","Input slot %i not defined for analysis task %s", islot, GetName());
262       return kFALSE;
263    }
264    // Check type matching          
265    if (!input->GetType()->InheritsFrom(cont->GetType())) {
266       Error("ConnectInput","Data type %s for input %i of task %s not matching container %s of type %s",input->GetType()->GetName(), islot, GetName(), cont->GetName(), cont->GetType()->GetName());
267       return kFALSE;
268    }  
269    // Connect the slot to the container as input          
270    if (!input->ConnectContainer(cont)) return kFALSE;
271    // Add this to the list of container consumers
272    cont->AddConsumer(this, islot);
273    AreSlotsConnected();
274    return kTRUE;
275 }   
276
277 //______________________________________________________________________________
278 Bool_t AliAnalysisTask::ConnectOutput(Int_t islot, AliAnalysisDataContainer *cont)
279 {
280 // Connect an output slot to a data container.
281    AliAnalysisDataSlot *output = GetOutputSlot(islot);
282    if (!output) {
283       Error("ConnectOutput","Output slot %i not defined for analysis task %s", islot, GetName());
284       return kFALSE;
285    }
286    // Check type matching          
287    if (!output->GetType()->InheritsFrom(cont->GetType())) {
288       Error("ConnectOutput","Data type %s for output %i of task %s not matching container %s of type %s",output->GetType()->GetName(), islot, GetName(), cont->GetName(), cont->GetType()->GetName());
289       return kFALSE;
290    }            
291    // Connect the slot to the container as output         
292    if (!output->ConnectContainer(cont)) return kFALSE;
293    // Declare this as the data producer
294    cont->SetProducer(this, islot);
295    AreSlotsConnected();
296    return kTRUE;
297 }   
298
299 //______________________________________________________________________________
300 void AliAnalysisTask::DefineInput(Int_t islot, TClass *type)
301 {
302 // Define an input slot and its type.
303    AliAnalysisDataSlot *input = new AliAnalysisDataSlot(type, this);
304    if (fNinputs<islot+1) fNinputs = islot+1;
305    fInputs->AddAtAndExpand(input, islot);
306 }
307
308 //______________________________________________________________________________
309 void AliAnalysisTask::DefineOutput(Int_t islot, TClass *type)
310 {
311 // Define an output slot and its type.
312    AliAnalysisDataSlot *output = new AliAnalysisDataSlot(type, this);
313    if (fNoutputs<islot+1) {
314       fNoutputs = islot+1;
315       if (fOutputReady) delete [] fOutputReady;
316       fOutputReady = new Bool_t[fNoutputs];
317       memset(fOutputReady, 0, fNoutputs*sizeof(Bool_t));
318    } 
319    fOutputs->AddAtAndExpand(output, islot);
320 }
321
322 //______________________________________________________________________________
323 TClass *AliAnalysisTask::GetInputType(Int_t islot) const
324 {
325 // Retreive type of a given input slot.
326    AliAnalysisDataSlot *input = GetInputSlot(islot);
327    if (!input) {
328       Error("GetInputType","Input slot %d not defined for analysis task %s", islot, GetName());
329       return NULL;
330    }
331    return (input->GetType());
332 }
333
334 //______________________________________________________________________________
335 TClass *AliAnalysisTask::GetOutputType(Int_t islot) const
336 {
337 // Retreive type of a given output slot.
338    AliAnalysisDataSlot *output = GetOutputSlot(islot);
339    if (!output) {
340       Error("GetOutputType","Output slot %d not defined for analysis task %s", islot, GetName());
341       return NULL;
342    }
343    return (output->GetType());
344 }
345
346 //______________________________________________________________________________
347 TObject *AliAnalysisTask::GetInputData(Int_t islot) const
348 {
349 // Retreive input data for a slot if ready. Normally called by Exec() and
350 // the object has to be statically cast to the appropriate type.
351    AliAnalysisDataSlot *input = GetInputSlot(islot);
352    if (!input) {
353       Error("GetInputData","Input slot %d not defined for analysis task %s", islot, GetName());
354       return NULL;
355    }
356    return (input->GetData()); 
357 }
358
359 //______________________________________________________________________________
360 TObject *AliAnalysisTask::GetOutputData(Int_t islot) const
361 {
362 // Retreive output data for a slot. Normally called in UserTask::Terminate to
363 // get a valid pointer to data even in case of Proof.
364    AliAnalysisDataSlot *output = GetOutputSlot(islot);
365    if (!output) {
366       Error("GetOutputData","Input slot %d not defined for analysis task %s", islot, GetName());
367       return NULL;
368    }
369    return (output->GetData()); 
370 }
371
372 //______________________________________________________________________________
373 char *AliAnalysisTask::GetBranchAddress(Int_t islot, const char *branch) const
374 {
375 // Check if a branch with a given name from the specified input is connected
376 // to some address. Call this in Init() before trying to call SetBranchAddress()
377 // since the adress may be set by other task.
378    return (char *)GetInputSlot(islot)->GetBranchAddress(branch);
379 }
380
381 //______________________________________________________________________________
382 Bool_t AliAnalysisTask::SetBranchAddress(Int_t islot, const char *branch, void *address) const
383 {
384 // Connect an object address to a branch of the specified input.
385    return GetInputSlot(islot)->SetBranchAddress(branch, address);
386 }   
387
388 //______________________________________________________________________________
389 void AliAnalysisTask::ConnectInputData(Option_t *)
390 {
391 // Overload and connect your branches here.
392 }
393
394 //______________________________________________________________________________
395 void AliAnalysisTask::LocalInit()
396 {
397 // The method LocalInit() may be implemented to call locally (on the client)
398 // all initialization methods of the class. It is not mandatory and was created
399 // in order to minimize the complexity and readability of the analysis macro.
400 // DO NOT create in this method the histigrams or task output objects that will
401 // go in the task output containers. Use CreateOutputObjects for that.
402 }
403
404 //______________________________________________________________________________
405 void AliAnalysisTask::CreateOutputObjects()
406 {
407 // Called once per task either in PROOF or local mode. Overload to put some 
408 // task initialization and/or create your output objects here.
409 }
410
411 //______________________________________________________________________________
412 void AliAnalysisTask::OpenFile(Int_t iout, Option_t *option) const
413 {
414 // This method has to be called INSIDE the user redefined CreateOutputObjects
415 // method, before creating each object corresponding to the output containers
416 // that are to be written to a file. This need to be done in general for the big output
417 // objects that may not fit memory during processing. 
418 // - 'option' is the file opening option.
419 //=========================================================================
420 // NOTE !: The method call will be ignored in PROOF mode, in which case the 
421 // results have to be streamed back to the client and written just before Terminate()
422 //=========================================================================
423 //
424 // Example:
425 // void MyAnaTask::CreateOutputObjects() {
426 //    OpenFile(0);   // Will open the file for the object to be written at output #0
427 //    fAOD = new TTree("AOD for D0toKPi");
428 //    OpenFile(1);
429 // now some histos that should go in the file of the second output container
430 //    fHist1 = new TH1F("my quality check hist1",...);
431 //    fHist2 = new TH2F("my quality check hist2",...);
432 // }
433    
434    if (iout<0 || iout>=fNoutputs) return;
435    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
436    if (!mgr || mgr->GetAnalysisType()==AliAnalysisManager::kProofAnalysis) return;
437    AliAnalysisDataContainer *cont = GetOutputSlot(iout)->GetContainer();
438    if (strlen(cont->GetFileName())) new TFile(cont->GetFileName(), option);
439 }
440
441 //______________________________________________________________________________
442 Bool_t AliAnalysisTask::Notify()
443 {
444 // Overload this IF you need to treat input file change.
445    return kTRUE;
446 }
447
448 //______________________________________________________________________________
449 void AliAnalysisTask::Terminate(Option_t *)
450 {
451 // Method called by the framework at the end of data processing.
452 }
453
454 //______________________________________________________________________________
455 Bool_t AliAnalysisTask::PostData(Int_t iout, TObject *data, Option_t *option)
456 {
457 // Post output data for a given ouput slot in the corresponding data container.
458 // Published data becomes owned by the data container.
459 // If option is specified, the container connected to the output slot must have
460 // an associated file name defined. The option represents the method to open the file.
461    fPublishedData = 0;
462    AliAnalysisDataSlot *output = GetOutputSlot(iout);
463    if (!output) {
464       Error("PostData","Output slot %i not defined for analysis task %s", iout, GetName());
465       return kFALSE;
466    }
467    if (!output->IsConnected()) {
468       Error("PostData","Output slot %i of analysis task %s not connected to any data container", iout, GetName());
469       return kFALSE;
470    }
471    if (!fOutputReady) {
472       fOutputReady = new Bool_t[fNoutputs];
473       memset(fOutputReady, 0, fNoutputs*sizeof(Bool_t));
474    }   
475    fOutputReady[iout] = kTRUE;
476    fPublishedData = data;
477    return (output->GetContainer()->SetData(data, option));
478 }
479
480 //______________________________________________________________________________
481 void AliAnalysisTask::SetUsed(Bool_t flag)
482 {
483 // Set 'used' flag recursively to task and all daughter tasks.
484    if (TestBit(kTaskUsed)==flag) return;
485    TObject::SetBit(kTaskUsed,flag);
486    Int_t nd = fTasks->GetSize();
487    AliAnalysisTask *task;
488    for (Int_t i=0; i<nd; i++) {
489       task = (AliAnalysisTask*)fTasks->At(i);
490       task->SetUsed(flag);
491    }
492 }   
493
494 //______________________________________________________________________________
495 Bool_t AliAnalysisTask::CheckCircularDeps()
496 {
497 // Check for illegal circular dependencies, e.g. a daughter task should not have
498 // a hierarchical parent as subtask.
499    if (IsChecked()) return kTRUE;
500    SetChecked();
501    TList *tasks = GetListOfTasks();
502    Int_t ntasks = tasks->GetSize();
503    AliAnalysisTask *task;
504    for (Int_t i=0; i<ntasks; i++) {
505       task = (AliAnalysisTask*)tasks->At(i);
506       if (task->CheckCircularDeps()) return kTRUE;
507    }
508    SetChecked(kFALSE);
509    return kFALSE;
510 }   
511    
512 //______________________________________________________________________________
513 void AliAnalysisTask::PrintTask(Option_t *option, Int_t indent) const
514 {
515 // Print task info.
516    AliAnalysisTask *thistask = (AliAnalysisTask*)this;
517    TString opt(option);
518    opt.ToLower();
519    Bool_t dep = (opt.Contains("dep"))?kTRUE:kFALSE;
520    TString ind;
521    Int_t islot;
522    AliAnalysisDataContainer *cont;
523    for (Int_t i=0; i<indent; i++) ind += " ";
524    if (!dep || (dep && IsChecked())) {
525       printf("%s\n", Form("%stask: %s  ACTIVE=%i", ind.Data(), GetName(),IsActive()));
526       if (dep) thistask->SetChecked(kFALSE);
527       else {
528          for (islot=0; islot<fNinputs; islot++) {
529             printf("%s", Form("%s   INPUT #%i: %s <- ",ind.Data(),islot, GetInputType(islot)->GetName()));
530             cont = GetInputSlot(islot)->GetContainer();
531             if (cont) printf(" [%s]\n", cont->GetName());
532             else printf(" [NO CONTAINER]\n");
533          }
534          for (islot=0; islot<fNoutputs; islot++) {
535             printf("%s", Form("%s   OUTPUT #%i: %s -> ",ind.Data(),islot, GetOutputType(islot)->GetName()));
536             cont = GetOutputSlot(islot)->GetContainer();
537             if (cont) printf(" [%s]\n", cont->GetName());
538             else printf(" [NO CONTAINER]\n");
539          }            
540       }
541    }
542    PrintContainers(option, indent+3);
543 }      
544
545 //______________________________________________________________________________
546 void AliAnalysisTask::PrintContainers(Option_t *option, Int_t indent) const
547 {
548 // Print containers info.
549    AliAnalysisDataContainer *cont;
550    TString ind;
551    for (Int_t i=0; i<indent; i++) ind += " ";
552    Int_t islot;
553    for (islot=0; islot<fNoutputs; islot++) {
554       cont = GetOutputSlot(islot)->GetContainer();
555       if (cont) cont->PrintContainer(option, indent);
556    }   
557 }
558
559 //______________________________________________________________________________
560 void AliAnalysisTask::SetExecPerEvent(Bool_t flag)
561 {
562 // Set the task execution mode - run in a event loop or single shot. All output
563 // containers of this task will get the same type.
564    TObject::SetBit(kTaskEvtByEvt,flag);
565    AliAnalysisDataContainer *cont;
566    Int_t islot;
567    for (islot=0; islot<fNoutputs; islot++) {
568       cont = GetOutputSlot(islot)->GetContainer();
569       if (cont) cont->SetEventByEvent(flag);
570    }   
571 }
572