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