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