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