]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG4/macros/AnalysisTrainPWG4Jets.C
Added new package names
[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] AnalysisTrainPWG4Jets("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
36 //== general input and output variables
37 Int_t       iAODanalysis       = 1;      // Analysis on input AOD's
38 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
39 Int_t       iESDfilter         = 0;      // ESD to AOD filter (barrel + muon tracks)
40 Bool_t      kUseKinefilter     = kFALSE; // use Kinematics filter
41 Bool_t      kUseMuonfilter     = kFALSE; // use Kinematics filter
42 TString     kCommonOutputFileName = "PWG4_JetTasksOutput.root";
43
44
45 //== general process variables
46
47 // ### Other flags to steer the analysis
48 //==============================================================================
49 Bool_t      kUseDate            = kFALSE; // use date in train name
50 Bool_t      kUseDebug           = kTRUE; // activate debugging
51 Int_t       kUseSysInfo         = 0; // activate debugging
52 Bool_t      kUseMC              = kTRUE;  // use MC info
53 Bool_t      kIsMC               = kTRUE;  // is MC info, if false it overwrites Use(AOD)MC
54 Bool_t      kUseAODMC           = kTRUE;  // use MC infA
55 Bool_t      kUseESDTags         = kFALSE; // use ESD tags for selection
56 Bool_t      kUseTR              = kFALSE;  // use track references
57 Bool_t      kUseAODTags         = kFALSE;  // use AOD tags
58 Bool_t      kSaveTrain          = kFALSE;  // save train configuration as: 
59
60 // ### Analysis modules to be included. Some may not be yet fully implemented.
61 //==============================================================================
62 Int_t       iJETAN             = 1;      // Jet analysis (PWG4) // 1 write standard 2 write non-standard jets, 3 wrtie both
63 Int_t       iDIJETAN           = 1;
64 Int_t       iPWG1QASym         = 0;      // Eva's QA task compiled on the fly...
65 Int_t       iPWG4JetTasks      = 0;      // all jet tasks flag for lib laoding
66 Int_t       iPWG4JetServices   = 0;      // jet spectrum analysis
67 Int_t       iPWG4JetSpectrum   = 0;      // jet spectrum analysis
68 Int_t       iPWG4UE            = 0;      // Underlying Event analysis
69 Int_t       iPWG4PtQAMC        = 0;      // Marta's QA tasks 
70 Int_t       iPWG4PtSpectra     = 0;      // Marta's QA tasks 
71 Int_t       iPWG4PtQATPC       = 0;      // Marta's QA tasks 
72 Int_t       iPWG4ThreeJets     = 0;      // Sona's thrust task
73 Int_t       iPWG4PartCorr      = 0;      // Gustavo's part corr analysis
74 Int_t       iPWG4GammaConv     = 0;      // Gamma Conversio
75 Int_t       kHighPtFilterMask  = 16;     // change depending on the used AOD Filter
76 TString     kDeltaAODJetName   = "AliAOD.Jet.root";     
77 TString     kDeltaAODPartCorrName   = "deltaAODPartCorr.root";     
78
79
80 //==============================================================================
81 // ### PROOF Steering varibales
82 //==============================================================================
83 //== proof setup variables
84 TString     kProofCluster      = "alicecaf.cern.ch";
85 Bool_t      kProofUseAFPAR     = kFALSE;  // use AF special par file
86 TString     kProofAFversion          = "AF-v4-17";
87 //== proof input and output variables
88 TString     kProofDataSet      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
89 Bool_t      kProofSaveToAlien   = kFALSE; // save proof outputs in AliEn train_[trainName]_ddMonthyyyy_time.C
90 TString     kProofOutdir       = "";
91 Bool_t      kProofClearPackages = kFALSE;
92 Int_t       kProofEvents = 10000;
93 Int_t       kProofOffset = 0;
94 //== proof process variables
95
96
97 //==============================================================================
98 // ### Grid plugin Steering varibiables
99 //==============================================================================
100 //== grid plugin setup variables
101 Bool_t      kPluginUse         = kTRUE;   // do not change
102 Bool_t      kPluginUseProductionMode  = kFALSE;   // use the plugin in production mode
103 TString     kPluginRootVersion       = "v5-25-04-1";  // *CHANGE ME IF MORE RECENT IN GRID*
104 TString     kPluginAliRootVersion    = "v4-18-14-AN";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
105 // TString kPluginExecutableCommand = "root -b -q";
106 TString     kPluginExecutableCommand = "source /Users/kleinb/setup_32bit_aliroot_trunk_clean_root_trunk.sh; alienroot -b -q ";
107 // == grid plugin input and output variables
108 TString     kGridDatadir      = "/alice/sim/PDC_08b/LHC09a1/AOD/";
109 TString     kGridLocalRunList = "";
110 TString     kGridOutdir       = ""; // AliEn output directory. If blank will become output_<kTrainName>
111 Int_t       kGridRunRange[2]       =  {0, -1}; // Set the run range
112 TString     kGridRunPattern        = "%03d"; // important for leading zeroes!!
113 TString     kGridPassPattern       = "";
114 TString     kGridExtraFiles        = ""; // files that will be added to the input list in the JDL...
115 Int_t       kGridMaxMergeFiles      = 50; // Number of files merged in a chunkgridrunragn
116 TString     kGridMergeExclude       = "AliAOD.root"; // Files that should not be merged
117 TString     kGridOutputStorages      = "ALICE::NIHAM::File,ALICE::CNAF::SE,ALICE::FZK::SE,ALICE::GSI::SE,ALICE::Legnaro::SE"; // Make replicas on the storages
118 // == grid process variables
119 Int_t       kGridRunsPerMaster     = 100; // Number of runs per master job
120 Int_t       kGridFilesPerJob       = 200; // Maximum number of files per job (gives size of AOD)
121
122 //==============================================================================
123 // ### Local Steering variables
124 //==============================================================================
125 //== local setup variables
126 //== local input and output variables
127 TString     kLocalXMLDataset   = ""; // Change local xml dataset for local interactive analysis
128 TString     kLocalDataList   = "local_deltaaod.txt"; // Change local xml dataset for local interactive analysis
129 // == local process variables
130
131
132
133 // Temporaries.
134 TString anaPars = "";
135 TString anaLibs = "";
136 TString anaSources = "";
137 // Function signatures
138 class AliAnalysisAlien;
139
140 //______________________________________________________________________________
141 void AnalysisTrainPWG4Jets(const char *analysis_mode="local", 
142                            const char *plugin_mode="",
143                            const char *config_file="",Int_t iOffset = 0)
144 {
145 // Main analysis train macro. If a configuration file is provided, all parameters
146 // are taken from there but may be altered by CheckModuleFlags.
147    if (strlen(config_file) && !LoadConfig(config_file)) return;
148    if(iOffset)kProofOffset = iOffset;
149    TString smode(analysis_mode);
150    smode.ToUpper();
151    if (kSaveTrain)WriteConfig();
152    // Check compatibility of selected modules
153    CheckModuleFlags(smode);
154
155    printf("==================================================================\n");
156    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", kTrainName.Data(),smode.Data());
157    printf("==================================================================\n");
158    printf("=  Configuring analysis train for:                               =\n");
159    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
160    else              printf("=  ESD analysis                                                  =\n");
161    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
162    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
163    printf("==================================================================\n");
164    printf(":: use MC truth      %d\n", (UInt_t)kUseMC);
165    printf(":: use KINE filter   %d\n", (UInt_t)kUseKinefilter);
166    printf(":: use track refs    %d\n", (UInt_t)kUseTR);
167    printf(":: use tags          %d\n", (UInt_t)kUseESDTags);
168    printf(":: use AOD tags      %d\n", (UInt_t)kUseAODTags);
169    printf(":: use debugging     %d\n", (UInt_t)kUseDebug);
170    printf(":: use PAR files     %d\n", (UInt_t)kUsePAR);
171    printf(":: use AliEn plugin  %d\n", (UInt_t)kPluginUse);
172    printf(":: use PWG1 QA sym       %d\n", iPWG1QASym);
173    printf(":: use PWG4 Jet tasks    %d\n",iPWG4JetTasks);
174    printf(":: use PWG4 Jet Services %d\n",iPWG4JetServices);     
175    printf(":: use PWG4 Jet Spectrum %d\n",iPWG4JetSpectrum);
176    printf(":: use PWG4 UE           %d \n",iPWG4UE); 
177    printf(":: use PWG4 Pt QA MC     %d\n",iPWG4PtQAMC);
178    printf(":: use PWG4 Pt Spectra   %d\n",iPWG4PtSpectra);
179    printf(":: use PWG4 Pt QA TPC    %d\n",iPWG4PtQATPC);     
180    printf(":: use PWG4 Three Jets   %d\n",iPWG4ThreeJets);
181    printf(":: use PWG4 Part Corr    %d\n",iPWG4PartCorr);
182    printf(":: use PWG4 Gamma Conv   %d\n",iPWG4GammaConv);
183    printf(":: use HighPt FilterMask %d\n",kHighPtFilterMask);    
184
185
186    //==========================================================================
187    // Connect to back-end system
188    if (!Connect(smode)) {
189       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
190       return;
191    }   
192
193    // Load common libraries and set include path
194    if (!LoadCommonLibraries(smode)) {
195       ::Error("AnalysisTrain", "Could not load common libraries");
196       return;
197    }
198     
199    // Make the analysis manager and connect event handlers
200    AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
201    if (kCommonOutputFileName.Length()>0)mgr->SetCommonFileName(kCommonOutputFileName.Data());
202    if (kProofSaveToAlien) mgr->SetSpecialOutputLocation(kProofOutdir);
203    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
204    if (kUseSysInfo)mgr->SetNSysInfo(kUseSysInfo);
205    // Load analysis specific libraries
206    if (!LoadAnalysisLibraries(smode)) {
207       ::Error("AnalysisTrain", "Could not load analysis libraries");
208      return;
209    }   
210
211    // Create input handler (input container created automatically)
212    if (iAODanalysis) {
213    // AOD input handler
214       AliAODInputHandler *aodH = new AliAODInputHandler();
215       mgr->SetInputEventHandler(aodH);
216    } else {   
217    // ESD input handler
218       AliESDInputHandler *esdHandler = new AliESDInputHandler();
219       if (kUseESDTags) esdHandler->SetReadTags();
220       mgr->SetInputEventHandler(esdHandler);       
221    }
222    // Monte Carlo handler
223    if (kUseMC && !iAODanalysis) {
224       AliMCEventHandler* mcHandler = new AliMCEventHandler();
225       mgr->SetMCtruthEventHandler(mcHandler);
226       mcHandler->SetReadTR(kUseTR); 
227    }   
228    // AOD output container, created automatically when setting an AOD handler
229    if (iAODhandler) {
230       // AOD output handler
231       AliAODHandler* aodHandler   = new AliAODHandler();
232       aodHandler->SetOutputFileName("AliAOD.root");
233       aodHandler->SetFillAOD(kFillAOD);
234       
235       mgr->SetOutputEventHandler(aodHandler);
236
237       if (iAODanalysis) {
238
239         //         aodHandler->SetCreateNonStandardAOD();
240         //      if (iJETAN)aodHandler->SetOutputFileName(kDeltaAODJetName.Data());
241       } 
242       AliAnalysisDataContainer * cout_aod = mgr->GetCommonOutputContainer();
243       cout_aod->SetSpecialOutput();
244    }
245    // Debugging if needed
246    if (kUseDebug) mgr->SetDebugLevel(3);
247
248    //==========================================================================
249    // Create the chain. In this example it is created only from ALIEN files but
250    // can be done to work in batch or grid mode as well.
251    TChain *chain = CreateChain(smode, plugin_mode);
252         
253    //==========================================================================
254    // Load the tasks configuration macros for all wagons. These files are supposed now to be
255    // in the current workdir, but in AliEn they will be in the file catalog, 
256    // mapped from AliRoot and pecified in the jdl input list.
257     
258    // For now connection to top input container and common AOD output container
259    // is done in this macro, but in future these containers will be connected
260    // from each task configuration macro.
261
262    if (iESDfilter && !iAODanalysis) {
263       //  ESD filter task configuration.
264       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
265       AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(kUseKinefilter,kUseMuonfilter);
266    }   
267
268    // AOD tags
269    if (kUseAODTags) {
270       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
271       mgr->AddTask(tagTask);
272       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
273                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
274       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
275       mgr->ConnectOutput(tagTask, 1, coutTags);
276    }   
277     
278     // Jet analysis
279    if (iJETAN) {
280       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
281       AliAnalysisTaskJets *taskjets = 0;
282       if(iJETAN&1)taskjets = AddTaskJets(kHighPtFilterMask); 
283       if(iJETAN&2)AddTaskJetsDelta(kDeltaAODJetName.Data(),kHighPtFilterMask,kUseAODMC); 
284       if (!taskjets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
285    }
286
287    if (iDIJETAN) {
288       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskDiJets.C");
289       AliAnalysisTaskDiJets *taskdijets = 0;
290       taskdijets = AddTaskDiJets(); 
291       if (!taskdijets) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
292    }
293
294        
295    if(iPWG1QASym){
296      gROOT->LoadMacro("$ALICE_ROOT/prod/acrcaf/qa_pp/AddTaskQAsym.C");
297      AliAnalysisTaskQASym *taskQASym = AddTaskQAsym(-1);
298      if (!taskQASym) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQASym cannot run for this train conditions - EXCLUDED");
299
300    }
301
302    if(iPWG4JetServices){
303      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetServices.C");
304      AliAnalysisTaskJetServices *taskjetServ = 0;
305      taskjetServ = AddTaskJetServices();
306      if (!taskjetServ) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetServices cannot run for this train conditions - EXCLUDED");
307      if(kGridRunRange[0]>0)taskjetServ->SetRunRange(kGridRunRange[0],kGridRunRange[1]);
308      else taskjetServ->SetRunRange(104000,105000);
309      if(!kIsMC) taskjetServ->SetRealData(kTRUE);
310    }
311
312
313    if(iPWG4JetSpectrum){
314      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJetSpectrum2.C");
315      AliAnalysisTaskJetSpectrum2 *taskjetSpectrum = 0;
316      if(iPWG4JetSpectrum&1)taskjetSpectrum = AddTaskJetSpectrum2("jets","",kHighPtFilterMask);      
317      if (!taskjetSpectrum) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskJetSpectrum2 cannot run for this train conditions - EXCLUDED");
318      if(iPWG4JetSpectrum&2)AddTaskJetSpectrum2Delta(kHighPtFilterMask,kUseAODMC);
319      if(kUseMC)taskjetSpectrum->SetAnalysisType( AliAnalysisTaskJetSpectrum2::kAnaMCESD);
320      taskjetSpectrum->SetDebugLevel(1);
321    }
322
323    if(iPWG4UE){
324      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskUE.C");
325      AliAnalysisTaskUE *taskUE = 0;
326      if(iPWG4UE&1)taskUE = AddTaskUE(); 
327      if(iPWG4UE&2){
328        taskUE = AddTaskUE("jetsAOD_CDF07"); 
329        taskUE = AddTaskUE("jetsAOD_UA1LO07"); 
330      }
331      if (!taskUE) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskUE cannot run for this train conditions - EXCLUDED");
332    }
333
334    if(iPWG4ThreeJets){
335      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskThreeJets.C");
336      AliAnalysisTaskThreeJets *taskThree = AddTaskThreeJets();
337      if(!taskThree)::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskThreets cannot run for this train conditions - EXCLUDED");
338    }
339
340    if(iPWG4PtQAMC){
341      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQAMC.C");
342      AliPWG4HighPtQAMC *taskQAMC = AddTaskPWG4HighPtQAMC();
343      if (!taskQAMC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQAMC cannot run for this train conditions - EXCLUDED");
344    }
345
346    if(iPWG4PtQATPC){
347      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtQATPConly.C");
348      AliPWG4HighPtQATPConly *taskQATPC = AddTaskPWG4HighPtQATPConly();
349      if (!taskQATPC) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskQATPC cannot run for this train conditions - EXCLUDED");
350    }
351    
352    if(iPWG4PtSpectra){
353      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPWG4HighPtSpectra.C");
354      AliPWG4HighPtSpectra *taskPtSpectra = AddTaskPWG4HighPtSpectra();
355      if (!taskPtSpectra) ::Warning("AnalysisTrainPWG4Jets", "AliAnalysisTaskPtSpectra cannot run for this train conditions - EXCLUDED");
356    }
357
358    if(iPWG4PartCorr){
359      gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
360      AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS",kUseMC,kFALSE,kIsMC);
361      if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
362      AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL",kUseMC,kFALSE,kIsMC);
363      if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
364      if(kDeltaAODPartCorrName.Length()>0)mgr->RegisterExtraFile(kDeltaAODPartCorrName.Data()); // hmm this is written anyway.... but at least we do not register it...
365    }   
366
367    // PWG4 gamma conversion analysis
368    if (iPWG4GammaConv) {
369       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
370       TString cdir = gSystem->WorkingDirectory();
371       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
372       //      TString gcArguments = "-run-on-train -run-jet -run-chic -run-neutralmeson -run-cf";
373       TString gcArguments = "-run-on-train -run-jet -run-neutralmeson -run-cf";
374       if(!kIsMC)gcArguments += " -mc-off";
375       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
376       gSystem->ChangeDirectory(cdir);
377       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
378    }   
379
380    //==========================================================================
381    // FOR THE REST OF THE TASKS THE MACRO AddTaskXXX() is not yet implemented/
382    // Run the analysis
383    //    
384    if (kPluginUse) {
385       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
386       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
387    }
388    
389    if (mgr->InitAnalysis()) {
390      mgr->PrintStatus();
391      // if (kSaveTrain || strlen(config_file)) gSystem->ChangeDirectory(kTrainName);
392      if (!strcmp(plugin_mode, "submit")&&smode=="GRID"){
393        TString alien_workdir = gGrid->GetHomeDirectory();
394        if (iAODanalysis) alien_workdir += "analysisAOD";
395        else              alien_workdir += "analysisESD";
396        AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
397        printf("=== Registering jdl in the work directory alien://%s/%s, should be done by the manager! ===\n",
398               alien_workdir.Data(),gridhandler->GetGridOutputDir());
399        TFile::Cp(Form("file:%s.jdl",kTrainName.Data()), Form("alien://%s/%s/%s.jdl",alien_workdir.Data(),
400                                                              gridhandler->GetGridOutputDir(),kTrainName.Data()));
401      }
402     
403      StartAnalysis(smode, chain);
404      if (!strcmp(plugin_mode, "offline")&&smode=="GRID"){
405      // Offline mode path files
406      // PatchJDL();
407      PatchAnalysisMacro();
408       }
409
410       if (kSaveTrain && smode=="GRID") {
411          AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();
412          TString alien_workdir = gGrid->GetHomeDirectory();
413          if (iAODanalysis) alien_workdir += "analysisAOD";
414          else              alien_workdir += "analysisESD";
415          //     kGridOutdir = gridhandler->GetGridOutputDir();
416          printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",
417                 alien_workdir.Data());
418          if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data())))
419             gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
420          if (strcmp(plugin_mode, "test"))
421             TFile::Cp(Form("file:%sConfig.C",kTrainName.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), kTrainName.Data()));
422       }
423 }
424 }
425
426 //______________________________________________________________________________
427 void StartAnalysis(const char *mode, TChain *chain) {
428 // Start analysis.
429    Int_t imode = -1;
430    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
431    if (!strcmp(mode, "LOCAL")) imode = 0;
432    if (!strcmp(mode, "PROOF")) imode = 1;
433    if (!strcmp(mode, "GRID"))  imode = 2;
434    switch (imode) {
435       case 0:
436          if (!chain) {
437             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
438             return;
439          }   
440          mgr->StartAnalysis(mode, chain);
441          return;
442       case 1:
443          if (!kProofDataSet.Length()) {
444             ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "kProofDataSet is empty");
445             return;
446          }   
447          mgr->StartAnalysis(mode, kProofDataSet, kProofEvents,kProofOffset);
448          return;
449       case 2:
450          if (kPluginUse) {
451             if (!mgr->GetGridHandler()) {
452                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Grid plugin not initialized");
453                return;
454             }   
455             mgr->StartAnalysis("grid");
456          } else {
457             if (!chain) {
458                ::Error("AnalysisTrainPWG4Jets.C::StartAnalysis", "Cannot create the chain");
459                return;
460             }   
461             mgr->StartAnalysis(mode, chain);
462          }   
463          return;
464    }      
465 }          
466     
467 //______________________________________________________________________________
468 void CheckModuleFlags(const char *mode) {
469 // Checks selected modules and insure compatibility
470    Int_t imode = -1;
471    if (!strcmp(mode, "LOCAL")) imode = 0;
472    if (!strcmp(mode, "PROOF")) imode = 1;
473    if (!strcmp(mode, "GRID"))  imode = 2;
474
475
476
477
478    if (imode==1) {
479       if (!kUsePAR) {
480          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
481          kUsePAR = kTRUE;
482       }   
483    }  
484    if (imode != 2) {
485       ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
486       kPluginUse = kFALSE; 
487    }   
488
489
490    if(!kIsMC){
491      // switch off anthin related to MC
492      kUseMC = 0;
493      kUseAODMC = 0;
494      kUseTR = kFALSE;
495    }
496
497    if (iAODanalysis) {
498    // AOD analysis
499       if (kUseMC)
500          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
501       if (kUseAODTags)
502          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
503       kUseMC = kFALSE;
504       kUseTR = kFALSE;
505       kUseAODTags = kFALSE;
506       if (iESDfilter)
507          ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
508       iESDfilter   = 0;
509       if (!iAODhandler) {
510          if (iJETAN) 
511             ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
512          iJETAN = 0;
513          iDIJETAN = 0;
514       }
515       // Disable tasks that do not work yet on AOD data
516       if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
517       iPWG4PtQAMC        = 0;
518       if( iPWG4PtQATPC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtTPC disabled in analysis on AOD's");
519       iPWG4PtQATPC        = 0;
520       if( iPWG4PtSpectra)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis on AOD's");
521       iPWG4PtSpectra     = 0;
522       if (iPWG4PartCorr)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4partcorr disabled on AOD's");
523       iPWG4PartCorr = 0;
524       if(iPWG1QASym)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG1 QA Sym disabled in analysis on AOD's");
525       if (iPWG4GammaConv)::Info("AnalysisPWG4Jets.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's");
526       iPWG4GammaConv = 0;   
527
528       iPWG1QASym     = 0;
529    } else {   
530    // ESD analysis
531      if (!kUseMC){
532        kUseTR = kFALSE;
533        
534        if(kUseKinefilter)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 Kine Filter disabled in analysis without MC");
535        kUseKinefilter = kFALSE;
536        if( iPWG4PtQAMC)::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "PWG4 PtQAMC disabled in analysis without MC");
537        iPWG4PtQAMC        = 0;
538
539      }
540      if (!kUseTR) {
541        //         ::Info("AnalysisTrainPWG4Jets.C::CheckModuleFlags", "iPWG2evchar disabled if not reading track references");
542      }   
543       if (iJETAN) iESDfilter=1;
544       if (!iESDfilter){
545         kUseKinefilter = kFALSE;
546         kUseMuonfilter = kFALSE;
547       }
548       if(!iJETAN){
549         iPWG4JetSpectrum = iPWG4UE = iPWG4ThreeJets = iDIJETAN = 0;
550       }
551    }
552    iPWG4JetTasks = iPWG4JetServices||iPWG4JetSpectrum||iPWG4UE||iPWG4PtQAMC||iPWG4PtSpectra||iPWG4PtQATPC||iPWG4ThreeJets;
553
554    if (iESDfilter) {iAODhandler=1;}
555    if (kUseKinefilter && !kUseMC) kUseKinefilter = kFALSE;
556    if (kUseAODTags && !iAODhandler) kUseAODTags = kFALSE;
557
558
559    
560 }
561
562 //______________________________________________________________________________
563 Bool_t Connect(const char *mode) {
564 // Connect <username> to the back-end system.
565    Int_t imode = -1;
566    if (!strcmp(mode, "LOCAL")) imode = 0;
567    if (!strcmp(mode, "PROOF")) imode = 1;
568    if (!strcmp(mode, "GRID"))  imode = 2;
569    TString username = gSystem->Getenv("alien_API_USER");
570    switch (imode) {
571       case 0:
572          break;
573       case 1:
574          if  (!username.Length()) {
575             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
576                            1. Have called: alien-token-init <username>\n \
577                            2. Have called: >source /tmp/gclient_env_$UID");
578             return kFALSE;
579          }
580          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
581                 username.Data(), kProofCluster.Data());
582          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
583 //         TProof::Open(Form("%s@%s:31093", username.Data(), kProofCluster.Data()));       
584          TProof::Open(Form("%s@%s", username.Data(), kProofCluster.Data()));       
585          if (!gProof) {
586             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
587                ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
588             return kFALSE;
589          }
590          if(kProofClearPackages)gProof->ClearPackages();
591
592          if(kProofSaveToAlien){
593            TGrid::Connect("alien://");
594            if (gGrid) {
595              TString homedir = gGrid->GetHomeDirectory();
596              TString workdir = homedir + kTrainName;
597              if (!gGrid->Cd(workdir)) {
598                gGrid->Cd(homedir);
599                if (gGrid->Mkdir(workdir)) {
600                  gGrid->Cd(kTrainName);
601                  ::Info("AnalysisTrainPWG4Jets::Connect()", "Directory %s created", gGrid->Pwd());
602                }
603              }
604              gGrid->Mkdir("proof_output");
605              gGrid->Cd("proof_output");
606              kProofOutdir = Form("alien://%s", gGrid->Pwd());
607            }   
608          }
609          break;
610       case 2:      
611          if  (!username.Length()) {
612             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), "Make sure you:\n \
613                            1. Have called: alien-token-init <username>\n \
614                            2. Have called: >source /tmp/gclient_env_$UID");
615             return kFALSE;
616          }
617          if (kPluginUse && !gSystem->Getenv("alien_CLOSE_SE")) {
618             ::Error(Form("AnalysisTrainPWG4Jets.C::Connect <%s>", mode), 
619                            "When using the AliEn plugin it is preferable to define the \
620                            variable alien_CLOSE_SE in your environment.");
621             return kFALSE;
622          }
623          ::Info("AnalysisTrainPWG4Jets.C::Connect", "Connecting user <%s> to AliEn ...", 
624                 username.Data());
625          TGrid::Connect("alien://");
626          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
627          break;
628       default:
629          ::Error("AnalysisTrainPWG4Jets.C::Connect", "Unknown run mode: %s", mode);
630          return kFALSE;
631    }
632    ::Info("AnalysisTrainPWG4Jets.C::Connect","Connected in %s mode", mode);
633    return kTRUE;
634 }
635
636 //______________________________________________________________________________
637 Bool_t LoadCommonLibraries(const char *mode)
638 {
639 // Load common analysis libraries.
640    Int_t imode = -1;
641    if (!strcmp(mode, "LOCAL")) imode = 0;
642    if (!strcmp(mode, "PROOF")) imode = 1;
643    if (!strcmp(mode, "GRID"))  imode = 2;
644    if (!gSystem->Getenv("ALICE_ROOT")) {
645       ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
646       return kFALSE;
647    }   
648    Bool_t success = kTRUE;
649    // ROOT libraries
650    gSystem->Load("libTree.so");
651    gSystem->Load("libGeom.so");
652    gSystem->Load("libVMC.so");
653    gSystem->Load("libPhysics.so");
654    
655    // Load framework classes. Par option ignored here.
656    switch (imode) {
657       case 0:
658       case 2:
659          if (kUseCPAR) {
660             success &= LoadLibrary("STEERBase", mode, kTRUE);
661             success &= LoadLibrary("ESD", mode, kTRUE);
662             success &= LoadLibrary("AOD", mode, kTRUE);
663             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
664             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
665             success &= LoadLibrary("CORRFW", mode, kTRUE);
666          } else {   
667             success &= LoadLibrary("libSTEERBase.so", mode);
668             success &= LoadLibrary("libESD.so", mode);
669             success &= LoadLibrary("libAOD.so", mode);
670             success &= LoadLibrary("libANALYSIS.so", mode);
671             success &= LoadLibrary("libANALYSISalice.so", mode);
672             success &= LoadLibrary("libCORRFW.so", mode);
673             gROOT->ProcessLine(".include $ALICE_ROOT/include");
674          }   
675          break;
676       case 1:
677          Int_t ires = -1;
678          if (kProofUseAFPAR && !gSystem->AccessPathName(kProofAFversion)) ires = gProof->UploadPackage(kProofAFversion);
679          if (ires < 0) {
680             success &= LoadLibrary("STEERBase", mode);
681             success &= LoadLibrary("ESD", mode);
682             success &= LoadLibrary("AOD", mode);
683             success &= LoadLibrary("ANALYSIS", mode);
684             success &= LoadLibrary("ANALYSISalice", mode);
685             success &= LoadLibrary("CORRFW", mode);
686          } else { 
687             ires = gProof->EnablePackage(kProofAFversion);
688             if (ires<0) success = kFALSE;
689             success &= LoadLibrary("CORRFW", mode);
690          }
691          break;         
692       default:
693          ::Error("AnalysisTrainPWG4Jets.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
694          return kFALSE;
695    }
696    if (success) {
697       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
698       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
699               gSystem->GetIncludePath());
700    } else {           
701       ::Info("AnalysisTrainPWG4Jets.C::LoadCommodLibraries", "Load common libraries:    FAILED");
702    }   
703       
704    return success;
705 }
706
707 //______________________________________________________________________________
708 Bool_t LoadAnalysisLibraries(const char *mode)
709 {
710 // Load common analysis libraries.
711    Bool_t success = kTRUE;
712    if (iESDfilter) {
713       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
714           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
715    }   
716    // JETAN
717    if (iJETAN||iDIJETAN) {
718      if (!strcmp(mode, "PROOF")){
719        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libCGALso\"\)", kTRUE); 
720        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libfastjet.so\"\)", kTRUE); 
721        // problem when loading siscone copiled with different gcc version??
722        // gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libsiscone.so\"\)", kTRUE); 
723        gProof->Exec("gSystem->Load\(\"/afs/cern.ch/user/d/dperrino/public/libSISConePlugin.so\"\)", kTRUE);      
724      }
725      if (!LoadLibrary("libCGAL.so", mode, kTRUE)) return kFALSE;
726      if (!LoadLibrary("libfastjet.so", mode, kTRUE)) return kFALSE;
727      if (!LoadLibrary("libsiscone.so", mode, kTRUE)) return kFALSE;
728      if (!LoadLibrary("libSISConePlugin.so", mode, kTRUE)) return kFALSE;
729      if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
730      if (!LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
731    }
732    if(iPWG4JetTasks){
733      // PWG4 particle correlations
734      if (!LoadLibrary("PWG4JetTasks", mode, kTRUE)) return kFALSE;
735    }
736    if(iPWG1QASym){
737      if (!LoadSource(Form("%s/PWG1/AliAnalysisTaskQASym.cxx",gSystem->ExpandPathName("$ALICE_ROOT")), mode, kTRUE))return kFALSE;
738    }
739    if (iPWG4PartCorr) {   
740       if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
741           !LoadLibrary("PHOSUtils", mode, kTRUE) ||
742           !LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
743           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
744    }
745    if (iPWG4GammaConv) {
746       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
747    }      
748
749    ::Info("AnalysisTrainPWG4Jets.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
750    return kTRUE;
751 }
752
753 //______________________________________________________________________________
754 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
755 {
756 // Load a module library in a given mode. Reports success.
757    Int_t imode = -1;
758    Int_t result;
759    TString smodule(module);
760    if (!strcmp(mode, "LOCAL")) imode = 0;
761    if (!strcmp(mode, "PROOF")) imode = 1;
762    if (!strcmp(mode, "GRID"))  imode = 2;
763    TString mod(module);
764    if (!mod.Length()) {
765       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Empty module name");
766       return kFALSE;
767    }   
768    // If a library is specified, just load it
769    if (smodule.EndsWith(".so")) {
770       mod.Remove(mod.Index(".so"));
771       result = gSystem->Load(mod);
772       if (result < 0) {
773          ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load library %s", module);
774          return kFALSE;
775       }
776       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
777       return kTRUE;
778    } 
779    // Check if the library is already loaded
780    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
781       return kTRUE;    
782    switch (imode) {
783       case 0:
784       case 2:
785          if (kUsePAR) {
786             result = SetupPar(module);
787             if (rec) anaPars += Form("%s.par ", module);
788          } else {
789             result = gSystem->Load(Form("lib%s.so", module));
790             if (rec) anaLibs += Form("lib%s.so ", module);
791          }   
792          break;
793       case 1:
794         if(!gSystem->AccessPathName(module)){
795           ::Info("AnalysisTrainPWG4Jets.C::LoadLibrary", "Removing directory %s",module);
796           gSystem->Exec(Form("rm -rf %s",module));
797         }
798          result = gProof->UploadPackage(module);
799          if (result<0) {
800             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
801             if (result<0) {
802                ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
803                return kFALSE;
804             }
805          }   
806          result = gProof->EnablePackage(module);
807          break;
808       default:
809          return kFALSE;
810    }         
811    if (result < 0) {
812       ::Error("AnalysisTrainPWG4Jets.C::LoadLibrary", "Could not load module %s", module);
813       return kFALSE;
814    }
815    return kTRUE;
816 }           
817
818
819
820 //______________________________________________________________________________
821 Bool_t LoadSource(const char *source, const char *mode, Bool_t rec=kFALSE)
822 {
823 // Load a module library in a given mode. Reports success.
824    Int_t imode = -1;
825    Int_t result = -1;
826    if (!strcmp(mode, "LOCAL")) imode = 0;
827    if (!strcmp(mode, "PROOF")) imode = 1;
828    if (!strcmp(mode, "GRID"))  imode = 2;
829    TString ssource(source);
830    TString basename = gSystem->BaseName(ssource.Data());
831    if (!ssource.Length()) {
832       ::Error("AnalysisTrainPWG4Jets.C::LoadSource", "Empty task name");
833       return kFALSE;
834    }   
835     // we have a source code so compile it
836    if (ssource.EndsWith(".cxx")) {
837      // need to copy it here other wise the path is also used on grid...
838      ssource.Remove(ssource.Index(".cxx"));
839      basename.Remove(basename.Index(".cxx"));
840      Printf("LoadSources:: Copying...  path %s{cxx,h}",ssource.Data());
841      gSystem->Exec(Form("cp %s.cxx . ",ssource.Data()));
842      gSystem->Exec(Form("cp %s.h . ",ssource.Data()));
843      // Path to code
844      // only needed for local compilation, in grid and proof mode 
845      // the task headers are uploaded 
846      //     path.Remove(path.Index(gSystem->BaseName(path.Data())));
847      // Printf("LoadSources:: Including path %s",path.Data());
848      //  if(path.Length()>0)gROOT->ProcessLine(Form(".include %s",path.Data()));
849      Printf("LoadSources:: Loading...  path %s",basename.Data());
850      switch (imode) {
851      case 0:
852        result = gROOT->LoadMacro(Form("%s.cxx+g",basename.Data()));
853        break;
854      case 1:
855        result = gProof->LoadMacro(Form("%s.cxx+g",basename.Data()));
856        break;
857      case 2:
858        result = gROOT->LoadMacro(Form("%s.cxx+g",basename.Data()));
859        if (rec){
860          // what we want to compile
861          anaSources += Form("%s.cxx ",basename.Data()); 
862          // what we need as input...
863          anaLibs += Form("%s.cxx %s.h ",basename.Data(),basename.Data()); 
864        }
865        break;
866      default:
867        return kFALSE;
868      }
869    } 
870    if (result < 0) {
871       ::Error("AnalysisTrainPWG4Jets.C::LoadSources", "Could not load source %s", source);
872       return kFALSE;
873    }
874    return kTRUE;
875 }           
876
877
878 //______________________________________________________________________________
879 TChain *CreateChain(const char *mode, const char *plugin_mode)
880 {
881 // Create the input chain
882    Int_t imode = -1;
883    if (!strcmp(mode, "LOCAL")) imode = 0;
884    if (!strcmp(mode, "PROOF")) imode = 1;
885    if (!strcmp(mode, "GRID"))  imode = 2;
886    TChain *chain = NULL;
887    // Local chain
888    switch (imode) {
889       case 0:
890          if (iAODanalysis) {
891             if (!kLocalXMLDataset.Length()) {
892                // Local AOD
893                chain = new TChain("aodTree");
894                TString line;
895                ifstream in;
896                in.open(kLocalDataList.Data());
897                while (in.good()) {
898                  in >> line;
899                  if (line.Length() == 0) continue;
900                  // cout << " line = " << line << endl;
901                  chain->Add(line.Data());
902                }       
903             } else {
904                // Interactive AOD
905                chain = CreateChainSingle(kLocalXMLDataset, "aodTree");
906             }
907          } else {      
908            if (!kLocalXMLDataset.Length()) {
909              // Local ESD
910              chain = new TChain("esdTree");
911              TString line;
912              ifstream in;
913              in.open(kLocalDataList.Data());
914              while (in.good()) {
915                in >> line;
916                if (line.Length() == 0) continue;
917                cout << " line = " << line << endl;
918                chain->Add(line.Data());
919              }       
920            } else {
921              // Interactive ESD
922                chain = CreateChainSingle(kLocalXMLDataset, "esdTree");
923            }   
924          }
925          break;
926       case 1:
927          break;
928       case 2:
929          if (kPluginUse) {
930 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
931 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
932          } else {
933             TString           treeName = "esdTree";
934             if (iAODanalysis) treeName = "aodTree";
935             chain = CreateChainSingle("wn.xml", treeName);
936          }
937          break;      
938       default:   
939    }
940    if (chain && chain->GetNtrees()) return chain;
941    return NULL;
942 }   
943
944 //______________________________________________________________________________
945 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
946 {
947    printf("*******************************\n");
948    printf("*** Getting the ESD Chain   ***\n");
949    printf("*******************************\n");
950    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
951
952    if (!myCollection) {
953       ::Error("AnalysisTrainPWG4Jets.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
954       return NULL ;
955    }
956
957    TChain* chain = new TChain(treeName);
958    myCollection->Reset() ;
959    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
960    chain->ls();
961    return chain;
962 }
963
964 //______________________________________________________________________________
965 Int_t SetupPar(char* pararchivename)
966 {
967    if (!pararchivename || !strlen(pararchivename)) return -1;
968    char processline[1024];
969    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
970       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
971          ::Info("AnalysisTrainPWG4Jets.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
972          TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
973                    Form("%s.par",pararchivename));
974       } else {
975          ::Error("AnalysisTrainPWG4Jets.C::SetupPar", "Cannot find %s.par", pararchivename);
976          return -1;
977       }   
978    }
979    if (kPluginUse && kSaveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, kTrainName.Data()));
980    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
981
982    TString ocwd = gSystem->WorkingDirectory();
983    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
984         
985    // check for BUILD.sh and execute
986    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
987       printf("*******************************\n");
988       printf("*** Building PAR archive    ***\n");
989       printf("*******************************\n");          
990       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
991          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
992          return -1;
993       }
994    }
995
996         // check for SETUP.C and execute
997         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
998             printf("*******************************\n");
999             printf("*** Setup PAR archive       ***\n");
1000             printf("*******************************\n");
1001             gROOT->Macro("PROOF-INF/SETUP.C");
1002         }       
1003         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
1004    return 0;
1005 }
1006
1007 //______________________________________________________________________________
1008 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1009 {
1010 // Check if user has a valid token, otherwise make one. This has limitations.
1011 // One can always follow the standard procedure of calling alien-token-init then
1012 //   source /tmp/gclient_env_$UID in the current shell.
1013    if (!AliAnalysisGrid::CreateToken()) return NULL;
1014    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1015 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1016    plugin->SetRunMode(plugin_mode);
1017    if (kPluginUseProductionMode) plugin->SetProductionMode();
1018    plugin->SetJobTag(kJobTag);
1019    plugin->SetNtestFiles(2);
1020 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1021 // Set versions of used packages
1022    plugin->SetAPIVersion("V1.0x");
1023    plugin->SetROOTVersion(kPluginRootVersion);
1024    plugin->SetAliROOTVersion(kPluginAliRootVersion);
1025 // Declare input data to be processed.
1026 // Method 1: Create automatically XML collections using alien 'find' command.
1027 // Define production directory LFN
1028    plugin->SetGridDataDir(kGridDatadir.Data());
1029 // Set data search pattern
1030    if (iAODanalysis) plugin->SetDataPattern(" *AliAOD.root");
1031    else              plugin->SetDataPattern(Form(" %s/*/*ESD.tag.root",kGridPassPattern.Data()));
1032 // ...then add run numbers to be considered
1033 //   plugin->SetRunRange(kGridRunRange[0], kGridRunRange[1]);
1034    for (Int_t i=kGridRunRange[0]; i<=kGridRunRange[1]; i++) {
1035      Printf("AnalysisTrainPWG4Jets Adding run number %s", Form(kGridRunPattern.Data(),i));
1036      plugin->AddRunNumber(Form(kGridRunPattern.Data(),i));
1037    }   
1038
1039    if(kGridLocalRunList.Length()>0){
1040      ifstream in1;
1041      in1.open(kGridLocalRunList.Data());
1042      int iRun;
1043      while(in1>>iRun){
1044        Printf("AnalysisTrainPWG4Jets Adding run number from File %s", Form(kGridRunPattern.Data(),iRun));
1045        plugin->AddRunNumber(Form(kGridRunPattern.Data(),iRun));
1046      }
1047    }
1048
1049 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1050 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1051 // XML collections added via this method can be combined with the first method if
1052 // the content is compatible (using or not tags)
1053 //   plugin->AddDataFile("tag.xml");
1054 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1055 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1056    if (iAODanalysis) plugin->SetGridWorkingDir("analysisAOD");
1057    else              plugin->SetGridWorkingDir("analysisESD");
1058    // Declare alien output directory. Relative to working directory.
1059    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1060    plugin->SetGridOutputDir(kGridOutdir);
1061
1062    // Add external packages
1063    if (iJETAN||iDIJETAN) {
1064       plugin->AddExternalPackage("boost::v1_38_0");
1065       plugin->AddExternalPackage("cgal::v3.3.1");
1066       plugin->AddExternalPackage("fastjet::v2.4.0");
1067    }   
1068
1069
1070    // set extra libs before par file compilation
1071    anaLibs += kGridExtraFiles;
1072    anaLibs     = anaLibs.Strip();   
1073    Printf("%s",anaLibs.Data());
1074    if (anaLibs.Length())     plugin->SetAdditionalLibs(anaLibs.Data());
1075
1076    TString ana_sources = "";
1077    TString ana_add = "";
1078    if (kUsePAR && anaPars.Length()) {
1079       printf("%s\n", anaPars.Data());
1080       TObjArray *arr;
1081       TObjString *objstr;
1082       arr = anaPars.Tokenize(" ");
1083       TIter next(arr);
1084       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1085       delete arr;
1086    } 
1087    
1088 // Declare the analysis source files names separated by blancs. To be compiled runtime
1089 // using ACLiC on the worker nodes.
1090    ana_sources = anaSources.Strip();
1091 // Declare all libraries (other than the default ones for the framework. These will be
1092 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1093
1094    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1095    plugin->SetExecutableCommand(kPluginExecutableCommand.Data());  
1096 // Declare the output file names separated by blancs.
1097 // (can be like: file.root or file.root@ALICE::Niham::File)
1098    plugin->SetDefaultOutputs();
1099    plugin->SetMergeExcludes(kGridMergeExclude);
1100    plugin->SetMaxMergeFiles(kGridMaxMergeFiles);
1101    plugin->SetNrunsPerMaster(kGridRunsPerMaster);
1102 // Optionally define the files to be archived.
1103 //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1104    
1105    
1106    // Put default output files to archive
1107    TString listhists = "";
1108    TString listaods  = "";
1109    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1110    TIter next(mgr->GetOutputs());
1111    AliAnalysisDataContainer *output;
1112    while ((output=(AliAnalysisDataContainer*)next())) {
1113       const char *filename = output->GetFileName();
1114       if (!(strcmp(filename, "default"))) {
1115         if (!mgr->GetOutputEventHandler()) continue;
1116          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
1117          if (listaods.Length()) listaods += ",";
1118          listaods += filename;
1119          if(kIsMC){
1120            listaods += ",";
1121            listaods += "pyxsec_hists.root";
1122          }
1123       } else {
1124         if(!listhists->Contains(filename)){
1125           if (listhists.Length()) listhists += ",";
1126           listhists += filename;
1127         }
1128       }
1129    }
1130
1131    if(kUseSysInfo>0){
1132      if (listhists.Length()) listhists += ",";
1133      listhists += "syswatch.root";
1134    }
1135
1136    if (mgr->GetExtraFiles().Length()) {
1137      if (listaods.Length()) listaods += ",";
1138      listaods += mgr->GetExtraFiles();
1139      listaods.ReplaceAll(" ", ",");
1140    }
1141
1142    // if we do not fill the aod we do not need to store it
1143    if(!kFillAOD)listaods="";
1144
1145    if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), kGridOutputStorages.Data());;
1146    if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), kGridOutputStorages.Data());;
1147
1148    if (!listhists.Length() && !listaods.Length()) {
1149       ::Fatal("AnalysisTrainPWG4Jets", "No task output !");
1150    }
1151
1152    kGridMergeExclude = listaods;
1153
1154    TString outputArchive = "log_archive.zip:stdout,stderr@ALICE::CERN::SE";
1155    if(kUseSysInfo>0)outputArchive = "log_archive.zip:stdout,stderr,syswatch.log@ALICE::CERN::SE";
1156    if (listaods.Length()) {
1157       outputArchive += " ";
1158       outputArchive += listaods;
1159    }   
1160    if (listhists.Length()) {
1161       outputArchive += " ";
1162       outputArchive += listhists;
1163    }   
1164    plugin->SetOutputArchive(outputArchive);
1165 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
1166    plugin->SetAnalysisMacro(Form("%s.C", kTrainName.Data()));
1167 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
1168    plugin->SetSplitMaxInputFileNumber(kGridFilesPerJob);
1169 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
1170 //   plugin->SetMaxInitFailed(5);
1171 // Optionally resubmit threshold.
1172 //   plugin->SetMasterResubmitThreshold(90);
1173 // Optionally set time to live (default 30000 sec)
1174    plugin->SetTTL(30000);
1175 // Optionally set input format (default xml-single)
1176    plugin->SetInputFormat("xml-single");
1177 // Optionally modify the name of the generated JDL (default analysis.jdl)
1178    plugin->SetJDLName(Form("%s.jdl", kTrainName.Data()));
1179 // Optionally modify the executable name (default analysis.sh)
1180    plugin->SetExecutable(Form("%s.sh", kTrainName.Data()));
1181 // Optionally modify job price (default 1)
1182    plugin->SetPrice(1);      
1183 // Optionally modify split mode (default 'se')    
1184    plugin->SetSplitMode("se");
1185    return plugin;
1186 }
1187
1188 //______________________________________________________________________________
1189 void WriteConfig()
1190 {
1191 // Write train configuration in a file. The file name has the format:
1192 // train_[trainName]_ddMonthyyyy_time.C
1193    if (kUseDate) {
1194       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
1195       ifstream fdate("date.tmp");
1196       if (!fdate.is_open()) {
1197          ::Error("AnalysisTrainPWG4Jets.C::Export","Could not generate file name");
1198          return;
1199       }
1200       const char date[64];
1201       fdate.getline(date,64);
1202       fdate.close();
1203       gSystem->Exec("rm date.tmp");
1204       kTrainName = Form("train_%s_%s", kTrainName.Data(), date);
1205    } else {
1206       kTrainName = Form("train_%s", kTrainName.Data());
1207    }   
1208    TString cdir = gSystem->WorkingDirectory();
1209    gSystem->MakeDirectory(kTrainName);
1210    gSystem->ChangeDirectory(kTrainName);
1211    ofstream out;
1212    out.open(Form("%sConfig.C",kTrainName.Data()), ios::out); 
1213    if (out.bad()) {
1214       ::Error("AnalysisTrainPWG4Jets.C::Export", "Cannot open ConfigTrain.C for writing");
1215       return;
1216    }
1217    out << "{" << endl;
1218    out << "   kTrainName      = " << "\"" << kTrainName.Data() << "\";" << endl;
1219    out << "   kProofCluster   = " << "\"" << kProofCluster.Data() << "\";" << endl;
1220    out << "   kProofUseAFPAR        = " << kProofUseAFPAR << ";" << endl;
1221    if (kProofUseAFPAR) 
1222       out << "   kProofAFversion       = " << kProofAFversion.Data() << ";" << endl;
1223    out << "   kProofDataSet   = " << "\"" << kProofDataSet.Data() << "\";" << endl;
1224    out << "   kPluginUse       = " << kPluginUse << ";" << endl;
1225    out << "   kUsePAR          = " << kUsePAR << ";" << endl;
1226    out << "   kUseCPAR         = " << kUseCPAR << ";" << endl;
1227    out << "   kPluginRootVersion    = " << "\"" << kPluginRootVersion.Data() << "\";" << endl;
1228    out << "   kPluginAliRootVersion = " << "\"" << kPluginAliRootVersion.Data() << "\";" << endl;
1229    out << "   kGridDatadir   = " << "\"" << kGridDatadir.Data() << "\";" << endl;
1230    if (!kGridOutdir.Length()) kGridOutdir = Form("output_%s",kTrainName.Data());
1231    out << "   kGridOutdir    = " << "\"" << kGridOutdir.Data() << "\";" << endl;
1232    out << "   kGridMaxMergeFiles   = " << kGridMaxMergeFiles << ";" << endl;
1233    out << "   kGridMergeExclude    = " << "\"" << kGridMergeExclude.Data() << "\";" << endl;
1234    out << "   kGridRunsPerMaster  = " << kGridRunsPerMaster << ";" << endl;
1235    out << "   kGridFilesPerJob    = " << kGridFilesPerJob << ";" << endl;
1236    out << "   kGridRunRange[0]    = " << kGridRunRange[0] << ";" << endl;
1237    out << "   kGridRunRange[1]    = " << kGridRunRange[1] << ";" << endl;
1238    out << "   kUseDebug          = " << kUseDebug << ";" << endl;
1239    out << "   kUseMC           = " << kUseMC << ";" << endl;
1240    out << "   kUseESDTags         = " << kUseESDTags << ";" << endl;
1241    out << "   kUseKinefilter      = " << kUseKinefilter << ";" << endl;
1242    out << "   kUseTR           = " << kUseTR << ";" << endl;
1243    out << "   kUseAODTags      = " << kUseAODTags << ";" << endl;
1244    out << "   kSaveTrain       = " << "kFALSE;" << endl << endl;
1245    out << "   // Analysis modules" << endl;
1246    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
1247    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
1248    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
1249    out << "   iJETAN          = " << iJETAN << ";" << endl;
1250    out << "// Configuration fot the wagons" << endl;
1251    out << "}" << endl;
1252    ::Info("AnalysisTrainPWG4Jets.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", kTrainName.Data()));
1253    gSystem->ChangeDirectory(cdir);
1254 }   
1255
1256 //______________________________________________________________________________
1257 Bool_t LoadConfig(const char *filename)
1258 {
1259 // Read train configuration from file
1260    if (gSystem->AccessPathName(filename)) {
1261       ::Error("AnalysisTrainPWG4Jets.C::LoadConfig", "Config file name not found");
1262       return kFALSE;
1263    }   
1264    gROOT->ProcessLine(Form(".x %s", filename));
1265    ::Info("AnalysisTrainPWG4Jets.C::LoadConfig", "Train configuration loaded from file %s", filename);
1266    return kTRUE;
1267 }
1268
1269 Bool_t PatchJDL(){
1270   Printf(">>> Patching JDL");
1271   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1272   AliAnalysisAlien*    gridHandler = (AliAnalysisAlien*)mgr->GetGridHandler();
1273   TGridJDL *jdl = gridHandler->GetGridJDL();
1274   if(iJETAN)jdl->AddToPackages("fastjet","v2.4.0");
1275   gridHandler->WriteJDL(kFALSE);
1276   Printf("<<< Patching JDL");
1277   return kTRUE;
1278 }
1279
1280 Bool_t PatchAnalysisMacro(){
1281     Printf(">>> Patching AnalysisMacro");
1282     gSystem->Exec(Form("mv %s.C %s.C_tmp",kTrainName.Data(),kTrainName.Data()));
1283
1284   ifstream in1; 
1285   in1.open(Form("%s.C_tmp", kTrainName.Data()));
1286   char cLine[250];
1287   TString st;
1288   while(in1.getline(cLine,250)){
1289     st += cLine;
1290     st += "\n";
1291   }
1292   Int_t index;
1293   index = st.Index("gSystem->Load(\"libPhysics\");");
1294   index += strlen("gSystem->Load(\"libPhysics\");");
1295   if(iJETAN){
1296     TObjArray *arr;
1297     TObjString *objstr;
1298     arr = anaLibs.Tokenize(" ");
1299     TIter next(arr);
1300     TString add = "";
1301     add += "\n\n // added by CKB \n";
1302     while ((objstr=(TObjString*)next())){
1303       if(objstr->GetString().EndsWith(".so"))add += Form("gSystem->Load(\"%s\");\n",objstr->GetString().Data());
1304     }
1305     delete arr; 
1306     add += "// BKC \n\n";
1307     st.Insert(index,add.Data());
1308   }
1309   ofstream out;
1310   out.open(Form("%s.C", kTrainName.Data()));
1311   if (out.bad()) {
1312     return kFALSE;
1313   }
1314   out << st << endl;
1315   Printf("<<< Patching AnalysisMacro");
1316   return kTRUE;
1317
1318 }