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