Changes to fast embedding and jetresponse: QA plot for delta AOD, Jet eta phi selecti...
[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(0.0001);
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      if(iAODanalysis){
726        //       taskjetServ->SetDebugLevel(3);
727        taskjetServ->SetAODInput(kTRUE);
728      }
729    }
730
731 if(iPWG4JetSpectrum){
732      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
733      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
734      TString bkgClusters = kDefaultJetBackgroundBranch.Data(); 
735      bkgClusters.ReplaceAll(Form("%s_",AliAODJetEventBackground::StdBranchName()),"");
736
737      if(iPWG4JetSpectrum&1){
738        if(kIsPbPb){
739          for(int i = 0;i<5;i++){
740            TString tmp(kDefaultJetBranch.Data());
741            //      tmp.ReplaceAll(Form(kJetSubtractMask2.Data(),1),kJetSubtractMask1.Data());
742            //      tmp.ReplaceAll(Form(kJetSubtractMask2.Data(),1),kJetSubtractMask1.Data());
743            tmp.ReplaceAll(Form(kJetSubtractMask2.Data(),1),Form(kJetSubtractMask1.Data(),0));
744
745            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),tmp.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
746            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
747            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
748
749            //      taskjetSpectrum->SetDebugLevel(3);
750            //      taskjetSpectrum->SetMinJetPt(10);
751            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
752            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
753            if(iAODanalysis)SetAODInput(taskjetSpectrum);
754
755            
756            // check the old subtracted vs. the new subtracted
757            TString tmp2(kDefaultJetBranch.Data());
758            tmp2.ReplaceAll(Form(kJetSubtractMask2.Data(),1),Form(kJetSubtractMask2.Data(),2));
759            taskjetSpectrum = AddTaskJetSpectrum2(tmp2.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
760            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
761            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
762            //      taskjetSpectrum->SetDebugLevel(3);
763            //      taskjetSpectrum->SetMinJetPt(10);
764            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
765            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
766            if(iAODanalysis)SetAODInput(taskjetSpectrum);
767
768            // check the old subtracted vs. the new subtracted
769            TString tmp3(kDefaultJetBranch.Data());
770            tmp3.ReplaceAll(Form(kJetSubtractMask2.Data(),1),Form(kJetSubtractMask2.Data(),3));
771
772            taskjetSpectrum = AddTaskJetSpectrum2(tmp3.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
773            //      taskjetSpectrum->SetDebugLevel(3);
774            //      taskjetSpectrum->SetMinJetPt(10);
775            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
776            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
777            taskjetSpectrum->SetTrackEtaWindow(0.8);
778            taskjetSpectrum->SetJetEtaWindow(0.4);
779            if(iAODanalysis)SetAODInput(taskjetSpectrum);
780
781
782            taskjetSpectrum = AddTaskJetSpectrum2(Form("jetsAOD_UA104_B2_Filter%05d_Cut01000",kHighPtFilterMask),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
783            //      taskjetSpectrum->SetDebugLevel(3);
784            //      taskjetSpectrum->SetMinJetPt(10);
785            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
786            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
787            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
788            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
789            if(iAODanalysis)SetAODInput(taskjetSpectrum);
790
791          }
792        }
793        else{ // ! PbPb
794          Int_t i = 0;
795
796          taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
797                                                "",kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
798          
799
800          
801          if(kDefaultJetBranchMC.Length()){
802            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
803                                                kDefaultJetBranchMC.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
804            //      taskjetSpectrum->SetMinJetPt(10);
805            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
806            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
807            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
808            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
809            if(iAODanalysis)SetAODInput(taskjetSpectrum);
810          }
811          if(kDefaultJetBranchMC2.Length()){
812            taskjetSpectrum = AddTaskJetSpectrum2(kDefaultJetBranch.Data(),
813                                                  kDefaultJetBranchMC2.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
814            //      taskjetSpectrum->SetMinJetPt(10);
815            taskjetSpectrum->SetTrackEtaWindow(fTrackEtaWindow);
816            taskjetSpectrum->SetJetEtaWindow(fJetEtaWindow);
817            taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
818            taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
819            if(iAODanalysis)SetAODInput(taskjetSpectrum);
820          }
821
822          /*
823          TString tmp2(kDefaultJetBranch.Data());
824          tmp2.ReplaceAll(Form(kJetSubtractMask2.Data(),0),Form(kJetSubtractMask2.Data(),2));
825          taskjetSpectrum = AddTaskJetSpectrum2(tmp2.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
826          //      taskjetSpectrum->SetDebugLevel(3);
827          //        taskjetSpectrum->SetMinJetPt(10);
828          taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
829          taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
830          taskjetSpectrum->SetTrackEtaWindow(0.8);
831          taskjetSpectrum->SetJetEtaWindow(0.4);
832
833          // check the old subtracted vs. the new subtracted
834          TString tmp3(kDefaultJetBranch.Data());
835          tmp3.ReplaceAll(Form(kJetSubtractMask2.Data(),0),Form(kJetSubtractMask2.Data(),3));
836          taskjetSpectrum = AddTaskJetSpectrum2(tmp3.Data(),kDefaultJetBranch.Data(),kDeltaAODJetName.Data(),kHighPtFilterMask,AliVEvent::kMB,0,i);
837          //      taskjetSpectrum->SetDebugLevel(3);
838          //        taskjetSpectrum->SetMinJetPt(10);
839          taskjetSpectrum->SetBranchBkgRec(bkgClusters.Data());
840          taskjetSpectrum->SetBranchBkgGen(bkgClusters.Data());
841          taskjetSpectrum->SetTrackEtaWindow(0.8);
842          taskjetSpectrum->SetJetEtaWindow(0.4);
843          if(iAODanalysis)SetAODInput(taskjetSpectrum);
844          */
845        }
846        if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
847      }
848    }
849
850    if(iPWG4Fragmentation){
851      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskFragmentationFunction.C");
852        AliAnalysisTaskFragmentationFunction *taskFrag = 0;
853      if(kUseAODMC){
854
855      }
856      else{
857        taskFrag = AddTaskFragmentationFunction(kDefaultJetBranch.Data(),"","","",kHighPtFilterMask);
858      }
859      if (!taskFrag) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskFragmentationFunction cannot run for this train conditions - EXCLUDED");
860    }
861
862    if(iPWG4JetChem){
863      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetChem.C");
864      AliAnalysisTask *taskChem = AddTaskJetChem(kHighPtFilterMask);
865      if (!taskChem) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetChem cannot run for this train conditions - EXCLUDED");
866    }
867
868    if (iPWG4JetResponse) {
869      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetResponse.C");
870      AliAnalysisTask *taskJetResponse = 0;
871
872      if(iJETAN){
873         taskJetResponse = AddTaskJetResponse("jets", "FASTJET", 0.4, kHighPtFilterMask, 0.15, 0);
874         taskJetResponse = AddTaskJetResponse("jets", "FASTJET", 0.4, kHighPtFilterMask, 0.15, 1);
875
876         taskJetResponse = AddTaskJetResponse("jets", "UA1", 0.4, kHighPtFilterMask, 1., 0);
877         taskJetResponse = AddTaskJetResponse("jets", "UA1", 0.4, kHighPtFilterMask, 1., 2);
878      }
879      if(iPWG4Cluster){
880         taskJetResponse = AddTaskJetResponse("clusters", "ANTIKT", 0.4, kHighPtFilterMask, 0.15, 0);
881         taskJetResponse = AddTaskJetResponse("clusters", "ANTIKT", 0.4, kHighPtFilterMask, 0.15, 1);
882      }
883      if (!taskJetResponse) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetResponse cannot run for this train conditions - EXCLUDED");
884
885    }
886
887    if(iPWG4JCORRAN){
888      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJCORRANTask.C");
889      AliJCORRANTask* corran = AddTaskJCORRAN(kDeltaAODJCORRANName.Data(),0);
890      if(!corran)::Warning("AnalysisTrainPWG4Jets", "AliJCORRANTask cannot run for this train conditions - EXCLUDED");
891      else{
892        if(kDeltaAODJCORRANName.Length()>0)mgr->RegisterExtraFile(kDeltaAODJCORRANName.Data()); 
893      }
894    }
895
896    if(iPWG4UE){
897      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
898      AliAnalysisTaskUE *taskUE = 0;
899      if(iPWG4UE&1)taskUE = AddTaskUE(); 
900      if(iPWG4UE&2){
901        taskUE  =AddTaskUE("jetsAOD_CDF04","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
902        //       taskUE  =AddTaskUE("jetsAOD_CDF07","CDF", "LJ", "TRANSV","MSP");
903        taskUE  =AddTaskUE("jetsAOD_SISCONE04","CDF", "LJ", "TRANSV","MSP");
904        //       taskUE  =AddTaskUE("jetsAOD_SISCONE07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
905        taskUE  =AddTaskUE("jetsAOD_ICDF","CDF","LJ","TRANSV","MSP");
906        taskUE  =AddTaskUE("jetsAOD_FASTKT04","CDF", "LJ", "TRANSV","MSP");
907        //       taskUE  =AddTaskUE("jetsAOD_FASTKT07","CDF", "LJ", "TRANSV","MSP"); //finder not yet in train
908        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta05", "TRANSV","MSP");
909        taskUE  =AddTaskUE("jetsAOD_NONE","CDF", "MP_eta09", "TRANSV","MSP");
910      }
911
912      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
913    }
914
915    if(iPWG4LeadingUE){
916      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskLeadingTrackUE.C");
917      AliAnalysisTaskLeadingTrackUE *taskLeadingUE = AddTaskLeadingTrackUE(kUseMC);
918      if (!taskLeadingUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTasLeadingTrackkUE cannot run for this train conditions - EXCLUDED");
919      //     taskLeadingUE->SetFilterBit(64);
920    }
921
922
923    if(iPWG4CorrectionsUE){
924      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCorrectionsUE.C");
925      AliAnalysisTaskCorrectionsUE *taskCorrectionsUE = 0;
926      if(iPWG4CorrectionsUE&1)taskCorrectionsUE = AddTaskCorrectionsUE("jetsAOD_NONE","CDF","MP_eta05","TRANSV","MSP",kFALSE);
927      if (!taskCorrectionsUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskCorrectionsUE cannot run for this train conditions - EXCLUDED");
928    }
929
930    if(iPWG4ThreeJets){
931      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
932      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
933      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
934    }
935    if(iPWG4QGSep){
936      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskQGSep.C");
937      AliAnalysisTaskQGSep *taskQGSep = AddTaskQGSep(kUseMC,iAODanalysis);
938      if(!taskQGSep)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQGSep cannot run for this train conditions - EXCLUDED");
939    }
940   
941
942    if(iPWG4Minijet){
943      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskMinijet.C");
944      AliAnalysisTaskMinijet *taskMini = AddTaskMinijet(-1,"esd",kUseMC,kGridDataSet);
945      // if we ha highmult trigger add another task
946      if(!taskMini)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskMinjet cannot run for this train conditions - EXCLUDED");
947    }
948
949
950    if(iPWG4PtQAMC){
951      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
952      AliPWG4HighPtQAMC *taskQAMC = 0;
953      if(kUseMC){
954        if(iPWG4PtQAMC&1){
955          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),0);
956          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),1);
957          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),2);
958          taskQAMC = AddTaskPWG4HighPtQAMC(kGridDataSet.Data(),3);
959        }
960      }
961      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
962    }
963
964    if(iPWG4PtQATPC){
965      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
966      AliPWG4HighPtQATPConly *taskQATPC = 0;
967      if(iPWG4PtQATPC&1)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),1);
968      if(iPWG4PtQATPC&2)taskQATPC = AddTaskPWG4HighPtQATPConly(kGridDataSet.Data(),2);
969
970  if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
971    }
972
973    if(iPWG4Cosmics){
974      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4CosmicCandidates.C");
975
976      AliPWG4CosmicCandidates *taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(0);
977      taskPWG4CosmicCandidates = AddTaskPWG4CosmicCandidates(1);
978
979      if (!taskPWG4CosmicCandidates) ::Warning("AnalysisTrainPWG4Jets", "AddTaskPWG4CosmicCandidates cannot run for this train conditions - EXCLUDED");
980    }
981
982
983    if(iPWG4PtSpectra){
984      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
985      AliPWG4HighPtSpectra *taskPtSpectra = AddTaskPWG4HighPtSpectra(kGridDataSet.Data(),0);
986      taskPtSpectra = AddTaskPWG4HighPtSpectra(kGridDataSet.Data(),1);
987      if (!taskPtSpectra) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskPtSpectra cannot run for this train conditions - EXCLUDED");
988    }
989
990    if(iPWG4KMeans){
991      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskKMeans.C");
992      AliAnalysisTaskKMeans *taskKMeans = AddTaskKMeans();
993      if (!taskKMeans) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskKMenans cannot run for this train conditions - EXCLUDED");
994    }
995
996    if(iPWG4PartCorr){
997      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
998      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kFALSE,kIsMC);
999      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
1000      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kFALSE,kIsMC);
1001      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
1002      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data());
1003    } 
1004
1005    if(iPWG4CaloQA){
1006      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/QA/AddTaskCalorimeterQA.C");
1007      AliAnalysisTaskParticleCorrelation *taskcaloQA =  AddTaskCalorimeterQA("ESD",kFALSE,kIsMC,kCaloQAOutputFileName.Data());
1008      if(!taskcaloQA)::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation QA cannot run - EXCLUDED");
1009      //  if(kCaloQAOutputFileName.Length()>0)mgr->RegisterExtraFile(kCaloQAOutputFileName.Data());
1010    } 
1011
1012    if(iPWG4JetCorr){
1013      //     using namespace JetCorrelHD;
1014      TString cdir = gSystem->WorkingDirectory();
1015      gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
1016      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetCorrel.C");
1017      AliAnalysisTaskJetCorrel *taskjetcorr = AddTaskJetCorrel();
1018      gSystem->ChangeDirectory(cdir);
1019      if (!taskjetcorr) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJetCorrel  cannot run for this train conditions - EXCLUDED");
1020    } 
1021
1022    if(iPWG4Tagged){
1023      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskTaggedPhotons.C");
1024      AliAnalysisTaskTaggedPhotons * taskTagged = AddTaskTaggedPhotons(kFALSE); // EMCAL
1025      taskTagged = AddTaskTaggedPhotons(kTRUE); // PHOS 
1026      if (!taskTagged) ::Warning("AnalysisTrainNew", "AliAnalysisTaskTaggedPhotons  cannot run for this train conditions - EXCLUDED");     
1027    }
1028    if (iPWG4omega3pi) {
1029      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
1030      AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
1031      if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run\
1032  for these train conditions - EXCLUDED");
1033    }
1034
1035    // PWG4 gamma conversion analysis
1036    if (iPWG4GammaConv) {
1037       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
1038       TString cdir = gSystem->WorkingDirectory();
1039       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
1040       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
1041       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
1042       //      TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf -use-own-xyz";
1043       TString gcArguments = "-run-on-train -run-jet -run-omega-meson -use-own-xyz -run-neutralmeson -no-aod";
1044       //      TString kGCAnalysisCutSelectionId="9003562000100310";
1045       //      TString kGCAnalysisCutSelectionId="9003562000100312";
1046       //      gcArguments.Append(Form(" -set-cut-selection %s ",kGCAnalysisCutSelectionId.Data()));
1047       if(!kIsMC)gcArguments += " -mc-off";
1048       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
1049       gSystem->ChangeDirectory(cdir);
1050       taskGammaConversion->SelectCollisionCandidates();
1051       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
1052    }   
1053
1054    if (iPWG4CaloConv) {
1055       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskCaloConv.C");
1056       AliAnalysisTaskCaloConv * taskCaloConv = AddTaskCaloConv();
1057       if (!taskCaloConv) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCaloConv cannot run for these train conditions - EXCLUDED");
1058    }   
1059
1060
1061
1062    //==========================================================================
1063    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
1064    // Run the analysis
1065    //    
1066    if (kPluginUse) {
1067       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1068       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1069    }
1070    
1071    if (mgr->InitAnalysis()) {
1072      mgr->PrintStatus();
1073      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
1074      if (!strcmp(plugin_mode,"submit")&&smode=="GRID"){
1075        TString alien_workdir = gGrid->GetHomeDirectory();
1076        if (iAODanalysis) alien_workdir += "analysisAOD";
1077        else              alien_workdir += "analysisESD";
1078        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
1079        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1080        printf("=== AnalysisTrainPWG4Jets:: Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
1081               alien_workdir.Data(),gridhandler->GetGridOutputDir());
1082
1083        TString dest;
1084        dest = Form("%s/%s/%s.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1085        if(AliAnalysisAlien::FileExists(dest.Data())){
1086          Printf("%s exist on grid removing...",dest.Data());
1087          gGrid->Rm(dest.Data());
1088        }
1089        Printf("%s copy ...",dest.Data());
1090        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1091
1092
1093        TString dest;
1094        dest = Form("%s/%s/%s_merge.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1095        if(AliAnalysisAlien::FileExists(dest.Data())){
1096          Printf("%s exist on grid removing...",dest.Data());
1097          gGrid->Rm(dest.Data());
1098        }
1099        Printf("%s copy ...",dest.Data());
1100        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1101        
1102        dest = Form("%s/%s/%s_merge_final.jdl",alien_workdir.Data(),gridhandler->GetGridOutputDir(),kTrainName.Data());
1103        if(AliAnalysisAlien::FileExists(dest.Data())){
1104          Printf("%s exist on grid removing...",dest.Data());
1105          gGrid->Rm(dest.Data());
1106        }
1107        Printf("%s copy ...",dest.Data());
1108        TFile::Cp(Form("file:%s_merge.jdl",kTrainName.Data()),Form("alien://%s",dest.Data()));
1109
1110
1111        /*
1112        dest = Form("%s/rootfiles/STEER/LQ1dRef_v1.root",gGrid->GetHomeDirectory());
1113        if(AliAnalysisAlien::FileExists(dest.Data())){
1114          Printf("%s exist on grid removing...",dest.Data());
1115          gGrid->Rm(dest.Data());
1116        }
1117        TFile::Cp(Form("file:%s/STEER/LQ1dRef_v1.root",
1118                       gSystem->ExpandPathName("$ALICE_ROOT")),Form("alien://%s",dest.Data()));
1119        */
1120      }
1121      AliLog::SetGlobalLogLevel(AliLog::kError);
1122      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
1123        TFile * fM = TFile::Open("manager_local.root","RECREATE");
1124        mgr->Write();
1125        fM->Close();
1126      }
1127      
1128      // grmpf, aliroot error handler overwrites root
1129      gErrorIgnoreLevel = kErrorIgnoreLevel;
1130      if(gErrorIgnoreLevel>3000) AliLog::SetGlobalLogLevel(AliLog::kFatal);
1131      StartAnalysis(smode, chain);
1132      if((kUseSysInfo>0&&smode=="LOCAL")||!strcmp(plugin_mode, "test")){
1133        for(int i = 0;i < mgr->GetTopTasks()->GetEntries();i++){
1134          mgr->ProfileTask(i);
1135        }
1136      }
1137      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
1138        // Offline mode path files
1139        //       PatchJDL();
1140        //       PatchAnalysisMacro();
1141      }
1142
1143      if (kSaveTrain && smode=="GRID") {
1144        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1145        TString alien_workdir = gGrid->GetHomeDirectory();
1146        if (iAODanalysis) alien_workdir += "analysisAOD";
1147        else              alien_workdir += "analysisESD";
1148        if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
1149        //     kGridOutdir = gridhandler->GetGridOutputDir();
1150        printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
1151                 alien_workdir.Data());
1152        if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
1153          gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
1154        if (strcmp(plugin_mode, "test"))
1155          TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
1156      }
1157    }
1158 }
1159
1160 //______________________________________________________________________________
1161 void StartAnalysis(const char *mode, TChain *chain) {
1162 // Start analysis.
1163    Int_t imode = -1;
1164    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1165    if (!strcmp(mode, "LOCAL")) imode = 0;
1166    if (!strcmp(mode, "PROOF")) imode = 1;
1167    if (!strcmp(mode, "GRID"))  imode = 2;
1168    switch (imode) {
1169       case 0:
1170          if (!chain) {
1171             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
1172             return;
1173          }   
1174          mgr->StartAnalysis(mode, chain,kNumberOfEvents);
1175          return;
1176       case 1:
1177          if (!kProofDataSet.Length()) {
1178             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
1179             return;
1180          }   
1181          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
1182          return;
1183       case 2:
1184          if (kPluginUse) {
1185             if (!mgr->GetGridHandler()) {
1186                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
1187                return;
1188             }   
1189             mgr->StartAnalysis("grid",chain,kNumberOfEvents);
1190          } else {
1191             if (!chain) {
1192                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
1193                return;
1194             }   
1195             mgr->StartAnalysis(mode, chain);
1196             mgr->StartAnalysis(mode, chain,kNumberOfEvents);
1197          }   
1198          return;
1199    }      
1200 }          
1201     
1202 //______________________________________________________________________________
1203 void CheckModuleFlags(const char *mode) {
1204 // Checks selected modules and insure compatibility
1205    Int_t imode = -1;
1206    if (!strcmp(mode, "LOCAL")) imode = 0;
1207    if (!strcmp(mode, "PROOF")) imode = 1;
1208    if (!strcmp(mode, "GRID"))  imode = 2;
1209
1210
1211    if (kUseCPAR) {
1212      kPluginAliRootVersion    = ""; // NO aliroot if we use CPAR
1213    }
1214
1215    if (imode==1) {
1216       if (!kUsePAR) {
1217          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
1218          kUsePAR = kTRUE;
1219       }   
1220    }  
1221    if (imode != 2) {
1222       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
1223       kPluginUse = kFALSE; 
1224    }   
1225
1226
1227    if(!kIsMC){
1228      // switch off anthin related to MC
1229      kUseMC = 0;
1230      kUseAODMC = 0;
1231      kUseTR = kFALSE;
1232    }
1233
1234    // Decide if we have PbPb
1235    if(kGridDataSet.CompareTo("LHC10h")==0||kGridDataSet.Contains("LHC10h")) {
1236      Printf("Using settings for Pb+Pb");
1237      kIsPbPb = true;
1238    }
1239
1240    
1241
1242    if (iAODanalysis) {
1243    // AOD analysis
1244       if (kUseMC)
1245          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
1246       if (kUseAODTags)
1247          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
1248       kUseMC = kFALSE;
1249       kUseTR = kFALSE;
1250       kUseAODTags = kFALSE;
1251       if (iESDfilter)
1252          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
1253       iESDfilter   = 0;
1254       if (iPhysicsSelection)
1255          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "Physics Selection disabled in analysis on AOD's");
1256       iPhysicsSelection   = 0;
1257       if (!iAODhandler) {
1258          if (iJETAN) 
1259             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
1260          iJETAN = 0;
1261          iDIJETAN = 0;
1262       }
1263       // Disable tasks that do not work yet on AOD data
1264       if(iPWG4JCORRAN)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 JCORRAN disabled in analysis on AOD's");
1265       iPWG4JCORRAN = 0;
1266       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
1267       iPWG4PtQAMC        = 0;
1268       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
1269       iPWG4PtQATPC        = 0;
1270       if( iPWG4Cosmics)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Comics disabled in analysis on AOD's");
1271       iPWG4Cosmics        = 0;
1272
1273       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
1274       iPWG4PtSpectra     = 0;
1275       if(iPWG4KMeans)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4KMeans disabled on AOD's");
1276       iPWG4KMeans       = 0;
1277       if (iPWG4JetCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4Jetcorr disabled on AOD's");
1278       iPWG4JetCorr = 0;
1279       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
1280       iPWG4PartCorr = 0;
1281       if (iPWG4CaloQA)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4CaloQA disabled on AOD's");
1282       iPWG4CaloQA = 0;
1283       if (iPWG4Tagged)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4tagged disabled on AOD's");
1284       iPWG4Tagged = 0;
1285       if (iPWG4omega3pi)
1286         ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
1287       iPWG4omega3pi = 0;
1288       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
1289       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
1290       iPWG4GammaConv = 0;   
1291       iPWG1QASym     = 0;
1292       iCentralitySelection = 0;
1293    } else {   
1294    // ESD analysis
1295
1296      if(kIsPbPb){
1297        iCentralitySelection = 1;
1298      }
1299
1300      if (!kUseMC){
1301        kUseTR = kFALSE;
1302        
1303        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
1304        kUseKinefilter = kFALSE;
1305        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
1306        iPWG4PtQAMC        = 0;
1307        if( iPWG4CorrectionsUE)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 CorrectionsUE disabled in analysis without MC");
1308        iPWG4CorrectionsUE = 0;
1309      }
1310      if (!kUseTR) {
1311        if(iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "iPWG4QATPCMC disabled if not reading track references");
1312        iPWG4PtQAMC        = 0;
1313      }   
1314      if (iJETAN){
1315        iESDfilter=1;
1316      }
1317       if (!iESDfilter){
1318         kUseKinefilter = kFALSE;
1319         kUseMuonfilter = kFALSE;
1320       }
1321       if(!iJETAN){
1322         iPWG4JetSpectrum = iPWG4UE =  iPWG4CorrectionsUE = iPWG4ThreeJets = iPWG4QGSep = iDIJETAN = 0;
1323       }
1324    }
1325    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4LeadingUE||iPWG4PtQAMC||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4Cosmics||iPWG4ThreeJets||iPWG4QGSep||iPWG4JetChem||iPWG4Minijet||iPWG4Fragmentation;
1326    iPWG4PartCorrLibs = iPWG4PartCorr||iPWG4Tagged||iPWG4CaloQA;
1327    iPWG4GammaConvLib = iPWG4GammaConv||iPWG4CaloConv;
1328
1329
1330    iEMCUtilLibs = iPWG4PartCorrLibs||iPWG4JCORRAN||iPWG4GammaConvLib;
1331    iJETANLib = iPWG4JetTasks||iJETAN||iDIJETAN;
1332
1333    if (iESDfilter) {iAODhandler=1;}
1334    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
1335    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
1336
1337
1338    
1339 }
1340
1341 //______________________________________________________________________________
1342 Bool_t Connect(const char *mode) {
1343 // Connect <username> to the back-end system.
1344    Int_t imode = -1;
1345    if (!strcmp(mode, "LOCAL")) imode = 0;
1346    if (!strcmp(mode, "PROOF")) imode = 1;
1347    if (!strcmp(mode, "GRID"))  imode = 2;
1348    TString username = gSystem->Getenv("alien_API_USER");
1349    switch (imode) {
1350       case 0:
1351          break;
1352       case 1:
1353          if  (!username.Length()) {
1354             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
1355                            1. Have called: alien-token-init <username>\n \
1356                            2. Have called: >source /tmp/gclient_env_$UID");
1357             return kFALSE;
1358          }
1359          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
1360                 username.Data(), kProofCluster.Data());
1361          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
1362 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
1363          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
1364          if (!gProof) {
1365             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
1366                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
1367             return kFALSE;
1368          }
1369          if(kProofClearPackages)gProof->ClearPackages();
1370
1371          if(kProofSaveToAlien){
1372            TGrid::Connect("alien://");
1373            if (gGrid) {
1374              TString homedir = gGrid->GetHomeDirectory();
1375              TString workdir = homedir + kTrainName;
1376              if (!gGrid->Cd(workdir)) {
1377                gGrid->Cd(homedir);
1378                if (gGrid->Mkdir(workdir)) {
1379                  gGrid->Cd(kTrainName);
1380                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
1381                }
1382              }
1383              gGrid->Mkdir("proof_output");
1384              gGrid->Cd("proof_output");
1385              kProofOutdir = Form("alien://%s", gGrid->Pwd());
1386            }   
1387          }
1388          break;
1389       case 2:      
1390          if  (!username.Length()) {
1391             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
1392                            1. Have called: alien-token-init <username>\n \
1393                            2. Have called: >source /tmp/gclient_env_$UID");
1394             return kFALSE;
1395          }
1396          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
1397             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
1398                            "When using the AliEn plugin it is preferable to define the \
1399                            variable alien_CLOSE_SE in your environment.");
1400             return kFALSE;
1401          }
1402          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
1403                 username.Data());
1404          TGrid::Connect("alien://");
1405          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
1406          break;
1407       default:
1408          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
1409          return kFALSE;
1410    }
1411    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
1412    return kTRUE;
1413 }
1414
1415 //______________________________________________________________________________
1416 Bool_t LoadCommonLibraries(const char *mode)
1417 {
1418    if (!gSystem->Getenv("ALICE_ROOT")) {
1419       ::Error("AnalysisTrainPWG4Jets.C", "Analysis train requires that ALICE_ROOT is set to pick up Configurations"); 
1420       return kFALSE;
1421    }   
1422    
1423    // Load common analysis libraries.
1424    Int_t imode = -1;
1425    if (!strcmp(mode, "LOCAL")) imode = 0;
1426    if (!strcmp(mode, "PROOF")) imode = 1;
1427    if (!strcmp(mode, "GRID"))  imode = 2;
1428    Bool_t success = kTRUE;
1429    // ROOT libraries
1430    gSystem->Load("libTree.so");
1431    gSystem->Load("libGeom.so");
1432    gSystem->Load("libVMC.so");
1433    gSystem->Load("libPhysics.so");
1434    
1435    // Load framework classes. Par option ignored here.
1436    switch (imode) {
1437       case 0:
1438       case 2:
1439          if (kUseCPAR) {
1440             success &= LoadLibrary("STEERBase", mode, kTRUE);
1441             success &= LoadLibrary("ESD", mode, kTRUE);
1442             success &= LoadLibrary("AOD", mode, kTRUE);
1443             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
1444             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
1445             success &= LoadLibrary("ROOTFILES", mode, kTRUE);
1446             // success &= LoadLibrary("EventMixing", mode,kTRUE);
1447             success &= LoadLibrary("CORRFW", mode, kTRUE);
1448          } else {   
1449             success &= LoadLibrary("libSTEERBase.so", mode);
1450             success &= LoadLibrary("libESD.so", mode);
1451             success &= LoadLibrary("libAOD.so", mode);
1452             success &= LoadLibrary("libANALYSIS.so", mode);
1453             success &= LoadLibrary("libANALYSISalice.so", mode);
1454             // success &= LoadLibrary("libEventMixing.so", mode);
1455             success &= LoadLibrary("libCORRFW.so", mode);
1456             gROOT->ProcessLine(".include $ALICE_ROOT/include");
1457          }   
1458          break;
1459       case 1:
1460          Int_t ires = -1;
1461          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
1462          if (ires < 0) {
1463             success &= LoadLibrary("STEERBase", mode);
1464             success &= LoadLibrary("ESD", mode);
1465             success &= LoadLibrary("AOD", mode);
1466             success &= LoadLibrary("ANALYSIS", mode);
1467             success &= LoadLibrary("ANALYSISalice", mode);
1468             success &= LoadLibrary("EventMixing", mode);
1469             success &= LoadLibrary("CORRFW", mode);
1470          } else { 
1471             ires = gProof->EnablePackage(kProofAFversion);
1472             if (ires<0) success = kFALSE;
1473             success &= LoadLibrary("CORRFW", mode);
1474          }
1475          break;         
1476       default:
1477          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
1478          return kFALSE;
1479    }
1480    if (success) {
1481       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
1482       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
1483               gSystem->GetIncludePath());
1484    } else {           
1485       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
1486    }   
1487       
1488    return success;
1489 }
1490
1491 //______________________________________________________________________________
1492 Bool_t LoadAnalysisLibraries(const char *mode)
1493 {
1494 // Load common analysis libraries.
1495   Bool_t success = kTRUE;
1496   if (useTender) {
1497       if (!LoadLibrary("TENDER", mode, kTRUE) ||
1498           !LoadLibrary("TENDERSupplies", mode, kTRUE)) return kFALSE;
1499    }
1500    if (iESDfilter) {
1501      /*
1502       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
1503           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
1504      */
1505    }   
1506    // JETAN
1507    if (iJETANLib) {
1508      // this part needs some rework in case we do not need the fastjed finders for processing
1509      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
1510      if (!strcmp(mode, "PROOF")){
1511        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGAL.so\"\)", kTRUE); 
1512        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
1513        // problem when loading siscone copiled with different gcc version??
1514        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
1515        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
1516      }
1517      if(!kUsePAR){ 
1518        if (!LoadLibrary("CGAL", mode, kTRUE)) return kFALSE;
1519        if (!LoadLibrary("fastjet", mode, kTRUE)) return kFALSE;
1520        if (!LoadLibrary("siscone", mode, kTRUE)) return kFALSE;
1521        if (!LoadLibrary("SISConePlugin", mode, kTRUE)) return kFALSE;
1522      }
1523      else{
1524        // par files plus FASTJET needs some extra work... need to change
1525        // the loading sequence in the auto generated .C file
1526        if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
1527        if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
1528        if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
1529        if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
1530      }
1531      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
1532    }
1533    if(iPWG4JetTasks){
1534      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
1535    }
1536
1537    if(iPWG1QASym){
1538      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1539    }
1540    if(iPWG4TmpSourceSara){
1541      if(!kUsePAR)gSystem->AddIncludePath("-I$ALICE_ROOT/include/JetTasks"); // ugly hack!!
1542      if(!LoadSource(Form("%s/PWG4/JetTasks/AliAnalysisTaskEta.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
1543    }
1544
1545    if(iEMCUtilLibs){
1546      if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
1547          !LoadLibrary("PHOSUtils", mode, kTRUE)) return kFALSE;
1548    }
1549
1550    if (iPWG4PartCorrLibs) {   
1551       if (!LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
1552           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
1553    }
1554    if(iPWG4JCORRAN){
1555      // PWG4 particle correlations
1556      if(!LoadLibrary("PWG4JCORRAN",mode,kTRUE))return kFALSE;
1557    }
1558    if (iPWG4JetCorr) { 
1559      if (!LoadLibrary("PWG4JetCorrel", mode, kTRUE)) return kFALSE;
1560    }  
1561    if (iPWG4omega3pi) {
1562      if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
1563    }
1564    if (iPWG4GammaConvLib) {
1565       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
1566    }      
1567
1568    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1569    return kTRUE;
1570 }
1571
1572 //______________________________________________________________________________
1573 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1574 {
1575 // Load a module library in a given mode. Reports success.
1576    Int_t imode = -1;
1577    Int_t result;
1578    TString smodule(module);
1579    if (!strcmp(mode, "LOCAL")) imode = 0;
1580    if (!strcmp(mode, "PROOF")) imode = 1;
1581    if (!strcmp(mode, "GRID"))  imode = 2;
1582    TString mod(module);
1583    if (!mod.Length()) {
1584       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
1585       return kFALSE;
1586    }   
1587    // If a library is specified, just load it
1588    if (smodule.EndsWith(".so")) {
1589       mod.Remove(mod.Index(".so"));
1590       result = gSystem->Load(mod);
1591       if (result < 0) {
1592          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
1593          return kFALSE;
1594       }
1595       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1596       if (rec) anaLibsExtra += Form("%s.so ",mod.Data()); 
1597       return kTRUE;
1598    } 
1599    // Check if the library is already loaded
1600    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
1601       return kTRUE;    
1602    switch (imode) {
1603       case 0:
1604       case 2:
1605          if (kUsePAR) {
1606             result = SetupPar(module);
1607             if (rec) anaPars += Form("%s.par ", module);
1608          } else {
1609             result = gSystem->Load(Form("lib%s.so", module));
1610             if (rec) anaLibs += Form("lib%s.so ", module);
1611          }   
1612          break;
1613       case 1:
1614         if(!gSystem->AccessPathName(module)){
1615           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
1616           gSystem->Exec(Form("rm -rf %s",module));
1617         }
1618          result = gProof->UploadPackage(module);
1619          if (result<0) {
1620             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1621             if (result<0) {
1622                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1623                return kFALSE;
1624             }
1625          }   
1626          result = gProof->EnablePackage(module);
1627          break;
1628       default:
1629          return kFALSE;
1630    }         
1631    if (result < 0) {
1632       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
1633       return kFALSE;
1634    }
1635    return kTRUE;
1636 }           
1637
1638
1639
1640 //______________________________________________________________________________
1641 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
1642 {
1643 // Load a module library in a given mode. Reports success.
1644    Int_t imode = -1;
1645    Int_t result = -1;
1646    if (!strcmp(mode, "LOCAL")) imode = 0;
1647    if (!strcmp(mode, "PROOF")) imode = 1;
1648    if (!strcmp(mode, "GRID"))  imode = 2;
1649    TString ssource(source);
1650    TString basename = gSystem->BaseName(ssource.Data());
1651    if (!ssource.Length()) {
1652       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
1653       return kFALSE;
1654    }   
1655    // we have a source code so compile it
1656    if (ssource.EndsWith(".cxx")) {
1657      // need to copy it here other wise the path is also used on grid...
1658      ssource.Remove(ssource.Index(".cxx"));
1659      basename.Remove(basename.Index(".cxx"));
1660      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
1661      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
1662      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
1663      // Path to code
1664      // only needed for local compilation, in grid and proof mode 
1665      // the task headers are uploaded 
1666      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
1667      // Printf("LoadSources:: Including path %s",path.Data());
1668      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
1669      Printf("LoadSources:: Loading...  path %s",basename.Data());
1670      switch (imode) {
1671      case 0:
1672        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1673        break;
1674      case 1:
1675        result = gProof->LoadMacro(Form("%s.cxx++g",basename.Data()));
1676        break;
1677      case 2:
1678        result = gROOT->LoadMacro(Form("%s.cxx++g",basename.Data()));
1679        if (rec){
1680          // what we want to compile
1681          anaSources += Form("%s.cxx ",basename.Data()); 
1682          // what we need as input...
1683          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
1684        }
1685        break;
1686      default:
1687        return kFALSE;
1688      }
1689    } 
1690    if (result < 0) {
1691       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
1692       return kFALSE;
1693    }
1694    return kTRUE;
1695 }           
1696
1697
1698 //______________________________________________________________________________
1699 TChain *CreateChain(const char *mode, const char *plugin_mode)
1700 {
1701 // Create the input chain
1702    Int_t imode = -1;
1703    if (!strcmp(mode, "LOCAL")) imode = 0;
1704    if (!strcmp(mode, "PROOF")) imode = 1;
1705    if (!strcmp(mode, "GRID"))  imode = 2;
1706    TChain *chain = NULL;
1707    // Local chain
1708    switch (imode) {
1709       case 0:
1710          if (iAODanalysis) {
1711             if (!kLocalXMLDataset.Length()) {
1712                // Local AOD
1713                chain = new TChain("aodTree");
1714                TString line;
1715                ifstream in;
1716                in.open(kLocalDataList.Data());
1717                Int_t ic = 0;
1718                while (in.good()) {
1719                  in >> line;
1720                  if (line.Length() == 0) continue;
1721                  Printf("%d adding %s",ic,line.Data());
1722                  chain->Add(line.Data());
1723                  ic++;
1724                }       
1725             } else {
1726                // Interactive AOD
1727                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
1728             }
1729          } else {      
1730            if (!kLocalXMLDataset.Length()) {
1731              // Local ESD
1732              chain = new TChain("esdTree");
1733              TString line;
1734              ifstream in;
1735              in.open(kLocalDataList.Data());
1736              while (in.good()) {
1737                in >> line;
1738                if (line.Length() == 0) continue;
1739                cout << " line = " << line << endl;
1740                chain->Add(line.Data());
1741              }       
1742            } else {
1743              // Interactive ESD
1744                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
1745            }   
1746          }
1747          break;
1748       case 1:
1749          break;
1750       case 2:
1751          if (kPluginUse) {
1752 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1753 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1754          } else {
1755             TString           treeName = "esdTree";
1756             if (iAODanalysis) treeName = "aodTree";
1757             chain = CreateChainSingle("wn.xml", treeName);
1758          }
1759          break;      
1760       default:   
1761    }
1762    if (chain && chain->GetNtrees()) return chain;
1763    return NULL;
1764 }   
1765
1766 //______________________________________________________________________________
1767 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1768 {
1769    printf("*******************************\n");
1770    printf("*** Getting the ESD Chain   ***\n");
1771    printf("*******************************\n");
1772    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1773
1774    if (!myCollection) {
1775       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1776       return NULL ;
1777    }
1778
1779    TChain* chain = new TChain(treeName);
1780    myCollection->Reset() ;
1781    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1782    chain->ls();
1783    return chain;
1784 }
1785
1786 //______________________________________________________________________________
1787 Int_t SetupPar(char* pararchivename)
1788 {
1789    if (!pararchivename || !strlen(pararchivename)) return -1;
1790    char processline[1024];
1791    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1792       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1793          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1794         TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1795                   Form("%s.par",pararchivename));
1796       } else {
1797          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
1798          return -1;
1799       }   
1800    }
1801    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
1802    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1803
1804    TString ocwd = gSystem->WorkingDirectory();
1805    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1806         
1807    // check for BUILD.sh and execute
1808    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1809       printf("*******************************\n");
1810       printf("*** Building PAR archive    ***\n");
1811       printf("*******************************\n");          
1812       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
1813          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
1814          return -1;
1815       }
1816    }
1817
1818         // check for SETUP.C and execute
1819         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1820             printf("*******************************\n");
1821             printf("*** Setup PAR archive       ***\n");
1822             printf("*******************************\n");
1823             gROOT->Macro("PROOF-INF/SETUP.C");
1824         }       
1825         if (!gSystem->ChangeDirectory(ocwd.Data())){
1826           Error("Change back directory",Form("Cannot change to %s",ocwd.Data()));
1827           return -1;
1828         }
1829    return 0;
1830 }
1831
1832 //______________________________________________________________________________
1833 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1834 {
1835 // Check if user has a valid token, otherwise make one. This has limitations.
1836 // One can always follow the standard procedure of calling alien-token-init then
1837 //   source /tmp/gclient_env_$UID in the current shell.
1838 //   if (!AliAnalysisGrid::CreateToken()) return NULL;
1839    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1840 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1841    plugin->SetRunMode(plugin_mode);
1842    if (kPluginUseProductionMode) plugin->SetProductionMode();
1843    plugin->SetJobTag(kJobTag);
1844    plugin->SetNtestFiles(1);
1845 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1846 // Set versions of used packages
1847    plugin->SetAPIVersion("V1.1x");
1848    //   plugin->SetAPIVersion("V1.0x");
1849 //   plugin->SetAPIVersion("V2.4");
1850    plugin->SetROOTVersion(kPluginRootVersion);
1851    plugin->SetAliROOTVersion(kPluginAliRootVersion);
1852 // Declare input data to be processed.
1853 // Method 1: Create automatically XML collections using alien 'find' command.
1854 // Define production directory LFN
1855    plugin->SetGridDataDir(kGridDatadir.Data());
1856 // Set data search pattern
1857    if (iAODanalysis) plugin->SetDataPattern(" *AliAOD.Jets.root");
1858    //   else              plugin->SetDataPattern(Form(" %s/*/*ESD.tag.root",kGridPassPattern.Data()));
1859    else              plugin->SetDataPattern(Form(" %s/*/*AliESDs.root",kGridPassPattern.Data()));
1860 // ...then add run numbers to be considered
1861 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
1862    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
1863      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
1864      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
1865    }   
1866
1867    if(kGridLocalRunList.Length()>0){
1868      ifstream in1;
1869      in1.open(kGridLocalRunList.Data());
1870      int iRun;
1871      int icount = 0;
1872      /*
1873      char c;
1874      char cLine[250];
1875      while(!in1.eof()){
1876        c = in1.get();
1877        if ( (c >= '0') && (c <= '9') )
1878          {
1879            in1.putback (c)s;
1880            in1>>iRun;
1881            Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1882            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1883        }
1884      else
1885        {
1886          in1.putback (c);
1887          in1.getline(cLine,250);
1888
1889        }
1890      }
1891      */
1892      
1893      Int_t nRun = 0;
1894
1895      // just use run numbers, negatives will be excluded
1896      while(in1>>iRun){
1897        if(iRun>=0){
1898          if(iRun>=0&&nRun>=kGridOffsetRunFromList&&(nRun<kGridMaxRunsFromList)){
1899            Printf("AnalysisTrainPWG4Jets Adding run number from File %d: %s",nRun,Form(kGridRunPattern.Data(),iRun));
1900            plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1901
1902          }
1903          else{
1904            Printf("AnalysisTrainPWG4Jets Skipping run number from File %d: %d",nRun, iRun);
1905          }
1906          nRun++;
1907        }
1908        else{
1909          Printf("AnalysisTrainPWG4Jets Skipping run number from File %d: %d",nRun, iRun);
1910        }
1911      }
1912    }
1913
1914 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1915 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1916 // XML collections added via this method can be combined with the first method if
1917 // the content is compatible (using or not tags)
1918 //   plugin->AddDataFile("tag.xml");
1919 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1920 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1921    TString alien_workdir = "";
1922    
1923    if (iAODanalysis)  alien_workdir += "analysisAOD";
1924    else               alien_workdir += "analysisESD";    
1925    if(kGridDataSet.Length()>0)alien_workdir += Form("/%s",kGridDataSet.Data());
1926    plugin->SetGridWorkingDir(alien_workdir.Data());
1927
1928    // Declare alien output directory. Relative to working directory.
1929    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1930    plugin->SetGridOutputDir(kGridOutdir);
1931
1932    // Add external packages
1933    if (iJETAN||iDIJETAN) {
1934       plugin->AddExternalPackage("boost::v1_43_0");
1935       plugin->AddExternalPackage("cgal::v3.6");
1936       plugin->AddExternalPackage("fastjet::v2.4.2");
1937    }   
1938
1939
1940    // set extra libs before par file compilation
1941    anaLibs += kGridExtraFiles;
1942    anaLibs     = anaLibs.Strip();   
1943    Printf("anaLibs %s",anaLibs.Data());
1944    Printf("anaLibsExtra %s",anaLibsExtra.Data());
1945
1946    if (anaLibs.Length())          plugin->SetAdditionalLibs(anaLibs.Data());
1947    if (anaLibsExtra.Length())     plugin->SetAdditionalRootLibs(anaLibsExtra.Data());
1948
1949    TString ana_sources = "";
1950    TString ana_add = "";
1951    if (kUsePAR && anaPars.Length()) {
1952       printf("%s\n", anaPars.Data());
1953       TObjArray *arr;
1954       TObjString *objstr;
1955       arr = anaPars.Tokenize(" ");
1956       TIter next(arr);
1957       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1958       delete arr;
1959    } 
1960    
1961 // Declare the analysis source files names separated by blancs. To be compiled runtime
1962 // using ACLiC on the worker nodes.
1963    ana_sources = anaSources.Strip();
1964 // Declare all libraries (other than the default ones for the framework. These will be
1965 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1966
1967    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1968    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
1969    // Declare the output file names separated by blancs.
1970    // (can be like: file.root or file.root@ALICE::Niham::File)
1971    plugin->SetMergeExcludes(kGridMergeExclude);
1972    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
1973    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
1974    plugin->SetMergeViaJDL(kPluginMergeViaJDL);
1975    // Use fastread option
1976    plugin->SetFastReadOption(kPluginFastReadOption);
1977    // UseOverwrite mode
1978    plugin->SetOverwriteMode(kPluginOverwriteMode); 
1979    // Optionally define the files to be archived.
1980    //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1981    plugin->SetOutputToRunNo(kPluginOutputToRunNumber);     // write the output to subdirs named after run number
1982    
1983    // Put default output files to archive
1984    TString listhists = "";
1985    TString listaods  = "";
1986    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1987    TIter next(mgr->GetOutputs());
1988    AliAnalysisDataContainer *output;
1989    while ((output=(AliAnalysisDataContainer*)next())) {
1990       const char *filename = output->GetFileName();
1991       if (!(strcmp(filename, "default"))) {
1992         if (!mgr->GetOutputEventHandler()) continue;
1993          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
1994          if (listaods.Length()) listaods += " ";
1995          listaods += filename;
1996       } else {
1997         if(!listhists.Contains(filename)){
1998           if (listhists.Length()) listhists += " ";
1999           listhists += filename;
2000         }
2001       }
2002    }
2003
2004    if (mgr->GetExtraFiles().Length()) {
2005      if (listaods.Length()) listaods += " ";
2006      listaods += mgr->GetExtraFiles();
2007    }
2008
2009    // if we do not fill the aod we do not need to store it
2010    //   kGridMergeExclude = listaods;
2011    
2012    if(kSaveAOD>=0){
2013      TString outputFiles =  "";
2014      outputFiles += mgr->GetExtraFiles();
2015      if (listhists.Length()) outputFiles += " ";
2016      outputFiles += listhists;
2017      plugin->SetDefaultOutputs(kFALSE);
2018      Printf("%s:%d Starting with the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
2019      // remove
2020      // no harm done when we try to remove something that is not there :)
2021      if(!(kSaveAOD&(1<<0))){
2022        outputFiles.ReplaceAll("AliAOD.root ","");
2023        listaods.ReplaceAll("AliAOD.root ","");
2024      }
2025      if(!(kSaveAOD&(1<<1))){
2026        if(kDeltaAODJetName.Length())outputFiles.ReplaceAll(kDeltaAODJetName.Data(),"");
2027        if(kDeltaAODJetName.Length())listaods.ReplaceAll(kDeltaAODJetName.Data(),"");
2028        
2029      }
2030      if(!(kSaveAOD&(1<<2))){
2031        if(kDeltaAODPartCorrName.Length())outputFiles.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
2032        if(kDeltaAODPartCorrName.Length())listaods.ReplaceAll(kDeltaAODPartCorrName.Data(),"");
2033      }
2034      if(!(kSaveAOD&(1<<3))){
2035        if(kDeltaAODJCORRANName.Length())outputFiles.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
2036        if(kDeltaAODJCORRANName.Length())listaods.ReplaceAll(kDeltaAODJCORRANName.Data(),"");
2037      }
2038      
2039      // 
2040      plugin->SetDefaultOutputs(kFALSE);
2041      Printf("%s:%d Saving the files %s",(char*)__FILE__,__LINE__,outputFiles.Data());
2042      plugin->SetOutputFiles(outputFiles.Data());
2043    }
2044
2045    TString outputArchive;
2046    outputArchive = Form("log_archive.zip:std*@%s","disk=1");
2047    listaods.ReplaceAll(" ", ",");
2048    listhists.ReplaceAll(" ", ",");
2049    if (listhists.Length()){
2050      outputArchive += " ";
2051      outputArchive += "root_archive.zip:";
2052      outputArchive += listhists;
2053      if (listaods.Length()){
2054        outputArchive += ",";
2055        outputArchive += listaods;
2056      }
2057      outputArchive += Form("@%s", kGridOutputStorages.Data());
2058    }
2059    else{
2060      
2061      if (listaods.Length()){
2062        // we have only aod'ish output
2063        outputArchive += " ";
2064        outputArchive += "root_archive.zip:";
2065        outputArchive += listaods;
2066        outputArchive += Form("@%s", kGridOutputStorages.Data());
2067      }
2068      else{
2069        // no other outputs than std..
2070       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
2071      }
2072    }
2073
2074    plugin->SetDefaultOutputs(kFALSE);
2075    plugin->SetOutputArchive(outputArchive);
2076
2077
2078    // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
2079    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
2080    // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
2081    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
2082    // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
2083    //   plugin->SetMaxInitFailed(5);
2084    // Optionally resubmit threshold.
2085    // plugin->SetMasterResubmitThreshold(90);
2086    // Optionally set time to live (default 30000 sec)
2087    plugin->SetTTL(54000); // 15h...
2088    // Optionally set input format (default xml-single)
2089    plugin->SetInputFormat("xml-single");
2090    // Optionally modify the name of the generated JDL (default analysis.jdl)
2091    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
2092    // Optionally modify the executable name (default analysis.sh)
2093    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
2094    // Optionally modify job price (default 1)
2095    plugin->SetPrice(1);      
2096    // Optionally modify split mode (default 'se')    
2097    plugin->SetSplitMode("se");
2098    return plugin;
2099 }
2100
2101 //______________________________________________________________________________
2102 void WriteConfig()
2103 {
2104 // Write train configuration in a file. The file name has the format:
2105 // train_[trainName]_ddMonthyyyy_time.C
2106    if (kUseDate) {
2107       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
2108       ifstream fdate("date.tmp");
2109       if (!fdate.is_open()) {
2110          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
2111          return;
2112       }
2113       const char date[64];
2114       fdate.getline(date,64);
2115       fdate.close();
2116       gSystem->Exec("rm date.tmp");
2117       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
2118    } else {
2119       kTrainName = Form("train_%s", kTrainName.Data());
2120    }   
2121    TString cdir = gSystem->WorkingDirectory();
2122    gSystem->MakeDirectory(kTrainName);
2123    gSystem->ChangeDirectory(kTrainName);
2124    ofstream out;
2125    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
2126    if (out.bad()) {
2127       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
2128       return;
2129    }
2130    out << "{" << endl;
2131    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
2132    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
2133    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
2134    if (kProofUseAFPAR) 
2135       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
2136    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
2137    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
2138    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
2139    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
2140    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
2141    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
2142    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
2143    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
2144    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
2145    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
2146    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
2147    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
2148    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
2149    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
2150    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
2151    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
2152    out << "   kUseMC           = " << kUseMC << ";" << endl;
2153    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
2154    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
2155    out << "   kUseTR           = " << kUseTR << ";" << endl;
2156    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
2157    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
2158    out << "   // Analysis modules" << endl;
2159    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
2160    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
2161    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
2162    out << "   iJETAN          = " << iJETAN << ";" << endl;
2163    out << "// Configuration fot the wagons" << endl;
2164    out << "}" << endl;
2165    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
2166    gSystem->ChangeDirectory(cdir);
2167 }   
2168
2169 //______________________________________________________________________________
2170 Bool_t LoadConfig(const char *filename)
2171 {
2172 // Read train configuration from file
2173    if (gSystem->AccessPathName(filename)) {
2174       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
2175       return kFALSE;
2176    }   
2177    gROOT->ProcessLine(Form(".x %s", filename));
2178    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
2179    return kTRUE;
2180 }
2181
2182 Bool_t PatchJDL(){
2183   Printf(">>> Patching JDL");
2184   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
2185   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
2186   TGridJDL *jdl = gridHandler->GetGridJDL();
2187   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
2188   gridHandler->WriteJDL(kFALSE);
2189   Printf("<<<  Patching JDL");
2190   return kTRUE;
2191 }
2192
2193 Bool_t PatchAnalysisMacro(){
2194   Printf(">>> Patching AnalysisMacro");
2195   gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
2196
2197   ifstream in1; 
2198   in1.open(Form("%s.C_tmp", kTrainName.Data()));
2199   char cLine[250];
2200   TString st;
2201   while(in1.getline(cLine,250)){
2202     st += cLine;
2203     st += "\n";
2204   }
2205   Int_t index= -1;
2206   index = st.Index("gSystem->Load(\"libPhysics\");");
2207   index += strlen("gSystem->Load(\"libPhysics\");");
2208   /*
2209     TObjArray *arr;
2210     TObjString *objstr;
2211     arr = anaLibs.Tokenize(" ");
2212     TIter next(arr);
2213
2214     add += "\n\n // added by CKB \n";
2215     while ((objstr=(TObjString*)next())){
2216       if(objstr->GetString().Contains("PWG3"))continue;
2217       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
2218     }
2219     delete arr; 
2220     */
2221     //    add += Form("AliLog::SetGlobalLogLevel(%d);\n",AliLog::GetGlobalLogLevel());
2222   TString add = "";
2223
2224   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2225   add += "\n\n // added by CKB \n";
2226   if(kErrorIgnoreLevel>0)add += Form("gErrorIgnoreLevel = %d;\n",kErrorIgnoreLevel);
2227   add += "\n gSystem->AddIncludePath(\"./\"); \n";
2228   add += "\n gSystem->SetFPEMask(); \n";
2229
2230
2231   if(gGrid&&kPluginAliRootVersion.Length()==0){
2232     /*
2233     add += "\n // Dirty hack for TRD reference data \n";
2234     add += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
2235     add += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
2236     add += "\"); \n";
2237     */
2238   }
2239
2240   add += "// BKC \n\n";
2241   st.Insert(index,add.Data());
2242
2243   if(kUseDebug){
2244     //    st.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
2245   }
2246
2247   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
2248     index = st.Index("gSystem->AddIncludePath(\"-I$"); // uncommen $ALICE_ROOT include for par files
2249     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2250     st.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
2251   }
2252
2253   if(AliLog::GetGlobalLogLevel()==AliLog::kFatal){
2254     index = st.Index("AliLog::SetGlobal"); // ncomment setting of log level, do my own
2255     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2256     st.Insert(index,"AliLog::SetGlobalLogLevel(AliLog::kFatal);// CKB \n  // CKB comment out for own setting \n  //");
2257   }
2258
2259   ofstream out;
2260   out.open(Form("%s.C", kTrainName.Data()));
2261   if (out.bad()) {
2262     return kFALSE;
2263   }
2264   out << st << endl;
2265   Printf("<<< Patching AnalysisMacro");
2266
2267
2268
2269
2270
2271   Printf(">>> Patching Merge Macro");
2272   gSystem->Exec(Form("mv %s_merge.C %s_merge.C_tmp",kTrainName.Data(),kTrainName.Data()));
2273
2274   ifstream in2; 
2275   in2.open(Form("%s_merge.C_tmp", kTrainName.Data()));
2276   TString st2;
2277   while(in2.getline(cLine,250)){
2278     st2 += cLine;
2279     st2 += "\n";
2280   }
2281   index = st2.Index("gSystem->Load(\"libPhysics\");");
2282   index += strlen("gSystem->Load(\"libPhysics\");");
2283   TString add2 = "";
2284   add2 += "\n gSystem->AddIncludePath(\"./\"); \n";
2285   if(gGrid&&kPluginAliRootVersion.Length()==0){
2286     /*
2287     add2 += "\n // Dirty hack for TRD reference data \n";
2288     add2 += "\n gSystem->Setenv(\"ALICE_ROOT\",\"";
2289     add2 += Form("alien://%s/rootfiles/",gGrid->GetHomeDirectory());
2290     add2 += "\"); \n";
2291     */
2292   }
2293   add2 += "// BKC \n\n";
2294   if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2295   st2.Insert(index,add.Data());
2296
2297
2298   if(kUseDebug){
2299     //    st2.Insert(index,"\n gROOT->ProcessLine(\".trace\"); // CKB \n");
2300   }
2301
2302   if(kUseCPAR&&kPluginAliRootVersion.Length()==0){
2303     index = st2.Index("gSystem->AddIncludePath(\"-I$"); // uncomment $ALICE_ROOT include for par files
2304     if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2305     st2.Insert(index,"// CKB comment out whehn no aliroot is provided \n //");
2306   }
2307
2308   // do not exclude the extra files from merign, this is done explicitly in this train script
2309   //  index = st2.Index("mergeExcludes +="); // uncommen $ALICE_ROOT include for par files
2310   //  if(index<0)Printf("%s:%d index out of bounds",(char*)__FILE__,__LINE__);
2311   // st2.Insert(index,"// CKB comment out, handled explicitly by the train macro \n //");
2312
2313
2314   ofstream out2;
2315   out2.open(Form("%s_merge.C", kTrainName.Data()));
2316   if (out2.bad()) {
2317     return kFALSE;
2318   }
2319   out2 << st2 << endl;
2320   Printf("<<< Patching Merging Macro");
2321
2322
2323
2324   return kTRUE;
2325
2326 }