]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG4/macros/AnalysisTrainPWG4Jets.C
5277025294b132a1f4b7843534e2cd7997d54d75
[u/mrichter/AliRoot.git] / PWG4 / macros / AnalysisTrainPWG4Jets.C
1 //===================== ANALYSIS TRAIN =========================================
2 // To use: copy this macro to your work directory, modify the global part to match
3 // your needs, then run root.
4 //    root[0] .L AnalysisTrain.C
5 // Grid full mode as below (other modes: test, offline, submit, terminate)
6 //    root[1] AnalysisTrainPWG-244Jets("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainPWG4Jets("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainPWG4Jets("local")
11 // In proof and grid modes, a token is needed and sourcing the produced environment file.
12 //
13 // If 'saveTrain' flag is set, the train will generate a directory name and run
14 // in this directory. A configuration file 'ConfigTrain.C' will be generated. 
15 // One can replay at any time the train via:
16 //    root[1] AnalysisTrainPWG4Jets(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
17
18 // For Usage with fastjet run in "offline" first and then "submit"
19 // jdl and analysismacro are automatically patched after "offline" mode
20
21 // =============================================================================
22 // ### General Steering variables
23 // =============================================================================
24 //== general setup variables
25 TString     kTrainName         = "testAnalysis"; // *CHANGE ME* (no blancs or special characters)
26 TString     kJobTag            = "PWG4 Jet Tasks analysis train configured"; // *CHANGE ME*
27
28 // Usage of par files ONLY in grid mode and ONLY if the code is not available
29 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
30 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
31 // AliRoot.
32 Bool_t      kUsePAR             = kFALSE;  // use par files for extra libs
33 Bool_t      kUseCPAR            = kFALSE;  // use par files for common libs
34 Bool_t      kFillAOD = kFALSE;  // switch of AOD filling for on the fly analysis
35
36 //== general input and output variables
37
38 Int_t       iAODanalysis       = 1;      // Analysis on input AOD's
39 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
40 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
41 Int_t       iPhysicsSelection  = 1;      // ESD to AOD filter (barrel + muon tracks)
42 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
43 Bool_t      kUseMuonfilter     = kFALSE; // use Kinematics filter
44 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
45
46
47 //== general process variables
48
49 // ### Other flags to steer the analysis
50 //==============================================================================
51 Bool_t      kSkipTerminate      = kTRUE; // Do not call Teminate
52 Bool_t      kUseDate            = kFALSE; // use date in train name
53 Bool_t      kUseDebug           = kTRUE; // activate debugging
54 Int_t       kUseSysInfo         = 0; // activate debugging
55 Long_t      kNumberOfEvents     = 1234567890; // number of events to process from the chain
56 Bool_t      kUseMC              = kTRUE;  // use MC info
57 Bool_t      kIsMC               = kTRUE;  // is MC info, if false it overwrites Use(AOD)MC
58 Bool_t      kUseAODMC           = kTRUE;  // use MC infA
59 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
60 Bool_t      kUseTR              = kFALSE;  // use track references
61 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
62 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
63
64
65 // ### Analysis modules to be included. Some may not be yet fully implemented.
66 //==============================================================================
67 Int_t       iJETAN             = 1;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
68 Int_t       iDIJETAN           = 1;
69 Int_t       iJETANLib          = 1;
70 Int_t       iPWG1QASym         = 0;      // Eva's QA task compiled on the fly...
71 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
72 Int_t       iPWG4JetServices   = 0;      // jet spectrum analysis
73 Int_t       iPWG4JetSpectrum   = 0;      // jet spectrum analysis
74 Int_t       iPWG4JCORRAN       = 0;      // JCORRAN module
75 Int_t       iPWG4UE            = 0;      // Underlying Event analysis
76 Int_t       iPWG4TmpSourceSara = 0;      // Underlying Event analysis not in svn
77 Int_t       iPWG4TmpSourceFrag = 0;      // Bastian's Fragmentation function not in svn
78 Int_t       iPWG4JetChem       = 0;      // Jet chemistry 
79 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
80 Int_t       iPWG4PtSpectra     = 0;      // Marta's QA tasks 
81 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
82 Int_t       iPWG4PtCosmics     = 0;      // Marta's Cosmics Taks 
83 Int_t       iPWG4ThreeJets     = 0;      // Sona's thrust task
84 Int_t       iPWG4KMeans        = 0;      // Andreas' KMeans task 
85 Int_t       iPWG4Cluster       = 0;      // CKB cluster task 
86 Int_t       iPWG4PartCorrLibs  = 0;      // Gustavo's part corr analysis
87 Int_t       iPWG4PartCorr      = 0;      // Gustavo's part corr analysis
88 Int_t       iPWG4CaloQA        = 0;      // Gustavo's part corr analysis
89 Int_t       iPWG4JetCorr       = 0;     // Paul's jet corr analysis
90 Int_t       iPWG4Tagged        = 0;      // Gustavo's part corr analysis
91 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4) 
92 Int_t       iPWG4GammaConv     = 0;      // Gamma Conversio
93 Int_t       kHighPtFilterMask  = 16;     // change depending on the used AOD Filter
94 TString     kDeltaAODJetName   = "AliAOD.Jets.root";     
95 TString     kDeltaAODPartCorrName   = "deltaAODPartCorr.root";     
96
97
98 //==============================================================================
99 // ### PROOF Steering varibales
100 //==============================================================================
101 //== proof setup variables
102 TString     kProofCluster      = "alicecaf.cern.ch";
103 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
104 TString     kProofAFversion          = "AF-v4-17";
105 //== proof input and output variables
106 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
107 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
108 TString     kProofOutdir       = "";
109 Bool_t      kProofClearPackages = kFALSE;
110 Int_t       kProofEvents = 10000;
111 Int_t       kProofOffset = 0;
112 //== proof process variables
113
114
115 //==============================================================================
116 // ### Grid plugin Steering varibiables
117 //==============================================================================
118 //== grid plugin setup variables
119 Bool_t      kPluginUse         = kTRUE;   // do not change
120 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
121 TString     kPluginRootVersion       = "v5-26-00b-7";  // *CHANGE ME IF MORE RECENT IN GRID*
122 TString     kPluginAliRootVersion    = "v4-19-15-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
123 Bool_t      kPluginMergeViaJDL       = kTRUE;  // merge via JDL
124 Bool_t      kPluginFastReadOption   = kFALSE;  // use xrootd tweaks
125 Bool_t      kPluginOverwriteMode    = kTRUE;  // overwrite existing collections
126 Int_t       kPluginOutputToRunNumber = 1;     // write the output to subdirs named after run number
127 // TString kPluginExecutableCommand = "root -b -q";
128 TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
129
130 // == grid plugin input and output variables
131 TString     kGridDatadir      = "/alice/sim/PDC_08b/LHC09a1/AOD/";
132 TString     kGridLocalRunList = "";
133 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
134 TString     kGridDataSet      = ""; // sub working directory not to confuse different run xmls 
135 Int_t       kGridRunRange[2]       =  {0, -1}; // Set the run range
136 TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
137 TString     kGridPassPattern       = "";
138 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
139 Int_t       kGridMaxMergeFiles      = 50; // Number of files merged in a chunkgridrunragn
140 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
141 TString     kGridOutputStorages      = "disk=2"; // Make replicas on the storages
142 // == grid process variables
143 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
144 Int_t       kGridFilesPerJob       = 100; // Maximum number of files per job (gives size of AOD)
145
146 //==============================================================================
147 // ### Local Steering variables
148 //==============================================================================
149 //== local setup variables
150 //== local input and output variables
151 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
152 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
153 // == local process variables
154
155
156
157 // Temporaries.
158 TString anaPars = "";
159 TString anaLibs = "";
160 TString anaLibsExtra = "";
161 TString anaSources = "";
162 // Function signatures
163 class AliAnalysisAlien;
164
165 //______________________________________________________________________________
166 void AnalysisTrainPWG4Jets(const char *analysis_mode="local", 
167                            const char *plugin_mode="",
168                            const char *config_file="",Int_t iOffset = 0)
169 {
170 // Main analysis train macro. If a configuration file is provided, all parameters
171 // are taken from there but may be altered by CheckModuleFlags.
172
173    if (strlen(config_file) && !LoadConfig(config_file)) return;
174
175    if(iOffset)kProofOffset = iOffset;
176    TString smode(analysis_mode);
177    smode.ToUpper();
178    if (kSaveTrain)WriteConfig();
179    // Check compatibility of selected modules
180    CheckModuleFlags(smode);
181    //   gROOT->ProcessLine(".trace");
182
183    printf("==================================================================\n");
184    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
185    printf("==================================================================\n");
186    printf("=  Configuring analysis train for:                               =\n");
187    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
188    else              printf("=  ESD analysis                                                  =\n");
189    if (iPhysicsSelection)   printf("=  Physics selection                                                    =\n");
190    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
191    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
192    printf("==================================================================\n");
193    printf(":: use Fill AOD      %d\n", (UInt_t)kFillAOD);
194    printf(":: use MC truth      %d\n", (UInt_t)kUseMC);
195    printf(":: use KINE filter   %d\n", (UInt_t)kUseKinefilter);
196    printf(":: use track refs    %d\n", (UInt_t)kUseTR);
197    printf(":: use tags          %d\n", (UInt_t)kUseESDTags);
198    printf(":: use AOD tags      %d\n", (UInt_t)kUseAODTags);
199    printf(":: use debugging     %d\n", (UInt_t)kUseDebug);
200    printf(":: use PAR files     %d\n", (UInt_t)kUsePAR);
201    printf(":: use AliEn plugin  %d\n", (UInt_t)kPluginUse);
202    printf(":: use PWG1 QA sym         %d\n", iPWG1QASym);
203    printf(":: use PWG4 Source Sara    %d\n",iPWG4TmpSourceSara);
204    printf(":: use PWG4 Source BB      %d\n",iPWG4TmpSourceFrag);
205    printf(":: use PWG4 Jet Chem       %d\n",iPWG4JetChem);
206    printf(":: use PWG4 Jet tasks      %d\n",iPWG4JetTasks);
207    printf(":: use PWG4 Jet Services   %d\n",iPWG4JetServices);     
208    printf(":: use PWG4 Jet Spectrum   %d\n",iPWG4JetSpectrum);
209    printf(":: use PWG4 JCORRAN        %d\n",iPWG4JCORRAN);
210    printf(":: use PWG4 UE             %d \n",iPWG4UE); 
211    printf(":: use PWG4 Pt QA MC       %d\n",iPWG4PtQAMC);
212    printf(":: use PWG4 Pt Spectra     %d\n",iPWG4PtSpectra);
213    printf(":: use PWG4 Pt QA TPC      %d\n",iPWG4PtQATPC);     
214    printf(":: use PWG4 Cosmics        %d\n",iPWG4Cosmics);     
215    printf(":: use PWG4 Three Jets     %d\n",iPWG4ThreeJets);
216    printf(":: use PWG4 KMeans         %d\n",iPWG4KMeans);
217    printf(":: use PWG4 Cluster        %d\n",iPWG4Cluster);
218    printf(":: use PWG4 Part Corr      %d\n",iPWG4PartCorr);
219    printf(":: use PWG4 Calo QA        %d\n",iPWG4CaloQA);
220    printf(":: use PWG4 Jet Corr       %d\n",iPWG4JetCorr);
221    printf(":: use PWG4 Tagged         %d\n",iPWG4Tagged);
222    printf(":: use PWG4 omega to 3 pi  %d\n",iPWG4omega3pi);
223    printf(":: use PWG4 Gamma Conv     %d\n",iPWG4GammaConv);
224    printf(":: use HighPt FilterMask   %d\n",kHighPtFilterMask);    
225    
226    //==========================================================================
227    // Connect to back-end system
228    if (!Connect(smode)) {
229       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
230       return;
231    }   
232
233    // Load common libraries and set include path
234    if (!LoadCommonLibraries(smode)) {
235       ::Error("AnalysisTrain", "Could not load common libraries");
236       return;
237    }
238
239
240     
241    // Make the analysis manager and connect event handlers
242    AliAnalysisManager *mgr  = new AliAnalysisManager("PWG4Train", "pwg4 mini train");
243    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
244    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
245    mgr->SetNSysInfo(0);
246    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
247    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
248    mgr->SetSkipTerminate(kSkipTerminate);
249
250    // Load analysis specific libraries
251    if (!LoadAnalysisLibraries(smode)) {
252       ::Error("AnalysisTrain", "Could not load analysis libraries");
253      return;
254    }   
255
256    // Create input handler (input container created automatically)
257    if (iAODanalysis) {
258    // AOD input handler
259       AliAODInputHandler *aodH = new AliAODInputHandler();
260       mgr->SetInputEventHandler(aodH);
261       if (iPWG4JetTasks) aodH->AddFriend(Form("deltas/%s",kDeltaAODJetName.Data()));
262       if (iPWG4PartCorr) aodH->AddFriend(Form("deltas/%s"kDeltaAODJetName.Data()));
263    } else {   
264    // ESD input handler
265       AliESDInputHandler *esdHandler = new AliESDInputHandler();
266       if (kUseESDTags) esdHandler->SetReadTags();
267       esdHandler->SetReadFriends(kFALSE);
268       mgr->SetInputEventHandler(esdHandler);       
269       //      if(iPWG4PtQATPC&& !kTrainName.Contains("pass5"))esdHandler->SetActiveBranches("ESDfriend");
270
271    }
272
273    // Monte Carlo handler
274    if (kUseMC && !iAODanalysis) {
275       AliMCEventHandler* mcHandler = new AliMCEventHandler();
276       mgr->SetMCtruthEventHandler(mcHandler);
277       mcHandler->SetReadTR(kUseTR); 
278    }   
279    // AOD output container, created automatically when setting an AOD handler
280    if (iAODhandler) {
281       // AOD output handler
282       AliAODHandler* aodHandler   = new AliAODHandler();
283       aodHandler->SetOutputFileName("AliAOD.root");
284       aodHandler->SetFillAODforRun(kFillAOD);
285       
286       mgr->SetOutputEventHandler(aodHandler);
287       //
288       if (iAODanalysis) {
289
290         //         aodHandler->SetCreateNonStandardAOD();
291         //      if (iJETAN)aodHandler->SetOutputFileName(kDeltaAODJetName.Data());
292       } 
293       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
294       cout_aod->SetSpecialOutput();
295    }
296    // Debugging if needed
297
298    if (kUseDebug){
299      mgr->SetDebugLevel(3);
300    }
301    else{
302      AliLog::SetGlobalLogLevel(AliLog::kError);
303    }
304    //==========================================================================
305    // Create the chain. In this example it is created only from ALIEN files but
306    // can be done to work in batch or grid mode as well.
307    TChain *chain = CreateChain(smode, plugin_mode);
308         
309    //==========================================================================
310    // Load the tasks configuration macros for all wagons. These files are supposed now to be
311    // in the current workdir, but in AliEn they will be in the file catalog, 
312    // mapped from AliRoot and pecified in the jdl input list.
313     
314    // For now connection to top input container and common AOD output container
315    // is done in this macro, but in future these containers will be connected
316    // from each task configuration macro.
317    if(iPhysicsSelection && !iAODanalysis){
318      gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
319      AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kIsMC,kTRUE,kTRUE); // last flag also adds information on  
320    }
321
322    if (iESDfilter && !iAODanalysis) {
323       //  ESD filter task configuration.
324       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
325       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
326    }   
327
328    // AOD tags
329    if (kUseAODTags) {
330       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
331       mgr->AddTask(tagTask);
332       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
333                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
334       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
335       mgr->ConnectOutput(tagTask, 1, coutTags);
336    }   
337     
338     // Jet analysis
339    if (iJETAN) {
340       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
341       AliAnalysisTaskJets *taskjets = 0;
342       if(iJETAN&1)taskjets = AddTaskJets(kHighPtFilterMask); 
343       if(iJETAN&2){
344         UInt_t selection = 0;
345         if(!kFillAOD) selection = 0xffffff; //&~(1<<13);
346         else selection = 0xffffff&~(1<<13);// selection = 1<<0|1<<1|1<<2|1<<5|1<<6|1<<7|1<<8|1<<9|1<<10|1<<11|1<<12;
347         AddTaskJetsDelta(kDeltaAODJetName.Data(),kHighPtFilterMask,kUseAODMC,selection); 
348       }
349       if (!taskjets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
350    }
351
352    if (iDIJETAN) {
353       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
354       AliAnalysisTaskDiJets *taskdijets = 0;
355       if(iDIJETAN&1)taskdijets = AddTaskDiJets(); 
356       if (!taskdijets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
357       if(iDIJETAN&2){
358         taskdijets = AddTaskDiJets("jetsAOD_CDF07"); 
359         taskdijets = AddTaskDiJets("jetsAOD_DA07"); 
360         taskdijets = AddTaskDiJets("jetsAOD_FASTJET07"); 
361         taskdijets = AddTaskDiJets("jetsAOD_FASTKT07"); 
362         taskdijets = AddTaskDiJets("jetsAOD_SISCONE07"); 
363         taskdijets = AddTaskDiJets("jetsAOD_UA107");
364       }
365    }
366
367    if(iPWG1QASym){
368      gROOT->LoadMacro("$ALICE_ROOT/PWG1/PilotTrain/AddTaskQAsym.C");
369      AliAnalysisTaskQASym *taskQASym = AddTaskQAsym(-1);
370      if (!taskQASym) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQASym cannot run for this train conditions - EXCLUDED");
371    }
372
373
374
375    if(iPWG4TmpSourceSara){
376      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskEta.C");
377      AliAnalysisTaskEta *taskEta = AddTaskEta();
378      if (!taskEta) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskEta cannot run for this train conditions - EXCLUDED");
379    }
380
381    if(iPWG4TmpSourceFrag){
382      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFragFunc.C");
383      UInt_t selection = 1<<2;
384      AliAnalysisTaskFragFunc *taskFrag = AddTaskFragFunc(kHighPtFilterMask, kUseAODMC,iPhysicsSelection, selection);
385      if (!taskFrag) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskFragFunc cannot run for this train conditions - EXCLUDED");
386    }
387
388
389    if(iPWG4JetChem){
390      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetChem.C");
391      AliAnalysisTask *taskChem = AddTaskJetChem();
392      if (!taskChem) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetChem cannot run for this train conditions - EXCLUDED");
393    }
394
395
396    if(iPWG4JetServices){
397      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
398      AliAnalysisTaskJetServices *taskjetServ = 0;
399      taskjetServ = AddTaskJetServices();
400      if (!taskjetServ) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
401      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
402      else taskjetServ->SetRunRange(104000,125000);
403      if(!kIsMC) taskjetServ->SetRealData(kTRUE);
404      taskjetServ->SetUsePhysicsSelection((Bool_t)iPhysicsSelection);
405      taskjetServ->SetDebugLevel(0);
406    }
407
408    if(iPWG4JetSpectrum){
409      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
410      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
411      if(iPWG4JetSpectrum&1){
412        taskjetSpectrum = AddTaskJetSpectrum2("jets","",kHighPtFilterMask,iPhysicsSelection);      
413        if(!iAODanalysis){
414          //      taskjetSpectrum = AddTaskJetSpectrum2("jets","tracks32",32,iPhysicsSelection);       // tmp hack to give it a different name
415          //      taskjetSpectrum = AddTaskJetSpectrum2("jets","tracks64",64,iPhysicsSelection);      
416        }
417        if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
418        taskjetSpectrum->SetDebugLevel(1);
419      }
420
421      if(iPWG4JetSpectrum&2){
422        UInt_t selection = 0;
423        if(!iAODanalysis) selection = 0xffffff;
424        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
425        AddTaskJetSpectrum2Delta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,selection);
426      }
427    }
428    if(iPWG4JCORRAN){
429      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJCORRANTask.C");
430      AliJCORRANTask* corran = AddTaskJCORRAN(kTRUE);
431      if(!corran)::Warning("AnalysisTrainPWG4Jets", "AliJCORRANTask cannot run for this train conditions - EXCLUDED");
432    }
433
434    if(iPWG4UE){
435      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
436      AliAnalysisTaskUE *taskUE = 0;
437      if(iPWG4UE&1)taskUE = AddTaskUE(); 
438      if(iPWG4UE&2){
439        taskUE  =AddTaskUE("jetsAOD_CDF04","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
440        taskUE  =AddTaskUE("jetsAOD_CDF07","CDF", "LJ", "TRANSV","MSP");
441        taskUE  =AddTaskUE("jetsAOD_SISCONE04","CDF", "LJ", "TRANSV","MSP");
442        taskUE  =AddTaskUE("jetsAOD_SISCONE07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
443        taskUE  =AddTaskUE("jetsAOD_ICDF","CDF","LJ","TRANSV","MSP");
444        taskUE  =AddTaskUE("jetsAOD_FASTKT04","CDF", "LJ", "TRANSV","MSP");
445        taskUE  =AddTaskUE("jetsAOD_FASTKT07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
446        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta05", "TRANSV","MSP");
447        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta09", "TRANSV","MSP");
448      }
449
450      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
451    }
452
453    if(iPWG4ThreeJets){
454      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
455      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
456      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
457    }
458    if(iPWG4PtQAMC){
459      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
460      AliPWG4HighPtQAMC *taskQAMC = AddTaskPWG4HighPtQAMC();
461      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
462    }
463
464    if(iPWG4PtQATPC){
465      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
466      AliPWG4HighPtQATPConly *taskQATPC = 0;
467      if(iPWG4PtQATPC&1)taskQATPC = AddTaskPWG4HighPtQATPConly(1);
468      if(iPWG4PtQATPC&2)taskQATPC = AddTaskPWG4HighPtQATPConly(2);
469
470  if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
471    }
472
473    if(iPWG4Cosmics){
474      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4CosmicCandidates.C");
475
476      AliPWG4CosmicCandidates *taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(0);
477      taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(1);
478
479      if (!taskPWG4CosmicCandidates) ::Warning("AnalysisTrainPWG4Jets", "AddTaskPWG4CosmicCandidates cannot run for this train conditions - EXCLUDED");
480    }
481
482
483    if(iPWG4PtSpectra){
484      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
485      AliPWG4HighPtSpectra *taskPtSpectra = AddTaskPWG4HighPtSpectra();
486      if (!taskPtSpectra) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskPtSpectra cannot run for this train conditions - EXCLUDED");
487    }
488    if(iPWG4KMeans){
489      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
490      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
491      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
492    }
493
494    if(iPWG4Cluster){
495      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCluster.C");
496      AliAnalysisTaskJetCluster *taskCl = 0;
497      if(iPWG4Cluster&1){
498        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelection,"KT");
499      }
500      if(iPWG4Cluster&2){
501        UInt_t selection = 0;
502        if(!iAODanalysis) selection = 0xffffff;
503        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
504        AddTaskJetClusterDelta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,"KT",selection);
505      }
506      if(iPWG4Cluster&4){
507        UInt_t selection = 0;
508        if(!iAODanalysis) selection = 0xffffff;
509        else selection = 1<<0|1<<1|1<<2|1<<3|1<<4|1<<5|1<<7|1<<8|1<<9;
510        taskCl = AddTaskJetCluster("AOD","",kHighPtFilterMask,iPhysicsSelection,"ANTIKT");
511        AddTaskJetClusterDelta(kHighPtFilterMask,kUseAODMC,iPhysicsSelection,"ANTIKT",selection);
512      }
513
514
515      if (!taskCl) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCluster cannot run for this train conditions - EXCLUDED");
516
517    }
518    if(iPWG4PartCorr){
519      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
520      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
521      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
522      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
523      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
524      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data()); // hmm this is written anyway.... but at least we do not register it...
525    } 
526
527    if(iPWG4CaloQA){
528      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
529      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC);
530      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
531    } 
532
533    if(iPWG4JetCorr){
534      //     using namespace JetCorrelHD;
535      TString cdir = gSystem->WorkingDirectory();
536      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
537      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
538      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
539      gSystem->ChangeDirectory(cdir);
540      if (!taskjetcorr) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
541    } 
542
543    if(iPWG4Tagged){
544      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
545      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
546      taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
547      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
548    }
549    if (iPWG4omega3pi) {
550      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
551      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
552      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
553  for these train conditions - EXCLUDED");
554    }
555
556    // PWG4 gamma conversion analysis
557    if (iPWG4GammaConv) {
558       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
559       TString cdir = gSystem->WorkingDirectory();
560       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
561       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
562       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
563       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
564       TString gcArguments = "-run-on-train -run-jet -run-omega-meson -run-neutralmeson";
565       TString kGCAnalysisCutSelectionId="9002111000";
566       gcArguments.Append(Form("-set-cut-selection  %s ",kGCAnalysisCutSelectionId.Data()));
567       if(!kIsMC)gcArguments += " -mc-off";
568       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
569       gSystem->ChangeDirectory(cdir);
570       taskGammaConversion->SelectCollisionCandidates();
571       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
572    }   
573
574
575    //==========================================================================
576    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
577    // Run the analysis
578    //    
579    if (kPluginUse) {
580       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
581       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
582    }
583    
584    if (mgr->InitAnalysis()) {
585      mgr->PrintStatus();
586      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
587      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
588        TString alien_workdir = gGrid->GetHomeDirectory();
589        if (iAODanalysis) alien_workdir += "analysisAOD";
590        else              alien_workdir += "analysisESD";
591        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
592        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
593        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
594               alien_workdir.Data(),gridhandler->GetGridOutputDir());
595
596        TString dest;
597        dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
598        if(AliAnalysisAlien::FileExists(dest.Data())){
599          //      Printf("%s exist on grid removing...",dest.Data());
600          //      gGrid->Rm(dest.Data());
601        }
602        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
603        
604        dest = Form("%s/rootfiles/STEER/LQ1dRef_v1.root",gGrid->GetHomeDirectory());
605        if(AliAnalysisAlien::FileExists(dest.Data())){
606          Printf("%s exist on grid removing...",dest.Data());
607          gGrid->Rm(dest.Data());
608        }
609        TFile::Cp(Form("file:%s/STEER/LQ1dRef_v1.root",
610                       gSystem->ExpandPathName("$ALICE_ROOT")), 
611                  Form("alien://%s",dest.Data()));
612      }
613      AliLog::SetGlobalLogLevel(AliLog::kError);
614      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
615        TFile * fM = TFile::Open("manager_local.root","RECREATE");
616        mgr->Write();
617        fM->Close();
618      }
619
620      StartAnalysis(smode, chain);
621        
622      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
623        for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
624          mgr->ProfileTask(i);
625        }
626      }
627      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
628        // Offline mode path files
629        //       PatchJDL();
630        PatchAnalysisMacro();
631      }
632
633      if (kSaveTrain && smode=="GRID") {
634        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
635        TString alien_workdir = gGrid->GetHomeDirectory();
636        if (iAODanalysis) alien_workdir += "analysisAOD";
637        else              alien_workdir += "analysisESD";
638        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
639        //     kGridOutdir = gridhandler->GetGridOutputDir();
640        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
641                 alien_workdir.Data());
642        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
643          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
644        if (strcmp(plugin_mode, "test"))
645          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
646      }
647    }
648 }
649
650 //______________________________________________________________________________
651 void StartAnalysis(const char *mode, TChain *chain) {
652 // Start analysis.
653    Int_t imode = -1;
654    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
655    if (!strcmp(mode, "LOCAL")) imode = 0;
656    if (!strcmp(mode, "PROOF")) imode = 1;
657    if (!strcmp(mode, "GRID"))  imode = 2;
658    switch (imode) {
659       case 0:
660          if (!chain) {
661             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
662             return;
663          }   
664          mgr->StartAnalysis(mode, chain,kNumberOfEvents);
665          return;
666       case 1:
667          if (!kProofDataSet.Length()) {
668             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
669             return;
670          }   
671          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
672          return;
673       case 2:
674          if (kPluginUse) {
675             if (!mgr->GetGridHandler()) {
676                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
677                return;
678             }   
679             mgr->StartAnalysis("grid");
680          } else {
681             if (!chain) {
682                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
683                return;
684             }   
685             mgr->StartAnalysis(mode, chain);
686          }   
687          return;
688    }      
689 }          
690     
691 //______________________________________________________________________________
692 void CheckModuleFlags(const char *mode) {
693 // Checks selected modules and insure compatibility
694    Int_t imode = -1;
695    if (!strcmp(mode, "LOCAL")) imode = 0;
696    if (!strcmp(mode, "PROOF")) imode = 1;
697    if (!strcmp(mode, "GRID"))  imode = 2;
698
699
700    if (kUseCPAR) {
701      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
702    }
703
704    if (imode==1) {
705       if (!kUsePAR) {
706          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
707          kUsePAR = kTRUE;
708       }   
709    }  
710    if (imode != 2) {
711       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
712       kPluginUse = kFALSE; 
713    }   
714
715
716    if(!kIsMC){
717      // switch off anthin related to MC
718      kUseMC = 0;
719      kUseAODMC = 0;
720      kUseTR = kFALSE;
721    }
722
723    if (iAODanalysis) {
724    // AOD analysis
725       if (kUseMC)
726          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
727       if (kUseAODTags)
728          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
729       kUseMC = kFALSE;
730       kUseTR = kFALSE;
731       kUseAODTags = kFALSE;
732       if (iESDfilter)
733          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
734       iESDfilter   = 0;
735       if (iPhysicsSelection)
736          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
737       iPhysicsSelection   = 0;
738       if (!iAODhandler) {
739          if (iJETAN) 
740             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
741          iJETAN = 0;
742          iDIJETAN = 0;
743       }
744       // Disable tasks that do not work yet on AOD data
745       if(iPWG4JCORRAN)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 JCORRAN disabled in analysis on AOD's");
746       iPWG4JCORRAN = 0;
747       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
748       iPWG4PtQAMC        = 0;
749       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
750       iPWG4PtQATPC        = 0;
751       if( iPWG4Cosmics)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Comics disabled in analysis on AOD's");
752       iPWG4Cosmics        = 0;
753
754       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
755       iPWG4PtSpectra     = 0;
756       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
757       iPWG4KMeans       = 0;
758       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
759       iPWG4JetCorr = 0;
760       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
761       iPWG4PartCorr = 0;
762       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
763       iPWG4CaloQA = 0;
764       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
765       iPWG4Tagged = 0;
766       if (iPWG4omega3pi)
767         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
768       iPWG4omega3pi = 0;
769       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
770       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
771       iPWG4GammaConv = 0;   
772       iPWG1QASym     = 0;
773    } else {   
774    // ESD analysis
775      if (!kUseMC){
776        kUseTR = kFALSE;
777        
778        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
779        kUseKinefilter = kFALSE;
780        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
781        iPWG4PtQAMC        = 0;
782
783      }
784      if (!kUseTR) {
785        if(iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "iPWG4QATPCMC disabled if not reading track references");
786        iPWG4PtQAMC        = 0;
787      }   
788      if (iJETAN){
789        iESDfilter=1;
790      }
791       if (!iESDfilter){
792         kUseKinefilter = kFALSE;
793         kUseMuonfilter = kFALSE;
794       }
795       if(!iJETAN){
796         iPWG4JetSpectrum = iPWG4UE = iPWG4ThreeJets = iDIJETAN = 0;
797       }
798    }
799    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4PtQAMC||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4Cosmics||iPWG4ThreeJets||iPWG4JetChem;
800    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
801    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
802    if (iESDfilter) {iAODhandler=1;}
803    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
804    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
805
806
807    
808 }
809
810 //______________________________________________________________________________
811 Bool_t Connect(const char *mode) {
812 // Connect <username> to the back-end system.
813    Int_t imode = -1;
814    if (!strcmp(mode, "LOCAL")) imode = 0;
815    if (!strcmp(mode, "PROOF")) imode = 1;
816    if (!strcmp(mode, "GRID"))  imode = 2;
817    TString username = gSystem->Getenv("alien_API_USER");
818    switch (imode) {
819       case 0:
820          break;
821       case 1:
822          if  (!username.Length()) {
823             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
824                            1. Have called: alien-token-init <username>\n \
825                            2. Have called: >source /tmp/gclient_env_$UID");
826             return kFALSE;
827          }
828          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
829                 username.Data(), kProofCluster.Data());
830          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
831 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
832          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
833          if (!gProof) {
834             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
835                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
836             return kFALSE;
837          }
838          if(kProofClearPackages)gProof->ClearPackages();
839
840          if(kProofSaveToAlien){
841            TGrid::Connect("alien://");
842            if (gGrid) {
843              TString homedir = gGrid->GetHomeDirectory();
844              TString workdir = homedir + kTrainName;
845              if (!gGrid->Cd(workdir)) {
846                gGrid->Cd(homedir);
847                if (gGrid->Mkdir(workdir)) {
848                  gGrid->Cd(kTrainName);
849                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
850                }
851              }
852              gGrid->Mkdir("proof_output");
853              gGrid->Cd("proof_output");
854              kProofOutdir = Form("alien://%s", gGrid->Pwd());
855            }   
856          }
857          break;
858       case 2:      
859          if  (!username.Length()) {
860             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
861                            1. Have called: alien-token-init <username>\n \
862                            2. Have called: >source /tmp/gclient_env_$UID");
863             return kFALSE;
864          }
865          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
866             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
867                            "When using the AliEn plugin it is preferable to define the \
868                            variable alien_CLOSE_SE in your environment.");
869             return kFALSE;
870          }
871          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
872                 username.Data());
873          TGrid::Connect("alien://");
874          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
875          break;
876       default:
877          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
878          return kFALSE;
879    }
880    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
881    return kTRUE;
882 }
883
884 //______________________________________________________________________________
885 Bool_t LoadCommonLibraries(const char *mode)
886 {
887 // Load common analysis libraries.
888    Int_t imode = -1;
889    if (!strcmp(mode, "LOCAL")) imode = 0;
890    if (!strcmp(mode, "PROOF")) imode = 1;
891    if (!strcmp(mode, "GRID"))  imode = 2;
892    if (!gSystem->Getenv("ALICE_ROOT")) {
893       ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
894       return kFALSE;
895    }   
896    Bool_t success = kTRUE;
897    // ROOT libraries
898    gSystem->Load("libTree.so");
899    gSystem->Load("libGeom.so");
900    gSystem->Load("libVMC.so");
901    gSystem->Load("libPhysics.so");
902    
903    // Load framework classes. Par option ignored here.
904    switch (imode) {
905       case 0:
906       case 2:
907          if (kUseCPAR) {
908             success &= LoadLibrary("STEERBase", mode, kTRUE);
909             success &= LoadLibrary("ESD", mode, kTRUE);
910             success &= LoadLibrary("AOD", mode, kTRUE);
911             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
912             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
913             success &= LoadLibrary("CORRFW", mode, kTRUE);
914          } else {   
915             success &= LoadLibrary("libSTEERBase.so", mode);
916             success &= LoadLibrary("libESD.so", mode);
917             success &= LoadLibrary("libAOD.so", mode);
918             success &= LoadLibrary("libANALYSIS.so", mode);
919             success &= LoadLibrary("libANALYSISalice.so", mode);
920             success &= LoadLibrary("libCORRFW.so", mode);
921             gROOT->ProcessLine(".include $ALICE_ROOT/include");
922          }   
923          break;
924       case 1:
925          Int_t ires = -1;
926          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
927          if (ires < 0) {
928             success &= LoadLibrary("STEERBase", mode);
929             success &= LoadLibrary("ESD", mode);
930             success &= LoadLibrary("AOD", mode);
931             success &= LoadLibrary("ANALYSIS", mode);
932             success &= LoadLibrary("ANALYSISalice", mode);
933             success &= LoadLibrary("CORRFW", mode);
934          } else { 
935             ires = gProof->EnablePackage(kProofAFversion);
936             if (ires<0) success = kFALSE;
937             success &= LoadLibrary("CORRFW", mode);
938          }
939          break;         
940       default:
941          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
942          return kFALSE;
943    }
944    if (success) {
945       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
946       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
947               gSystem->GetIncludePath());
948    } else {           
949       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
950    }   
951       
952    return success;
953 }
954
955 //______________________________________________________________________________
956 Bool_t LoadAnalysisLibraries(const char *mode)
957 {
958 // Load common analysis libraries.
959    Bool_t success = kTRUE;
960    if (iESDfilter) {
961       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
962           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
963    }   
964    // JETAN
965    if (iJETANLib) {
966      // this part needs some rework in case we do not need the fastjed finders for processing
967      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
968      if (!strcmp(mode, "PROOF")){
969        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
970        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
971        // problem when loading siscone copiled with different gcc version??
972        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
973        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
974      }
975      if(!kUsePAR){ 
976        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
977        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
978        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
979        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
980      }
981      else{
982        // par files plus FASTJET needs some extra work... need to change
983        // the loading sequence in the auto generated .C file
984        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
985        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
986        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
987        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
988      }
989      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
990    }
991    if(iPWG4JetTasks){
992      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
993    }
994    if(iPWG4JCORRAN){
995      // PWG4 particle correlations
996      if(!LoadLibrary("PWG4JCORRAN",mode,kTRUE))return kFALSE;
997    }
998
999    if(iPWG1QASym){
1000      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1001    }
1002    if(iPWG4TmpSourceSara){
1003      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1004      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskEta.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1005    }
1006    if(iPWG4TmpSourceFrag){
1007      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1008      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskFragFunc.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1009    }
1010
1011
1012    /*
1013    if(iPWG4JetChem){
1014      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1015      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskJetChem.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1016    }
1017    */
1018
1019    if (iPWG4PartCorrLibs) {   
1020       if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
1021           !LoadLibrary("PHOSUtils", mode, kTRUE) ||
1022           !LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
1023           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
1024    }
1025    if (iPWG4JetCorr) { 
1026      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
1027    }  
1028    if (iPWG4omega3pi) {
1029      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
1030    }
1031    if (iPWG4GammaConv) {
1032       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
1033    }      
1034
1035    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1036    return kTRUE;
1037 }
1038
1039 //______________________________________________________________________________
1040 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1041 {
1042 // Load a module library in a given mode. Reports success.
1043    Int_t imode = -1;
1044    Int_t result;
1045    TString smodule(module);
1046    if (!strcmp(mode, "LOCAL")) imode = 0;
1047    if (!strcmp(mode, "PROOF")) imode = 1;
1048    if (!strcmp(mode, "GRID"))  imode = 2;
1049    TString mod(module);
1050    if (!mod.Length()) {
1051       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
1052       return kFALSE;
1053    }   
1054    // If a library is specified, just load it
1055    if (smodule.EndsWith(".so")) {
1056       mod.Remove(mod.Index(".so"));
1057       result = gSystem->Load(mod);
1058       if (result < 0) {
1059          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
1060          return kFALSE;
1061       }
1062       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1063       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
1064       return kTRUE;
1065    } 
1066    // Check if the library is already loaded
1067    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
1068       return kTRUE;    
1069    switch (imode) {
1070       case 0:
1071       case 2:
1072          if (kUsePAR) {
1073             result = SetupPar(module);
1074             if (rec) anaPars += Form("%s.par ", module);
1075          } else {
1076             result = gSystem->Load(Form("lib%s.so", module));
1077             if (rec) anaLibs += Form("lib%s.so ", module);
1078          }   
1079          break;
1080       case 1:
1081         if(!gSystem->AccessPathName(module)){
1082           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
1083           gSystem->Exec(Form("rm -rf %s",module));
1084         }
1085          result = gProof->UploadPackage(module);
1086          if (result<0) {
1087             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1088             if (result<0) {
1089                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1090                return kFALSE;
1091             }
1092          }   
1093          result = gProof->EnablePackage(module);
1094          break;
1095       default:
1096          return kFALSE;
1097    }         
1098    if (result < 0) {
1099       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
1100       return kFALSE;
1101    }
1102    return kTRUE;
1103 }           
1104
1105
1106
1107 //______________________________________________________________________________
1108 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
1109 {
1110 // Load a module library in a given mode. Reports success.
1111    Int_t imode = -1;
1112    Int_t result = -1;
1113    if (!strcmp(mode, "LOCAL")) imode = 0;
1114    if (!strcmp(mode, "PROOF")) imode = 1;
1115    if (!strcmp(mode, "GRID"))  imode = 2;
1116    TString ssource(source);
1117    TString basename = gSystem->BaseName(ssource.Data());
1118    if (!ssource.Length()) {
1119       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1120       return kFALSE;
1121    }   
1122    // we have a source code so compile it
1123    if (ssource.EndsWith(".cxx")) {
1124      // need to copy it here other wise the path is also used on grid...
1125      ssource.Remove(ssource.Index(".cxx"));
1126      basename.Remove(basename.Index(".cxx"));
1127      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1128      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1129      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1130      // Path to code
1131      // only needed for local compilation, in grid and proof mode 
1132      // the task headers are uploaded 
1133      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1134      // Printf("LoadSources:: Including path %s",path.Data());
1135      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1136      Printf("LoadSources:: Loading...  path %s",basename.Data());
1137      switch (imode) {
1138      case 0:
1139        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1140        break;
1141      case 1:
1142        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1143        break;
1144      case 2:
1145        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1146        if (rec){
1147          // what we want to compile
1148          anaSources += Form("%s.cxx ",basename.Data()); 
1149          // what we need as input...
1150          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1151        }
1152        break;
1153      default:
1154        return kFALSE;
1155      }
1156    } 
1157    if (result < 0) {
1158       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1159       return kFALSE;
1160    }
1161    return kTRUE;
1162 }           
1163
1164
1165 //______________________________________________________________________________
1166 TChain *CreateChain(const char *mode, const char *plugin_mode)
1167 {
1168 // Create the input chain
1169    Int_t imode = -1;
1170    if (!strcmp(mode, "LOCAL")) imode = 0;
1171    if (!strcmp(mode, "PROOF")) imode = 1;
1172    if (!strcmp(mode, "GRID"))  imode = 2;
1173    TChain *chain = NULL;
1174    // Local chain
1175    switch (imode) {
1176       case 0:
1177          if (iAODanalysis) {
1178             if (!kLocalXMLDataset.Length()) {
1179                // Local AOD
1180                chain = new TChain("aodTree");
1181                TString line;
1182                ifstream in;
1183                in.open(kLocalDataList.Data());
1184                while (in.good()) {
1185                  in >> line;
1186                  if (line.Length() == 0) continue;
1187                  // cout << " line = " << line << endl;
1188                  chain->Add(line.Data());
1189                }       
1190             } else {
1191                // Interactive AOD
1192                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1193             }
1194          } else {      
1195            if (!kLocalXMLDataset.Length()) {
1196              // Local ESD
1197              chain = new TChain("esdTree");
1198              TString line;
1199              ifstream in;
1200              in.open(kLocalDataList.Data());
1201              while (in.good()) {
1202                in >> line;
1203                if (line.Length() == 0) continue;
1204                cout << " line = " << line << endl;
1205                chain->Add(line.Data());
1206              }       
1207            } else {
1208              // Interactive ESD
1209                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1210            }   
1211          }
1212          break;
1213       case 1:
1214          break;
1215       case 2:
1216          if (kPluginUse) {
1217 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1218 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1219          } else {
1220             TString           treeName = "esdTree";
1221             if (iAODanalysis) treeName = "aodTree";
1222             chain = CreateChainSingle("wn.xml", treeName);
1223          }
1224          break;      
1225       default:   
1226    }
1227    if (chain && chain->GetNtrees()) return chain;
1228    return NULL;
1229 }   
1230
1231 //______________________________________________________________________________
1232 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1233 {
1234    printf("*******************************\n");
1235    printf("*** Getting the ESD Chain   ***\n");
1236    printf("*******************************\n");
1237    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1238
1239    if (!myCollection) {
1240       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1241       return NULL ;
1242    }
1243
1244    TChain* chain = new TChain(treeName);
1245    myCollection->Reset() ;
1246    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1247    chain->ls();
1248    return chain;
1249 }
1250
1251 //______________________________________________________________________________
1252 Int_t SetupPar(char* pararchivename)
1253 {
1254    if (!pararchivename || !strlen(pararchivename)) return -1;
1255    char processline[1024];
1256    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1257       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1258          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1259          TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1260                    Form("%s.par",pararchivename));
1261       } else {
1262          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
1263          return -1;
1264       }   
1265    }
1266    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
1267    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1268
1269    TString ocwd = gSystem->WorkingDirectory();
1270    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1271         
1272    // check for BUILD.sh and execute
1273    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1274       printf("*******************************\n");
1275       printf("*** Building PAR archive    ***\n");
1276       printf("*******************************\n");          
1277       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
1278          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
1279          return -1;
1280       }
1281    }
1282
1283         // check for SETUP.C and execute
1284         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1285             printf("*******************************\n");
1286             printf("*** Setup PAR archive       ***\n");
1287             printf("*******************************\n");
1288             gROOT->Macro("PROOF-INF/SETUP.C");
1289         }       
1290         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
1291    return 0;
1292 }
1293
1294 //______________________________________________________________________________
1295 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1296 {
1297 // Check if user has a valid token, otherwise make one. This has limitations.
1298 // One can always follow the standard procedure of calling alien-token-init then
1299 //   source /tmp/gclient_env_$UID in the current shell.
1300    if (!AliAnalysisGrid::CreateToken()) return NULL;
1301    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1302 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1303    plugin->SetRunMode(plugin_mode);
1304    if (kPluginUseProductionMode) plugin->SetProductionMode();
1305    plugin->SetJobTag(kJobTag);
1306    plugin->SetNtestFiles(2);
1307 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1308 // Set versions of used packages
1309    plugin->SetAPIVersion("V1.1x");
1310    //   plugin->SetAPIVersion("V1.0x");
1311 //   plugin->SetAPIVersion("V2.4");
1312    plugin->SetROOTVersion(kPluginRootVersion);
1313    plugin->SetAliROOTVersion(kPluginAliRootVersion);
1314 // Declare input data to be processed.
1315 // Method 1: Create automatically XML collections using alien 'find' command.
1316 // Define production directory LFN
1317    plugin->SetGridDataDir(kGridDatadir.Data());
1318 // Set data search pattern
1319    if (iAODanalysis) plugin->SetDataPattern(" *AliAOD.root");
1320    else              plugin->SetDataPattern(Form(" %s/*/*ESD.tag.root",kGridPassPattern.Data()));
1321 // ...then add run numbers to be considered
1322 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
1323    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
1324      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
1325      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
1326    }   
1327
1328    if(kGridLocalRunList.Length()>0){
1329      ifstream in1;
1330      in1.open(kGridLocalRunList.Data());
1331      int iRun;
1332
1333      /*
1334      char c;
1335      char cLine[250];
1336      while(!in1.eof()){
1337        c = in1.get();
1338        if ( (c >= '0') && (c <= '9') )
1339          {
1340            in1.putback (c);
1341            in1>>iRun;
1342            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1343            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1344        }
1345      else
1346        {
1347          in1.putback (c);
1348          in1.getline(cLine,250);
1349
1350        }
1351      }
1352      */
1353
1354      // just use run numbers, negatives will be excluded
1355      while(in1>>iRun){
1356        if(iRun>0){
1357            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1358            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1359        }
1360        else{
1361          Printf("AnalysisTrainPWG4Jets Skipping run number from File %d", iRun);
1362        }
1363      }
1364    }
1365
1366 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1367 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1368 // XML collections added via this method can be combined with the first method if
1369 // the content is compatible (using or not tags)
1370 //   plugin->AddDataFile("tag.xml");
1371 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1372 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1373    TString alien_workdir = "";
1374    
1375    if (iAODanalysis)  alien_workdir += "analysisAOD";
1376    else               alien_workdir += "analysisESD";    
1377    if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
1378    plugin->SetGridWorkingDir(alien_workdir.Data());
1379
1380    // Declare alien output directory. Relative to working directory.
1381    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1382    plugin->SetGridOutputDir(kGridOutdir);
1383
1384    // Add external packages
1385    if (iJETAN||iDIJETAN) {
1386       plugin->AddExternalPackage("boost::v1_38_0");
1387       plugin->AddExternalPackage("cgal::v3.3.1");
1388       plugin->AddExternalPackage("fastjet::v2.4.0");
1389    }   
1390
1391
1392    // set extra libs before par file compilation
1393    anaLibs += kGridExtraFiles;
1394    anaLibs     = anaLibs.Strip();   
1395    Printf("anaLibs %s",anaLibs.Data());
1396    Printf("anaLibsExtra %s",anaLibsExtra.Data());
1397
1398    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
1399    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
1400
1401    TString ana_sources = "";
1402    TString ana_add = "";
1403    if (kUsePAR && anaPars.Length()) {
1404       printf("%s\n", anaPars.Data());
1405       TObjArray *arr;
1406       TObjString *objstr;
1407       arr = anaPars.Tokenize(" ");
1408       TIter next(arr);
1409       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1410       delete arr;
1411    } 
1412    
1413 // Declare the analysis source files names separated by blancs. To be compiled runtime
1414 // using ACLiC on the worker nodes.
1415    ana_sources = anaSources.Strip();
1416 // Declare all libraries (other than the default ones for the framework. These will be
1417 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1418
1419    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1420    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
1421 // Declare the output file names separated by blancs.
1422 // (can be like: file.root or file.root@ALICE::Niham::File)
1423    plugin->SetDefaultOutputs();
1424    plugin->SetMergeExcludes(kGridMergeExclude);
1425    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
1426    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
1427    plugin->SetMergeViaJDL(kPluginMergeViaJDL);
1428 // Use fastread option
1429    plugin->SetFastReadOption(kPluginFastReadOption);
1430 // UseOverwrite mode
1431    plugin->SetOverwriteMode(kPluginOverwriteMode); 
1432 // Optionally define the files to be archived.
1433 //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1434    plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
1435    
1436    // Put default output files to archive
1437    TString listhists = "";
1438    TString listaods  = "";
1439    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1440    TIter next(mgr->GetOutputs());
1441    AliAnalysisDataContainer *output;
1442    while ((output=(AliAnalysisDataContainer*)next())) {
1443       const char *filename = output->GetFileName();
1444       if (!(strcmp(filename, "default"))) {
1445         if (!mgr->GetOutputEventHandler()) continue;
1446          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
1447          if (listaods.Length()) listaods += " ";
1448          listaods += filename;
1449       } else {
1450         if(!listhists.Contains(filename)){
1451           if (listhists.Length()) listhists += " ";
1452           listhists += filename;
1453         }
1454       }
1455    }
1456
1457    if(kUseSysInfo>0){
1458      if (listhists.Length()) listhists += " ";
1459      listhists += "syswatch.root";
1460    }
1461
1462    if(kIsMC){
1463      if (listaods.Length()) listaods += " ";
1464      listaods += "pyxsec_hists.root";
1465    }
1466
1467
1468    if (mgr->GetExtraFiles().Length()) {
1469      if (listaods.Length()) listaods += " ";
1470      listaods += mgr->GetExtraFiles();
1471    }
1472
1473    // if we do not fill the aod we do not need to store it
1474    kGridMergeExclude = listaods;
1475    
1476    if(!kFillAOD){
1477      listaods="";
1478      plugin->SetDefaultOutputs(kFALSE);
1479      plugin->SetOutputFiles(listhists.Data());
1480    }
1481
1482
1483    listaods.ReplaceAll(" ", ",");
1484    listhists.ReplaceAll(" ", ",");
1485    if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), kGridOutputStorages.Data());;
1486    if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), kGridOutputStorages.Data());;
1487
1488    if (!listhists.Length() && !listaods.Length()) {
1489       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
1490    }
1491
1492
1493
1494    TString outputArchive = "log_archive.zip:stdout,stderr@disk=2";
1495    if(kUseSysInfo>0)outputArchive = "log_archive.zip:stdout,stderr,syswatch.log@disk=2";
1496    if (listaods.Length()) {
1497       outputArchive += " ";
1498       outputArchive += listaods;
1499    }   
1500    if (listhists.Length()) {
1501       outputArchive += " ";
1502       outputArchive += listhists;
1503    }   
1504    plugin->SetOutputArchive(outputArchive);
1505 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
1506    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
1507 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
1508    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
1509 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
1510 //   plugin->SetMaxInitFailed(5);
1511 // Optionally resubmit threshold.
1512 //   plugin->SetMasterResubmitThreshold(90);
1513 // Optionally set time to live (default 30000 sec)
1514    plugin->SetTTL(30000);
1515 // Optionally set input format (default xml-single)
1516    plugin->SetInputFormat("xml-single");
1517 // Optionally modify the name of the generated JDL (default analysis.jdl)
1518    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
1519 // Optionally modify the executable name (default analysis.sh)
1520    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
1521 // Optionally modify job price (default 1)
1522    plugin->SetPrice(1);      
1523 // Optionally modify split mode (default 'se')    
1524    plugin->SetSplitMode("se");
1525    return plugin;
1526 }
1527
1528 //______________________________________________________________________________
1529 void WriteConfig()
1530 {
1531 // Write train configuration in a file. The file name has the format:
1532 // train_[trainName]_ddMonthyyyy_time.C
1533    if (kUseDate) {
1534       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
1535       ifstream fdate("date.tmp");
1536       if (!fdate.is_open()) {
1537          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
1538          return;
1539       }
1540       const char date[64];
1541       fdate.getline(date,64);
1542       fdate.close();
1543       gSystem->Exec("rm date.tmp");
1544       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
1545    } else {
1546       kTrainName = Form("train_%s", kTrainName.Data());
1547    }   
1548    TString cdir = gSystem->WorkingDirectory();
1549    gSystem->MakeDirectory(kTrainName);
1550    gSystem->ChangeDirectory(kTrainName);
1551    ofstream out;
1552    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
1553    if (out.bad()) {
1554       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
1555       return;
1556    }
1557    out << "{" << endl;
1558    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
1559    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
1560    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
1561    if (kProofUseAFPAR) 
1562       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
1563    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
1564    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
1565    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
1566    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
1567    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
1568    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
1569    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
1570    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1571    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
1572    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
1573    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
1574    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
1575    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
1576    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
1577    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
1578    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
1579    out << "   kUseMC           = " << kUseMC << ";" << endl;
1580    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
1581    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
1582    out << "   kUseTR           = " << kUseTR << ";" << endl;
1583    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
1584    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
1585    out << "   // Analysis modules" << endl;
1586    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
1587    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
1588    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
1589    out << "   iJETAN          = " << iJETAN << ";" << endl;
1590    out << "// Configuration fot the wagons" << endl;
1591    out << "}" << endl;
1592    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
1593    gSystem->ChangeDirectory(cdir);
1594 }   
1595
1596 //______________________________________________________________________________
1597 Bool_t LoadConfig(const char *filename)
1598 {
1599 // Read train configuration from file
1600    if (gSystem->AccessPathName(filename)) {
1601       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
1602       return kFALSE;
1603    }   
1604    gROOT->ProcessLine(Form(".x %s", filename));
1605    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
1606    return kTRUE;
1607 }
1608
1609 Bool_t PatchJDL(){
1610   Printf(">>> Patching JDL");
1611   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1612   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1613   TGridJDL *jdl = gridHandler->GetGridJDL();
1614   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
1615   gridHandler->WriteJDL(kFALSE);
1616   Printf("<<<  Patching JDL");
1617   return kTRUE;
1618 }
1619
1620 Bool_t PatchAnalysisMacro(){
1621     Printf(">>> Patching AnalysisMacro");
1622     gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
1623
1624   ifstream in1; 
1625   in1.open(Form("%s.C_tmp", kTrainName.Data()));
1626   char cLine[250];
1627   TString st;
1628   while(in1.getline(cLine,250)){
1629     st += cLine;
1630     st += "\n";
1631   }
1632   Int_t index;
1633   index = st.Index("gSystem->Load(\"libPhysics\");");
1634   index += strlen("gSystem->Load(\"libPhysics\");");
1635   if(iJETAN&&kUsePAR){
1636     TObjArray *arr;
1637     TObjString *objstr;
1638     arr = anaLibs.Tokenize(" ");
1639     TIter next(arr);
1640     TString add = "";
1641     add += "\n\n // added by CKB \n";
1642     while ((objstr=(TObjString*)next())){
1643       if(objstr->GetString().Contains("PWG3"))continue;
1644       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
1645     }
1646     delete arr; 
1647     //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());
1648     add += "gSystem->AddIncludePath(\"./\") \n";
1649     if(gGrid&&kPluginAliRootVersion.Length()==0){
1650       add += "// Dirty hack for TRD reference data \n";
1651       add += "gSystem->Setenv(\"ALICE_ROOT\",\"";
1652       add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
1653       add += "\"); \n";
1654     }
1655     add += "// BKC \n\n";
1656     st.Insert(index,add.Data());
1657   }
1658
1659   if(kUseDebug){
1660     st.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
1661   }
1662
1663   index = st.Index("gSystem->AddIncludePath");
1664   st.Insert(index,"// CKB ");
1665
1666   ofstream out;
1667   out.open(Form("%s.C", kTrainName.Data()));
1668   if (out.bad()) {
1669     return kFALSE;
1670   }
1671   out << st << endl;
1672   Printf("<<< Patching AnalysisMacro");
1673   return kTRUE;
1674
1675 }