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