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