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