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