Split: fix refs to AddTaskPhysicsSelection.C
[u/mrichter/AliRoot.git] / ANALYSIS / macros / AnalysisTrainNew.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] AnalysisTrainNew("grid", "full")
7 // CAF mode (requires root v5-23-02 + aliroot v4-16-Rev08)
8 //    root[2] AnalysisTrainNew("proof")
9 // Local mode requires AliESds.root or AliAOD.root in ./data directory
10 //    root[3] AnalysisTrainNew("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] AnalysisTrainNew(ana_mode, plugin_mode, "train_default_<date>/ConfigTrain.C")
17
18 //==================   TRAIN NAME   ============================================
19 TString     train_name         = "FILTER_DATA"; // *CHANGE ME* (no blancs or special characters)
20 TString     job_tag            = "FILTER_DATA: data ESD + PhysSel + Tender -> AOD + Muons + Vertices"; // *CHANGE ME*
21 //==============================================================================
22
23 // ### Settings that make sense in PROOF only
24 //==============================================================================
25 TString     proof_cluster      = "alicecaf.cern.ch";
26 Bool_t      useAFPAR           = kFALSE;  // use AF special par file
27 TString     AFversion          = "AF-v4-17";
28 // Change CAF dataset here
29 TString     proof_dataset      = "/COMMON/COMMON/LHC09a4_run8100X#/esdTree";
30 TString     proof_outdir       = "";
31
32 // ### Settings that make sense when using the Alien plugin
33 //==============================================================================
34 Int_t       runOnData          = 1;       // Set to 1 if processing real data
35 Int_t       iCollision         = 0;       // 0=pp, 1=Pb-Pb
36 Bool_t      usePLUGIN          = kTRUE;   // do not change
37 Bool_t      useProductionMode  = kTRUE;   // use the plugin in production mode
38 // Usage of par files ONLY in grid mode and ONLY if the code is not available
39 // in the deployed AliRoot versions. Par file search path: local dir, if not there $ALICE_ROOT.
40 // To refresh par files, remove the ones in the workdir, then do "make <target.par>" in 
41 // AliRoot.
42 Bool_t      usePAR             = kFALSE;  // use par files for extra libs
43 Bool_t      useCPAR            = kFALSE;  // use par files for common libs
44 TString     root_version       = "v5-27-05";  // *CHANGE ME IF MORE RECENT IN GRID*
45 TString     aliroot_version    = "v4-20-06-AN-1";  // *CHANGE ME IF MORE RECENT IN GRID*                                          
46 // Change production base directory here
47 TString     alien_datadir      = "/alice/data/2010/LHC10d";
48 // AliEn output directory. If blank will become output_<train_name>
49 //TString     alien_outdir       = "/alice/data/2010/LHC10b/AOD1";
50 TString     alien_outdir       = "";
51 // Output folder to write delta AOD's. Considered if not null.
52 TString     outputSingleFolder = "";
53 //TString     outputSingleFolder = "deltas";
54 // Number of files merged in a chunk
55 Int_t       maxMergeFiles      = 20;
56 // Files that should not be merged
57 TString     mergeExclude       = "AliAOD.root AliAOD.VertexingHF.root AliAOD.Jets.root deltaAODPartCorr.root AliAOD.Muons.root AliAOD.Dimuons.root";
58 // Make replicas on the storages below
59 TString     outputStorages      = "disk=4";
60 // Number of runs per master job
61 Int_t       nRunsPerMaster     = 10;
62 // Maximum number of files per job (gives size of AOD)
63 Int_t       nFilesPerJob       = 50;
64 // Int_t       nFilesPerJob       = 1; (AOD->delta AOD production case)
65 // Set the run range
66 Int_t run_numbers[10] = {126432}; // **********************!!!!!!!
67 //Int_t       run_range[2]       =  {114786, 114949};  // LHC09a7   *CHANGE ME*
68 // ### Settings that make sense only for local analysis
69 //==============================================================================
70 // Change local xml dataset for local interactive analysis
71 TString     local_xmldataset   = "";
72
73 // ### Other flags to steer the analysis
74 //==============================================================================
75 Bool_t      usePhysicsSelection = kTRUE; // use physics selection
76 Bool_t      useTender           = kTRUE; // use tender wagon
77 Bool_t      useMergeViaJDL      = kTRUE;  // merge via JDL
78 Bool_t      useFastReadOption   = kTRUE;  // use xrootd tweaks
79 Bool_t      useOverwriteMode    = kTRUE;  // overwrite existing collections
80 Bool_t      useDATE             = kFALSE; // use date in train name
81 Bool_t      useDBG              = kTRUE;  // activate debugging
82 Bool_t      useMC               = kFALSE;  // use MC info
83 Bool_t      useTAGS             = kFALSE;  // use ESD tags for selection
84 Bool_t      useKFILTER          = kFALSE;  // use Kinematics filter
85 Bool_t      useTR               = kFALSE;  // use track references
86 Bool_t      useCORRFW           = kFALSE; // do not change
87 Bool_t      useAODTAGS          = kFALSE; // use AOD tags
88 Bool_t      saveTrain           = kTRUE;  // save train configuration as: 
89 Bool_t      saveCanvases        = kFALSE;  // save canvases created in Terminate
90 Bool_t      saveProofToAlien    = kFALSE; // save proof outputs in AliEn
91
92 // ### Analysis modules to be included. Some may not be yet fully implemented.
93 //==============================================================================
94 Int_t       iAODanalysis       = 0;      // Analysis on input AOD's
95 Int_t       iAODhandler        = 1;      // Analysis produces an AOD or dAOD's
96 Int_t       iESDfilter         = 1;      // ESD to AOD filter (barrel + muon tracks)
97 Int_t       iMUONcopyAOD       = 1;      // Task that copies only muon events in a separate AOD (PWG3)
98 Int_t       iJETAN             = 1;      // Jet analysis (PWG4)
99 Int_t       iJETANdelta        = 0;      // Jet delta AODs
100 Int_t       iPWG4partcorr      = 0;      // Gamma-hadron correlations task (PWG4)
101 Int_t       iPWG4gammaconv     = 0;      // Gamma conversion analysis (PWG4)
102 Int_t       iPWG4omega3pi      = 0;      // Omega to 3 pi analysis (PWG4)
103 Int_t       iPWG3vertexing     = 1;      // Vertexing HF task (PWG3)
104 Int_t       iPWG3hfe           = 0;      // Electrons analysis (PWG3)
105 Int_t       iPWG3d2h           = 0;      // D0->2 hadrons (PWG3)
106 Int_t        iPWG3d0mass       = 1;      // D0 mass (PWG3D2H)                                                                              
107 Int_t        iPWG3d0massLS     = 1;      // D0 mass LS (PWG3D2H)                                                                           
108 Int_t        iPWG3dplus        = 1;      // D+ analysis (PWG3D2H)                                                                          
109 Int_t        iPWG3LSd0         = 1;      // LS D0 analysis (PWG3D2H)                                                                       
110 Int_t        iPWG3LSjpsi       = 1;      // LS J/Psi analysis (PWG3D2H)                                                                    
111 Int_t        iPWG3CFd0         = 1;      // CF D0 analysis (PWG3D2H)                                                                       
112 Int_t        iPWG3promptd0     = 1;      // prompt D0 analysis (PWG3D2H)                                                                   
113 Int_t       iPWG3MuonTrain     = 0;      // Muon analysis train
114 Int_t       iPWG2femto         = 0;      // Femtoscopy task (PWG2)
115 Int_t       iPWG2spectra       = 0;      // Spectra tasks (PWG2
116 Int_t        iPWG2protons      = 1;         // Proton-antiproton analysis
117 Int_t        iPWG2checkcascade = 1;         // Check cascades task
118 Int_t        iPWG2perfcascade  = 1;         // Check performance cascade
119 Int_t        iPWG2checkv0      = 1;         // Check V0 task
120 Int_t        iPWG2strange      = 1;         // Strangeness task
121 Int_t        iPWG2central      = 1;         // Anisothropy in central collisions
122 Int_t       iPWG2flow          = 0;      // Flow analysis tasks (PWG2)
123 Int_t       iPWG2res           = 0;      // Resonances task (PWG2)
124 Int_t        iPWG2rsneff       = 0;      // Resonances efficiency
125 Int_t       iPWG2kink          = 0;      // Kink analysis tasks (PWG2)
126 Int_t        iPWG2kinkESDMC    = 1;         // Kink ESD-MC comparison (PWG2)
127 Int_t        iPWG2kinkLSKstar  = 1;      // Kink like-sign K* (PWG2)
128 Int_t        iPWG2kinkLSL1520  = 1;      // Kink like-sign L1520 (PWG2)
129 Int_t        iPWG2kinkLSPhi    = 1;      // Kink like-sign Phi (PWG2)
130 Int_t        iPWG2kinkKstarESD = 1;      // Kink Kstar ESD (PWG2)
131 Int_t        iPWG2kinkKstarMC  = 1;      // Kink Kstar MC (PWG2)
132 Int_t        iPWG2kinkL1520ESD = 1;      // Kink L1520 ESD (PWG2)
133 Int_t        iPWG2kinkL1520MC  = 1;      // Kink L1520 MC (PWG2)
134 Int_t        iPWG2kinkPhiESD   = 1;      // Kink resonances Phi ESD (PWG2)
135 Int_t        iPWG2kinkPhiMC    = 1;      // Kink resonances Phi MC (PWG2)
136 Int_t       iPWG2evchar        = 0;      // Event characteristics (PWG2)
137 Int_t       iPWG2unicor        = 0;      // Unicor analysis (PWG2)
138 Int_t       iPWG2forward       = 0;      // FMD analysis (PWG2)
139
140 // ### Configuration macros used for each module
141 //==============================================================================
142 TString     configPWG2femto    = "$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/Train/Train3/ConfigFemtoAnalysis.C";
143 //TString     configPWG3d2h      = "$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF_highmult.C";
144 TString     configPWG3d2h      = "$ALICE_ROOT/PWG3/vertexingHF/ConfigVertexingHF.C";
145 // Temporaries.
146 TString anaPars = "";
147 TString anaLibs = "";
148 // Function signatures
149 class AliAnalysisAlien;
150
151 //______________________________________________________________________________
152 void AnalysisTrainNew(const char *analysis_mode="grid", 
153                       const char *plugin_mode="full",
154                       const char *config_file="")
155 {
156 // Main analysis train macro. If a configuration file is provided, all parameters
157 // are taken from there but may be altered by CheckModuleFlags.
158    if (strlen(config_file) && !LoadConfig(config_file)) return;
159    TString smode(analysis_mode);
160    smode.ToUpper();
161    // Check compatibility of selected modules
162    CheckModuleFlags(smode);
163    if (saveTrain)              WriteConfig();
164
165    printf("==================================================================\n");
166    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", train_name.Data(),smode.Data());
167    printf("==================================================================\n");
168    printf("=  Configuring analysis train for:                               =\n");
169    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
170    else              printf("=  ESD analysis                                                  =\n");
171    if (usePhysicsSelection)   printf("=  Physics selection                                                =\n");
172    if (useTender)    printf("=  TENDER                                                        =\n");
173    if (iESDfilter)   printf("=  ESD filter                                                    =\n");
174    if (iMUONcopyAOD) printf("=  MUON copy AOD                                                 =\n");
175    if (iJETAN)       printf("=  Jet analysis                                                  =\n");
176    if (iJETANdelta)  printf("=     Jet delta AODs                                             =\n");
177    if (iPWG2spectra) {
178       printf("=  PWG2 SPECTRA tasks :                                          =\n");
179       if (iPWG2protons)      printf("=     PWG2 proton-antiproton                                     =\n");
180       if (iPWG2checkcascade) printf("=     PWG2 check cascades                                        =\n");
181       if (iPWG2perfcascade)  printf("=     PWG2 performance cascades                                  =\n");
182       if (iPWG2checkv0)      printf("=     PWG2 check V0                                              =\n");
183       if (iPWG2strange)      printf("=     PWG2 strangeness                                           =\n");
184       if (iPWG2central)      printf("=     PWG2 central                                               =\n");
185    }   
186    if (iPWG2femto) {
187       printf("=  PWG2 femtoscopy                                               =\n");
188       printf("   +++ configured by: %s\n", configPWG2femto.Data());
189    }   
190    if (iPWG2flow)    printf("=  PWG2 flow                                                     =\n");
191    if (iPWG2res)     printf("=  PWG2 resonances                                               =\n");
192       if (iPWG2rsneff)    printf("=     PWG2 resonances efficiency                                    =\n");
193    if (iPWG2kink) {
194       printf("=  PWG2 kink analysis tasks:                                     =\n");
195       if (iPWG2kinkESDMC)    printf("=     PWG2 ESD-MC kinks                                          =\n");
196       if (iPWG2kinkLSKstar)  printf("=     PWG2 kink like-sign analysis K*                            =\n");
197       if (iPWG2kinkLSL1520)  printf("=     PWG2 kink like-sign analysis L1520                         =\n");
198       if (iPWG2kinkLSPhi)    printf("=     PWG2 kink like-sign analysis Phi                           =\n");
199       if (iPWG2kinkKstarESD) printf("=     PWG2 kink Kstar ESD analysis                               =\n");
200       if (iPWG2kinkKstarMC)  printf("=     PWG2 kink Kstar MC analysis                                =\n");
201       if (iPWG2kinkL1520ESD) printf("=     PWG2 kink L1520 ESD analysis                               =\n");
202       if (iPWG2kinkL1520MC)  printf("=     PWG2 kink L1520 MC analysis                                =\n");
203       if (iPWG2kinkPhiESD) printf("=     PWG2 kink Phi ESD analysis                                 =\n");
204       if (iPWG2kinkPhiMC)  printf("=     PWG2 kink Phi MC analysis                                  =\n");
205   }   
206    if (iPWG2evchar)    printf("=  PWG2 event characteristics                                    =\n");
207    if (iPWG2unicor)    printf("=  PWG2 Unicor analysis                                          =\n");
208    if (iPWG2forward)   printf("=  PWG2 forward: sharing, density, bkg. correction, dNdEta       =\n");
209    if (iPWG3vertexing) printf("=  PWG3 vertexing                                                =\n");
210    if (iPWG3hfe)       printf("=  PWG3 electrons                                                =\n");
211    if (iPWG3d2h) {
212       printf("=  PWG3 D0->2 hadrons tasks                                      =\n");
213       printf("   +++ configured by: %s\n", configPWG3d2h.Data());
214       if (iPWG3d0mass)       printf("=     PWG3 D0 mass                                               =\n");                               
215       if (iPWG3d0massLS)     printf("=     PWG3 D0 mass LS                                            =\n");                               
216       if (iPWG3dplus)        printf("=     PWG3 D+ analysis                                           =\n");                               
217       if (iPWG3LSd0)         printf("=     PWG3 LS D0                                                 =\n");                               
218       if (iPWG3LSjpsi)       printf("=     PWG3 LS J/Psi                                              =\n");                               
219       if (iPWG3CFd0)         printf("=     PWG3 CF D0                                                 =\n");                               
220       if (iPWG3promptd0)     printf("=     PWG3 prompt D0                                             =\n");                               
221    }         
222    if (iPWG3MuonTrain) printf("=  PWG3 muon train                                               =\n");
223    if (iPWG4partcorr)  printf("=  PWG4 gamma-hadron, pi0 and gamma-jet correlations             =\n");
224    if (iPWG4gammaconv) printf("=  PWG4 gamma conversion                                         =\n");
225    if (iPWG4omega3pi)  printf("=  PWG4 omega to 3 pions                                         =\n");
226    printf("==================================================================\n");
227    printf(":: use physics selection: %d\n", (UInt_t)usePhysicsSelection);
228    printf(":: use xrootd tweaks:     %d\n", (UInt_t)useFastReadOption);
229    printf(":: use overwrite xml    : %d\n", (UInt_t)useOverwriteMode);
230    printf(":: use merge via JDL:     %d\n", (UInt_t)useMergeViaJDL);
231    printf(":: use MC truth:          %d\n", (UInt_t)useMC);
232    printf(":: use KINE filter:       %d\n", (UInt_t)useKFILTER);
233    printf(":: use track references:  %d\n", (UInt_t)useTR);
234    printf(":: use tags:              %d\n", (UInt_t)useTAGS);
235    printf(":: use AOD tags:          %d\n", (UInt_t)useAODTAGS);
236    printf(":: use debugging:         %d\n", (UInt_t)useDBG);
237    printf(":: use PAR files:         %d\n", (UInt_t)usePAR);
238    printf(":: use AliEn plugin:      %d\n", (UInt_t)usePLUGIN);
239
240    //==========================================================================
241    // Connect to back-end system
242    if (!Connect(smode)) {
243       ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
244       return;
245    }   
246
247    // Load common libraries and set include path
248    if (!LoadCommonLibraries(smode)) {
249       ::Error("AnalysisTrain", "Could not load common libraries");
250       return;
251    }
252     
253    // Make the analysis manager and connect event handlers
254    AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
255    if (saveProofToAlien) mgr->SetSpecialOutputLocation(proof_outdir);
256    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
257    // Load analysis specific libraries
258    if (!LoadAnalysisLibraries(smode)) {
259       ::Error("AnalysisTrain", "Could not load analysis libraries");
260       return;
261    }   
262
263    // Create input handler (input container created automatically)
264    if (iAODanalysis) {
265    // AOD input handler
266       AliAODInputHandler *aodH = new AliAODInputHandler();
267       if (iPWG3d2h) aodH->AddFriend("AliAOD.VertexingHF.root");
268       mgr->SetInputEventHandler(aodH);
269    } else {   
270    // ESD input handler
271       AliESDInputHandler *esdHandler = new AliESDInputHandler();
272       if (useTAGS) esdHandler->SetReadTags();
273       mgr->SetInputEventHandler(esdHandler);       
274    }
275    // Monte Carlo handler
276    if (useMC && !iAODanalysis) {
277       AliMCEventHandler* mcHandler = new AliMCEventHandler();
278       mgr->SetMCtruthEventHandler(mcHandler);
279       mcHandler->SetReadTR(useTR); 
280    }   
281    // AOD output container, created automatically when setting an AOD handler
282    if (iAODhandler) {
283       // AOD output handler
284       AliAODHandler* aodHandler   = new AliAODHandler();
285       aodHandler->SetOutputFileName("AliAOD.root");
286       mgr->SetOutputEventHandler(aodHandler);
287       if (iAODanalysis) {
288          aodHandler->SetFillAOD(kFALSE);
289          aodHandler->SetCreateNonStandardAOD();
290          if (iJETAN)         aodHandler->SetOutputFileName("AliAOD.Jets.root");
291 //         if (iPWG3vertexing) aodHandler->SetOutputFileName("AliAOD.VertexingHF.root");
292       } 
293    }
294    // Debugging if needed
295    if (useDBG) mgr->SetDebugLevel(3);
296    if (saveCanvases) mgr->SetSaveCanvases(kTRUE);
297
298    //==========================================================================
299    // Create the chain. In this example it is created only from ALIEN files but
300    // can be done to work in batch or grid mode as well.
301    TChain *chain = CreateChain(smode, plugin_mode);
302         
303    //==========================================================================
304    // Load the tasks configuration macros for all wagons. These files are supposed now to be
305    // in the current workdir, but in AliEn they will be in the file catalog, 
306    // mapped from AliRoot and pecified in the jdl input list.
307     
308    // For now connection to top input container and common AOD output container
309    // is done in this macro, but in future these containers will be connected
310    // from each task configuration macro.
311                                                                                                                                            
312    AddAnalysisTasks();                                                                                                                     
313                                                                                                                                            
314    // Run the analysis                                                                                                                     
315    //                                                                                                                                      
316    if (usePLUGIN) {                                                                                                                        
317       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);                                                                     
318       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);                                                              
319    }                                                                                                                                       
320                                                                                                                                            
321    if (mgr->InitAnalysis()) {                                                                                                              
322       mgr->PrintStatus();                                                                                                                  
323       if (saveTrain || strlen(config_file)) gSystem->ChangeDirectory(train_name);                                                          
324       StartAnalysis(smode, chain);                                                                                                         
325       if (saveTrain && smode=="GRID") {                                                                                                    
326          AliAnalysisAlien *gridhandler = (AliAnalysisAlien*)mgr->GetGridHandler();                                                         
327          TString alien_workdir = gGrid->GetHomeDirectory();                                                                                
328          alien_workdir += train_name;
329          alien_outdir = gridhandler->GetGridOutputDir();                                                                                   
330          printf("=== Registering ConfigTrain.C in the work directory <%s> ===\n",                                                          
331                 alien_workdir.Data());                                                                                                     
332          if (AliAnalysisAlien::FileExists(Form("%s/%sConfig.C", alien_workdir.Data(), train_name.Data())))                                 
333             gGrid->Rm(Form("%s/%sConfig.C", alien_workdir.Data(), train_name.Data()));                                                     
334          if (strcmp(plugin_mode, "test"))                                                                                                  
335             TFile::Cp(Form("file:%sConfig.C",train_name.Data()), Form("alien://%s/%sConfig.C", alien_workdir.Data(), train_name.Data()));  
336       }                                                                                                                                    
337    }                                                                                                                                       
338 }                                                                                                                                          
339                                                                                                                                             
340 //______________________________________________________________________________                                                           
341 void AddAnalysisTasks()                                                                                                                    
342 {                                                                                                                                          
343 // Add all analysis task wagons to the train                                                                                               
344    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();                                                                     
345
346   //
347   // Tender and supplies
348   //
349    if (useTender) {
350       gROOT->LoadMacro("$ALICE_ROOT/TENDER/TenderSupplies/AddTaskTender.C");
351       AliAnalysisTaskSE *tender = AddTaskTender(kTRUE);
352 //      tender->SelectCollisionCandidates();
353       tender->SetDebugLevel(2);
354    }
355    if (usePhysicsSelection) {
356    // Physics selection task
357       gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskPhysicsSelection.C");
358       mgr->RegisterExtraFile("event_stat.root");
359       AliPhysicsSelectionTask *physSel = AddTaskPhysicsSelection(useMC);
360    }
361
362    if (iESDfilter && !iAODanalysis) {
363       //  ESD filter task configuration.
364       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskESDFilter.C");
365       if (iMUONcopyAOD) {
366          printf("Registering delta AOD file\n");
367          mgr->RegisterExtraFile("AliAOD.Muons.root");
368          mgr->RegisterExtraFile("AliAOD.Dimuons.root");
369          AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER, kTRUE, kTRUE, usePhysicsSelection);
370       } else {
371          AliAnalysisTaskESDfilter *taskesdfilter = AddTaskESDFilter(useKFILTER, kFALSE, kFALSE, usePhysicsSelection);
372       }   
373    }   
374
375    // AOD tags
376    if (useAODTAGS) {
377       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
378       mgr->AddTask(tagTask);
379       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
380                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
381       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
382       mgr->ConnectOutput(tagTask, 1, coutTags);
383    }   
384     
385 // ********** PWG2 wagons ******************************************************
386    AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
387
388    // Proton analysis
389    if (iPWG2spectra) {
390       // protons
391       if (iPWG2protons) {
392         gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskProtons.C");
393         AliAnalysisTaskProtons *taskprotons = AddTaskProtons();
394         if (!taskprotons) ::Warning("AnalysisTrainNew", "AliAnalysisTaskProtons cannot run for this train conditions - EXCLUDED");
395       }  
396       // cascades
397       if (iPWG2checkcascade) {
398         gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckCascade.C");
399         AliAnalysisTaskCheckCascade *taskcheckcascade = AddTaskCheckCascade(iCollision,runOnData);
400         if (!taskcheckcascade) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckCascade cannot run for this train conditions - EXCLUDED");
401       }  
402       // v0's
403       if (iPWG2checkv0) {
404         gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckV0.C");
405         AliAnalysisTaskCheckV0 *taskcheckV0 = AddTaskCheckV0();
406         if (!taskcheckV0) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckV0 cannot run for this train conditions - EXCLUDED");
407       }  
408       // strangeness
409       if (iPWG2strange) {
410         gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskStrange.C");
411         AliAnalysisTaskStrange *taskstrange = AddTaskStrange();
412         if (!taskstrange) ::Warning("AnalysisTrainNew", "AliAnalysisTaskStrange cannot run for this train conditions - EXCLUDED");
413       }  
414       // performance cascades
415       if (iPWG2perfcascade) {
416         gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCheckPerformanceCascade.C");
417         AliAnalysisTaskCheckPerformanceCascade *taskperfcascade = AddTaskCheckPerformanceCascade();
418         if (!taskperfcascade) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCheckPerformanceCascade cannot run for this train conditions - EXCLUDED");
419       }  
420        // central
421       if (iPWG2central) {
422         gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskCentral.C");
423         AliAnalysisTaskCentral *taskcentral = AddTaskCentral();
424         if (!taskcentral) ::Warning("AnalysisTrainNew", "AliAnalysisTaskCentral cannot run for this train conditions - EXCLUDED");
425       }  
426   }   
427    
428    // Femtoscopy analysis modules
429    if (iPWG2femto) {
430       gROOT->LoadMacro("$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/AddTaskFemto.C");
431       AliAnalysisTaskFemto *taskfemto = AddTaskFemto(configPWG2femto);
432       if (!taskfemto) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFemto cannot run for this train conditions - EXCLUDED");
433    }   
434
435    // Kink analysis
436    if (iPWG2kink) {
437       if (iPWG2kinkESDMC) {
438         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKink.C");
439         AliAnalysisKinkESDMC *taskkink1 = AddTaskKink();
440         if (!taskkink1) ::Warning("AnalysisTrainNew", "AliAnalysisKinkESDMC cannot run for this train conditions - EXCLUDED");
441       }   
442       if (iPWG2kinkLSKstar) {
443         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResLikeSignKstar.C");
444         AliResonanceKinkLikeSign *taskkink2 = AddTaskKinkResLikeSignKstar();
445         if (!taskkink2) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
446       }  
447       if (iPWG2kinkLSL1520) {
448         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResLikeSignL1520.C");
449         AliResonanceKinkLikeSign *taskkink3 = AddTaskKinkResLikeSignL1520();
450         if (!taskkink3) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
451       }  
452       if (iPWG2kinkLSPhi) {
453         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResLikeSignPhi.C");
454         AliResonanceKinkLikeSign *taskkink4 = AddTaskKinkResLikeSignPhi();
455         if (!taskkink4) ::Warning("AnalysisTrainNew", "AliResonanceKinkLikeSign cannot run for this train conditions - EXCLUDED");
456       }  
457       if (iPWG2kinkKstarESD) {
458         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceKstarESD.C");
459         AliAnalysisTaskKinkResonance *taskkink5 = AddTaskKinkResonanceKstarESD();
460         if (!taskkink5) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceKstarESD cannot run for this train conditions - EXCLUDED");
461       }   
462       if (iPWG2kinkKstarMC) {
463         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceKstarMC.C");
464         AliAnalysisTaskKinkResonance *taskkink6 = AddTaskKinkResonanceKstarMC();
465         if (!taskkink6) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceKstarMC cannot run for this train conditions - EXCLUDED");
466       }   
467       if (iPWG2kinkL1520ESD) {
468         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceL1520ESD.C");
469         AliAnalysisTaskKinkResonance *taskkink7 = AddTaskKinkResonanceL1520ESD();
470         if (!taskkink7) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceL1520ESD cannot run for this train conditions - EXCLUDED");
471       }   
472       if (iPWG2kinkL1520MC) {
473         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonanceL1520MC.C");
474         AliAnalysisTaskKinkResonance *taskkink8 = AddTaskKinkResonanceL1520MC();
475         if (!taskkink8) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonanceL1520MC cannot run for this train conditions - EXCLUDED");
476       }   
477       if (iPWG2kinkPhiESD) {
478         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonancePhiESD.C");
479         AliAnalysisTaskKinkResonance *taskkink9 = AddTaskKinkResonancePhiESD();
480         if (!taskkink9) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonancePhiESD cannot run for this train conditions - EXCLUDED");
481       }   
482       if (iPWG2kinkPhiMC) {
483         gROOT->LoadMacro("$ALICE_ROOT/PWG2/KINK/macros/AddTaskKinkResonancePhiMC.C");
484         AliAnalysisTaskKinkResonance *taskkink10 = AddTaskKinkResonancePhiMC();
485         if (!taskkink10) ::Warning("AnalysisTrainNew", "AliAnalysisKinkResonancePhiMC cannot run for this train conditions - EXCLUDED");
486       }   
487    }   
488
489    // Event characterization
490    if (iPWG2evchar) {
491       gROOT->LoadMacro("$ALICE_ROOT/PWG2/EVCHAR/macros/AddTaskSPDdNdEta.C");
492       AliAnalysisTaskSPDdNdEta *taskspddndeta = AddTaskSPDdNdEta();
493       if (!taskspddndeta) ::Warning("AnalysisTrainNew", "AliAnalysisTaskSPDdNdEta cannot run for this train conditions - EXCLUDED");
494       taskspddndeta->SetReadMC(useMC);
495    }   
496
497    // Unicor
498    if (iPWG2unicor) {
499       gROOT->LoadMacro("$ALICE_ROOT/PWG2/UNICOR/AddTaskUnicor.C");
500       AliAnalysisTaskUnicor *taskunicor = AddTaskUnicor();
501       if (!taskunicor) ::Warning("AnalysisTrainNew", "AliAnalysisTaskUnicor cannot run for this train conditions - EXCLUDED");
502    }   
503
504    // Forward Multiplicity
505    AliAnalysisManager::SetCommonFileName("forward.root");
506    if (iPWG2forward) {
507       gROOT->LoadMacro("$ALICE_ROOT/PWG2/FORWARD/analysis2/AddTaskForwardMult.C");
508       gROOT->LoadMacro("$ALICE_ROOT/PWG2/FORWARD/analysis2/AddTaskCentralMult.C");
509       Bool_t   mc  = false;
510       UShort_t sys = 0; // 0: get from data, 1: pp, 2: AA 
511       UShort_t sNN = 0; // 0: get from data, otherwise center of mass
512                         // energy (per nucleon pair)
513       Short_t  fld = 0; // 0: get from data, otherwise L3 field in kG
514       AliAnalysisTask *taskForward = AddTaskForwardMult(mc, sys, sNN, fld);
515       if (!taskForward) 
516         ::Warning("AnalysisTrainNew", "AliForwardMultiplicityTask cannot run for this train conditions - EXCLUDED");
517       AliAnalysisTask *taskCentral = AddTaskCentralMult(mc, sys, sNN, fld);
518       if (!taskCentral) 
519         ::Warning("AnalysisTrainNew", "AliCentralMultiplicityTask cannot run for this train conditions - EXCLUDED");
520    }   
521    AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
522
523    // Flow analysis
524    if (iPWG2flow) {
525       gROOT->LoadMacro("$ALICE_ROOT/PWG2/FLOW/macros/AddTaskFlow.C");
526       Bool_t SP       = kTRUE;
527       Bool_t LYZ1SUM  = kTRUE;
528       Bool_t LYZ1PROD = kTRUE;
529       Bool_t LYZ2SUM  = kFALSE; 
530       Bool_t LYZ2PROD = kFALSE;
531       Bool_t LYZEP    = kFALSE; 
532       Bool_t GFC      = kTRUE;
533       Bool_t QC       = kTRUE;
534       Bool_t FQD      = kFALSE;
535       Bool_t MCEP     = kFALSE; //does not work yet 24/12/08
536       Bool_t kineFromESD = kTRUE;
537       Bool_t METHODS[] = {SP,LYZ1SUM,LYZ1PROD,LYZ2SUM,LYZ2PROD,LYZEP,GFC,QC,FQD,MCEP};
538       // Analysis type can be ESD, AOD, MC, ESDMC0, ESDMC1
539       TString type = "AOD";
540       if (!iAODanalysis) type = "ESD";
541       // Boolean to fill/not fill the QA histograms
542       Bool_t QA = kTRUE;   
543       // Boolean to use/not use weights for the Q vector
544       Bool_t WEIGHTS[] = {kFALSE,kFALSE,kFALSE}; //Phi, v'(pt), v'(eta)
545       AliAnalysisTaskFlowEvent* taskFE = AddTaskFlow(type,METHODS,QA,WEIGHTS);
546       if (!taskFE) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFlowEvent cannot run for this train conditions - EXCLUDED");
547    }   
548
549    // PWG2 resonances
550    AliAnalysisManager::SetCommonFileName("resonances.root");
551    if (iPWG2res) {
552       gROOT->LoadMacro("$ALICE_ROOT/PWG2/RESONANCES/macros/train/AddAnalysisTaskRsnNew.C");
553       gROOT->LoadMacro("$ALICE_ROOT/PWG2/RESONANCES/macros/train/AddAnalysisTaskRsnEffNew.C");
554       TString path = gROOT->GetMacroPath();
555       path += ":$ALICE_ROOT/PWG2/RESONANCES/macros/train";
556       gROOT->SetMacroPath(path);
557       AddAnalysisTaskRsn(kTRUE);
558       if (iPWG2rsneff) AddAnalysisTaskRsnEff();
559    }   
560    AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
561
562 // ********** PWG3 wagons ******************************************************
563    AliAnalysisManager::SetCommonFileName("PWG3histograms.root");
564            
565    // PWG3 vertexing
566    if (iPWG3vertexing) {
567       gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/macros/AddTaskVertexingHF.C");
568       if (!iPWG3d2h) TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("%s/ConfigVertexingHF.C", train_name.Data()));
569       AliAnalysisTaskSEVertexingHF *taskvertexingHF = AddTaskVertexingHF();
570       if (!taskvertexingHF) ::Warning("AnalysisTrainNew", "AliAnalysisTaskSEVertexingHF cannot run for this train conditions - EXCLUDED");
571       else mgr->RegisterExtraFile("AliAOD.VertexingHF.root");
572    }   
573       
574    // PWG3 electrons
575    if (iPWG3hfe) {
576       gROOT->LoadMacro("$ALICE_ROOT/PWG3/hfe/AddTaskHFE.C");
577       AliAnalysisTaskHFE *taskHFE = AddTaskHFE();
578       if (!taskHFE) ::Warning("AnalysisTrainNew", "AliAnalysisTaskHFE cannot run for this train conditions - EXCLUDED");
579    }   
580
581    // PWG3 D2h
582    if (iPWG3d2h) {
583       gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/AddD2HTrain.C");
584       TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("%s/ConfigVertexingHF.C", train_name.Data()));
585       AddD2HTrain(iPWG3d0mass,iPWG3d0massLS,iPWG3dplus, iPWG3LSd0, iPWG3LSjpsi, iPWG3CFd0, iPWG3promptd0);                                 
586    }   
587
588    // PWG3 muon
589    if (iPWG3MuonTrain) {
590       gROOT->LoadMacro("$ALICE_ROOT/PWG3/muon/AddPWG3MuonTrain.C");
591       // iESDAnalysis, iAODAnalysis -> flags to select if the train is AOD or ESD based
592       // iMuonDistributions, iSingleMuonANAlysis -> flags to switch on/off analysis wagons
593       Int_t isESDAnalysis = (iAODanalysis)?0:1;
594       Int_t isAODAnalysis = (iAODanalysis)?1:0;
595       Int_t addMuonDistributions = 1;
596       Int_t addSingleMuonAnalysis = 1;
597       Int_t addMuonHFAnalysis = 1;
598       Int_t ntaskmuon = AddPWG3MuonTrain(isESDAnalysis,isAODAnalysis,addMuonDistributions,addSingleMuonAnalysis,addMuonHFAnalysis);
599       printf("Added %d muon tasks\n", ntaskmuon);
600    }   
601       
602 // ********** PWG4 wagons ******************************************************
603    AliAnalysisManager::SetCommonFileName("PWG4histograms.root");
604
605     // Jet analysis
606    if (iJETAN) {
607       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskJets.C");
608       if (!iAODanalysis) {
609          // Default jet reconstructor running on ESD's
610          AliAnalysisTaskJets * taskjets = AddTaskJets();
611          if (!taskjets) ::Warning("AnalysisTrainNew", "AliAnalysisTaskJets cannot run for this train conditions - EXCLUDED");
612          if (iJETANdelta) {
613             AddTaskJetsDelta("AliAOD.Jets.root");
614             mgr->RegisterExtraFile("AliAOD.Jets.root");
615          }   
616       } else {
617          // AOD-based analysis. Add all reconstructors to write into delta AOD's
618          if (iJETANdelta) {
619             Int_t ntasksjets = AddTaskJetsDelta("AliAOD.Jets.root",0,kFALSE);
620             if (ntasksjets) printf("Added %d jet reconstructors\n", ntasksjets);
621          }
622       }      
623    }
624    // PWG4 hadron correlations
625    if (iPWG4partcorr) {
626       Bool_t isSimulation = (runOnData)?kFALSE:kTRUE;
627       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskPartCorr.C");
628       AliAnalysisTaskParticleCorrelation *taskpartcorrPHOS = AddTaskPartCorr("AOD", "PHOS", kFALSE, isSimulation);
629       if (!taskpartcorrPHOS) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation PHOS cannot run for this train conditions - EXCLUDED");
630       AliAnalysisTaskParticleCorrelation *taskpartcorrEMCAL = AddTaskPartCorr("AOD", "EMCAL", kFALSE, isSimulation);
631       if (!taskpartcorrEMCAL) ::Warning("AnalysisTrainNew", "AliAnalysisTaskParticleCorrelation EMCAL cannot run for this train conditions - EXCLUDED");
632       mgr->RegisterExtraFile("deltaAODPartCorr.root");
633    }   
634
635    // PWG4 gamma conversion analysis
636    if (iPWG4gammaconv) {
637       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskGammaConversion.C");
638       TString cdir = gSystem->WorkingDirectory();
639       gSystem->ChangeDirectory(gSystem->ExpandPathName("$ALICE_ROOT/PWG4/macros/"));
640       TString gcArguments = "-run-on-train   -use-own-xyz  -run-jet  -run-neutralmeson -no-aod  -apply-chi2-cut -low-memory -use-v0-multiplicity -move-bg-vertex ";
641       TString kGCAnalysisCutSelectionId="900110204010001";
642       gcArguments.Append(Form(" -set-cut-selection %s",kGCAnalysisCutSelectionId.Data()));
643       if(!useMC)gcArguments += " -mc-off";
644       AliAnalysisTaskGammaConversion * taskGammaConversion = AddTaskGammaConversion(gcArguments,mgr->GetCommonInputContainer());
645       gSystem->ChangeDirectory(cdir);
646       taskGammaConversion->SelectCollisionCandidates();
647       if (!taskGammaConversion) ::Warning("AnalysisTrainNew", "AliAnalysisTaskGammaConversion cannot run for these train conditions - EXCLUDED");
648    }   
649
650    // PWG4 omega to 3 pions analysis
651    if (iPWG4omega3pi) {
652       gROOT->LoadMacro("$ALICE_ROOT/PWG4/macros/AddTaskomega3pi.C");
653       AliAnalysisTaskOmegaPi0PiPi *taskomega3pi = AddTaskomega3pi();
654       if (!taskomega3pi) ::Warning("AnalysisTrainNew", "AliAnalysisTaskomega3pi cannot run for these train conditions - EXCLUDED");
655    }   
656 }
657
658 //______________________________________________________________________________
659 void StartAnalysis(const char *mode, TChain *chain) {
660 // Start analysis.
661    Int_t imode = -1;
662    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
663    if (!strcmp(mode, "LOCAL")) imode = 0;
664    if (!strcmp(mode, "PROOF")) imode = 1;
665    if (!strcmp(mode, "GRID"))  imode = 2;
666    switch (imode) {
667       case 0:
668          if (!chain) {
669             ::Error("AnalysisTrainNew.C::StartAnalysis", "Cannot create the chain");
670             return;
671          }   
672          mgr->StartAnalysis(mode, chain);
673          return;
674       case 1:
675          if (!proof_dataset.Length()) {
676             ::Error("AnalysisTrainNew.C::StartAnalysis", "proof_dataset is empty");
677             return;
678          }   
679          mgr->StartAnalysis(mode, proof_dataset, 1000);
680          return;
681       case 2:
682          if (usePLUGIN) {
683             if (!mgr->GetGridHandler()) {
684                ::Error("AnalysisTrainNew.C::StartAnalysis", "Grid plugin not initialized");
685                return;
686             }   
687             mgr->StartAnalysis("grid");
688          } else {
689             if (!chain) {
690                ::Error("AnalysisTrainNew.C::StartAnalysis", "Cannot create the chain");
691                return;
692             }   
693             mgr->StartAnalysis(mode, chain);
694          }   
695          return;
696    }      
697 }          
698     
699 //______________________________________________________________________________
700 void CheckModuleFlags(const char *mode) {
701 // Checks selected modules and insure compatibility
702    Int_t imode = -1;
703    if (!strcmp(mode, "LOCAL")) imode = 0;
704    if (!strcmp(mode, "PROOF")) imode = 1;
705    if (!strcmp(mode, "GRID"))  imode = 2;
706    if (!iJETAN) iJETANdelta = 0;
707    if (imode==1) {
708       if (!usePAR) {
709          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
710          usePAR = kTRUE;
711       }   
712    }  
713    if (imode != 2) {
714       ::Info("AnalysisTrainNew.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
715       usePLUGIN = kFALSE; 
716    }   
717    if (iAODanalysis) {
718    // AOD analysis
719       if (useMC)
720          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
721       if (useAODTAGS)
722          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
723       useMC = kFALSE;
724       useTR = kFALSE;
725       useAODTAGS = kFALSE;
726       if (iESDfilter)
727          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "ESD filter disabled in analysis on AOD's");
728       iESDfilter   = 0;
729       if (!iAODhandler) {
730          if (iJETAN) 
731             ::Info("AnalysisTrainNew.C::CheckModuleFlags", "JETAN disabled in analysis on AOD's without AOD handler");
732          iJETAN = 0;
733          iJETANdelta = 0;
734       }
735       // Disable tasks that do not work yet on AOD data
736       if (iPWG4gammaconv)
737          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4gammaconv disabled on AOD's without AOD handler");
738       iPWG4gammaconv = 0;   
739       if (iPWG2central)
740          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2central disabled on AOD's");
741          iPWG2central = 0;
742       if (iPWG2flow)
743          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2flow disabled on AOD's");
744          iPWG2flow = 0;
745       if (iPWG2femto)
746          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2femto disabled on AOD's");
747          iPWG2femto = 0;
748       if (iPWG2res)
749          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2res disabled on AOD's");
750          iPWG2res = 0;
751        if (iPWG2rsneff)
752          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2rsneff disabled on AOD's");
753          iPWG2rsneff = 0;
754      if (iPWG2kink)         
755          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2kink disabled in analysis on AOD's");
756          iPWG2kink = 0;
757       if (iPWG2unicor)         
758          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2unicor disabled in analysis on AOD's");
759          iPWG2unicor = 0;
760       if (iPWG2evchar)
761          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4evchar disabled on AOD's");
762          iPWG2evchar = 0;
763       if (iPWG2forward)         
764          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2forward disabled in analysis on AOD's");
765          iPWG2forward = 0;
766       if (iPWG3hfe)
767          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG3hfe disabled on AOD's");
768          iPWG3hfe = 0;
769       if (iPWG4omega3pi)
770          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG4omega3pi disabled on AOD's");
771          iPWG4omega3pi = 0;
772    } else {   
773    // ESD analysis
774       if (!useMC) useTR = kFALSE;
775       if (!useTR) {
776          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "iPWG2evchar disabled if not reading track references");
777          iPWG2evchar = 0;
778       }   
779    }
780    if (!useMC) {
781       if (iPWG2perfcascade)
782          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2perfcascade disabled without MC info");
783       iPWG2perfcascade = 0;   
784       if (iPWG2central)
785          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PWG2central disabled without MC info");
786          iPWG2central = 0;
787    }   
788    if (iJETAN && !iAODanalysis) iESDfilter=1;
789    if (iESDfilter) {iAODhandler=1; useCORRFW = kTRUE;}
790    if (iPWG2spectra || iPWG2flow || iPWG3vertexing || iPWG3hfe || iPWG2res || iPWG2rsneff) useCORRFW = kTRUE;
791    if (useKFILTER && !useMC) useKFILTER = kFALSE;
792    if (useAODTAGS && !iAODhandler) useAODTAGS = kFALSE;
793 }
794
795 //______________________________________________________________________________
796 Bool_t Connect(const char *mode) {
797 // Connect <username> to the back-end system.
798    Int_t imode = -1;
799    if (!strcmp(mode, "LOCAL")) imode = 0;
800    if (!strcmp(mode, "PROOF")) imode = 1;
801    if (!strcmp(mode, "GRID"))  imode = 2;
802    TString username = gSystem->Getenv("alien_API_USER");
803    switch (imode) {
804       case 0:
805          break;
806       case 1:
807          if  (!username.Length()) {
808             ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), "Make sure you:\n \
809                            1. Have called: alien-token-init <username>\n \
810                            2. Have called: >source /tmp/gclient_env_$UID");
811             return kFALSE;
812          }
813          ::Info("AnalysisTrainNew.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
814                 username.Data(), proof_cluster.Data());
815          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
816 //         TProof::Open(Form("%s@%s:31093", username.Data(), proof_cluster.Data()));       
817          TProof::Open(Form("%s@%s", username.Data(), proof_cluster.Data()));       
818          if (!gProof) {
819             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
820                ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
821             return kFALSE;
822          }
823          TGrid::Connect("alien://");
824          if (gGrid) {
825             TString homedir = gGrid->GetHomeDirectory();
826             TString workdir = homedir + train_name;
827             if (!gGrid->Cd(workdir)) {
828                gGrid->Cd(homedir);
829                if (gGrid->Mkdir(workdir)) {
830                   gGrid->Cd(train_name);
831                   ::Info("AnalysisTrainNew::Connect()", "Directory %s created", gGrid->Pwd());
832                }
833             }
834             gGrid->Mkdir("proof_output");
835             gGrid->Cd("proof_output");
836             proof_outdir = Form("alien://%s", gGrid->Pwd());
837          }   
838          break;
839       case 2:      
840          if (usePLUGIN && !gSystem->Getenv("alien_CLOSE_SE")) {
841             ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), 
842                            "When using the AliEn plugin it is preferable to define the \
843                            variable alien_CLOSE_SE in your environment.");
844             return kFALSE;
845          }
846          ::Info("AnalysisTrainNew.C::Connect", "Connecting user <%s> to AliEn ...", 
847                 username.Data());
848          TGrid::Connect("alien://");
849          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
850          break;
851       default:
852          ::Error("AnalysisTrainNew.C::Connect", "Unknown run mode: %s", mode);
853          return kFALSE;
854    }
855    ::Info("AnalysisTrainNew.C::Connect","Connected in %s mode", mode);
856    return kTRUE;
857 }
858
859 //______________________________________________________________________________
860 Bool_t LoadCommonLibraries(const char *mode)
861 {
862 // Load common analysis libraries.
863    Int_t imode = -1;
864    if (!strcmp(mode, "LOCAL")) imode = 0;
865    if (!strcmp(mode, "PROOF")) imode = 1;
866    if (!strcmp(mode, "GRID"))  imode = 2;
867    if (!gSystem->Getenv("ALICE_ROOT")) {
868       ::Error("AnalysisTrainNew.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
869       return kFALSE;
870    }   
871    Bool_t success = kTRUE;
872    // ROOT libraries
873    gSystem->Load("libTree");
874    gSystem->Load("libGeom");
875    gSystem->Load("libVMC");
876    gSystem->Load("libPhysics");
877    gSystem->Load("libMinuit");
878    
879    // Load framework classes. Par option ignored here.
880    switch (imode) {
881       case 0:
882       case 2:
883          if (useCPAR) {
884             success &= LoadLibrary("STEERBase", mode, kTRUE);
885             success &= LoadLibrary("ESD", mode, kTRUE);
886             success &= LoadLibrary("AOD", mode, kTRUE);
887             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
888             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
889             if (useCORRFW) success &= LoadLibrary("CORRFW", mode, kTRUE);
890          } else {   
891             success &= LoadLibrary("libSTEERBase.so", mode);
892             success &= LoadLibrary("libESD.so", mode);
893             success &= LoadLibrary("libAOD.so", mode);
894             success &= LoadLibrary("libANALYSIS.so", mode);
895             success &= LoadLibrary("libANALYSISalice.so", mode);
896             if (useCORRFW) success &= LoadLibrary("libCORRFW.so", mode);
897             gROOT->ProcessLine(".include $ALICE_ROOT/include");
898          }   
899          break;
900       case 1:
901          Int_t ires = -1;
902          if (useAFPAR && !gSystem->AccessPathName(AFversion)) ires = gProof->UploadPackage(AFversion);
903          if (ires < 0) {
904             success &= LoadLibrary("STEERBase", mode);
905             success &= LoadLibrary("ESD", mode);
906             success &= LoadLibrary("AOD", mode);
907             success &= LoadLibrary("ANALYSIS", mode);
908             success &= LoadLibrary("ANALYSISalice", mode);
909             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
910          } else { 
911             ires = gProof->EnablePackage(AFversion);
912             if (ires<0) success = kFALSE;
913             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
914          }
915          break;         
916       default:
917          ::Error("AnalysisTrainNew.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
918          return kFALSE;
919    }
920    if (success) {
921       ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
922       ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
923               gSystem->GetIncludePath());
924    } else {           
925       ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Load common libraries:    FAILED");
926    }   
927       
928    return success;
929 }
930
931 //______________________________________________________________________________
932 Bool_t LoadAnalysisLibraries(const char *mode)
933 {
934 // Load common analysis libraries.
935    Bool_t success = kTRUE;
936    if (useTender) {
937       if (!LoadLibrary("Tender", mode, kTRUE) ||
938           !LoadLibrary("TenderSupplies", mode, kTRUE)) return kFALSE;
939    }       
940    if (iESDfilter || iPWG3MuonTrain) {
941       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
942           !LoadLibrary("PWG3muon", mode, kTRUE)) return kFALSE;
943    }   
944    // JETAN
945    if (iJETAN) {
946       if (!LoadLibrary("JETAN", mode, kTRUE)) return kFALSE;
947    }
948    if (iJETANdelta) {
949       if (!LoadLibrary("JETAN", mode, kTRUE) ||
950           !LoadLibrary("CGAL", mode, kTRUE) ||
951           !LoadLibrary("fastjet", mode, kTRUE) ||
952           !LoadLibrary("siscone", mode, kTRUE) ||
953           !LoadLibrary("SISConePlugin", mode, kTRUE) ||
954           !LoadLibrary("FASTJETAN", mode, kTRUE)) return kFALSE;
955    }     
956    // PWG4 particle correlations
957    if (iPWG4partcorr) {   
958       if (!LoadLibrary("EMCALUtils", mode, kTRUE) ||
959           !LoadLibrary("PHOSUtils", mode, kTRUE) ||
960           !LoadLibrary("PWG4PartCorrBase", mode, kTRUE) ||
961           !LoadLibrary("PWG4PartCorrDep", mode, kTRUE)) return kFALSE;
962    }
963    // PWG4 gamma conversion
964    if (iPWG4gammaconv) {
965       if (!LoadLibrary("PWG4GammaConv", mode, kTRUE)) return kFALSE;
966    }      
967    // PWG4 omega to 3 pions
968    if (iPWG4omega3pi) {
969       if (!LoadLibrary("PWG4omega3pi", mode, kTRUE)) return kFALSE;
970    }      
971    // PWG2 task protons 
972    if (iPWG2spectra) {
973       if (!LoadLibrary("PWG2spectra", mode, kTRUE)) return kFALSE;
974    }
975    // PWG2 flow
976    if (iPWG2flow) {
977       if (!LoadLibrary("PWG2flowCommon", mode, kTRUE) ||
978           !LoadLibrary("PWG2flowTasks", mode, kTRUE)) return kFALSE;
979    }
980    // PWG2 resonances
981    if (iPWG2res || iPWG2rsneff) {
982       if (!LoadLibrary("PWG2resonances", mode, kTRUE)) return kFALSE;
983    }   
984    // PWG2 kink
985    if (iPWG2kink) {
986       if (!LoadLibrary("PWG2kink", mode, kTRUE)) return kFALSE;
987    }   
988    // PWG2 unicor
989    if (iPWG2unicor) {
990       if (!LoadLibrary("PWG2unicor", mode, kTRUE)) return kFALSE;
991    }   
992    // PWG2 evchar
993    if (iPWG2evchar) {
994       if (!LoadLibrary("PWG2evchar", mode, kTRUE)) return kFALSE;
995    }   
996    // PWG2 femtoscopy
997    if (iPWG2femto) {
998       if (!LoadLibrary("PWG2AOD", mode, kTRUE) ||
999           !LoadLibrary("PWG2femtoscopy", mode, kTRUE) ||
1000           !LoadLibrary("PWG2femtoscopyUser", mode, kTRUE)) return kFALSE;
1001 //      TFile::Cp(gSystem->ExpandPathName("$(ALICE_ROOT)/PWG2/FEMTOSCOPY/macros/ConfigFemtoAnalysis.C"), Form("%s/ConfigFemtoAnalysis.C", train_name.Data()));
1002 //      anaLibs += "ConfigFemtoAnalysis.C ";
1003    }   
1004    // PWG2 FORWARD
1005    if (iPWG2forward) {
1006       if (!LoadLibrary("PWG2forward2", mode, kTRUE)) return kFALSE;
1007    }   
1008    // PWG3 Vertexing HF
1009    if (iPWG3vertexing || iPWG3d2h) {
1010       if (!LoadLibrary("PWG3base", mode, kTRUE) ||
1011           !LoadLibrary("PWG3vertexingHF", mode, kTRUE)) return kFALSE;
1012    }   
1013    // PWG3 hfe
1014    if (iPWG3hfe) {
1015       if (!LoadLibrary("PWG3hfe", mode, kTRUE)) return kFALSE;
1016    }   
1017    
1018    ::Info("AnalysisTrainNew.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
1019    return kTRUE;
1020 }
1021
1022 //______________________________________________________________________________
1023 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
1024 {
1025 // Load a module library in a given mode. Reports success.
1026    Int_t imode = -1;
1027    Int_t result;
1028    TString smodule(module);
1029    if (!strcmp(mode, "LOCAL")) imode = 0;
1030    if (!strcmp(mode, "PROOF")) imode = 1;
1031    if (!strcmp(mode, "GRID"))  imode = 2;
1032    TString mod(module);
1033    if (!mod.Length()) {
1034       ::Error("AnalysisTrainNew.C::LoadLibrary", "Empty module name");
1035       return kFALSE;
1036    }   
1037    // If a library is specified, just load it
1038    if (smodule.EndsWith(".so")) {
1039       mod.Remove(mod.Index(".so"));
1040       result = gSystem->Load(mod);
1041       if (result < 0) {
1042          ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not load library %s", module);
1043          return kFALSE;
1044       }
1045       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
1046       return kTRUE;
1047    } 
1048    // Check if the library is already loaded
1049    if (strlen(gSystem->GetLibraries(module, "", kFALSE)) > 0)
1050       return kTRUE;    
1051    switch (imode) {
1052       case 0:
1053       case 2:
1054          if (usePAR) {
1055             result = SetupPar(module);
1056             if (rec) anaPars += Form("%s.par ", module);
1057          } else {
1058             result = gSystem->Load(Form("lib%s", module));
1059             if (rec) anaLibs += Form("lib%s.so ", module);
1060          }   
1061          break;
1062       case 1:
1063          result = gProof->UploadPackage(module);
1064          if (result<0) {
1065             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
1066             if (result<0) {
1067                ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
1068                return kFALSE;
1069             }
1070          }   
1071          result = gProof->EnablePackage(module);
1072          break;
1073       default:
1074          return kFALSE;
1075    }         
1076    if (result < 0) {
1077       ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not load module %s", module);
1078       return kFALSE;
1079    }
1080    return kTRUE;
1081 }           
1082
1083
1084 //______________________________________________________________________________
1085 TChain *CreateChain(const char *mode, const char *plugin_mode)
1086 {
1087 // Create the input chain
1088    Int_t imode = -1;
1089    if (!strcmp(mode, "LOCAL")) imode = 0;
1090    if (!strcmp(mode, "PROOF")) imode = 1;
1091    if (!strcmp(mode, "GRID"))  imode = 2;
1092    TChain *chain = NULL;
1093    // Local chain
1094    switch (imode) {
1095       case 0:
1096          if (iAODanalysis) {
1097             if (!local_xmldataset.Length()) {
1098                // Local AOD
1099                chain = new TChain("aodTree");
1100                if (gSystem->AccessPathName("data/AliAOD.root")) 
1101                   ::Error("AnalysisTrainNew.C::CreateChain", "File: AliAOD.root not in ./data dir");
1102                else {
1103                   if (!saveTrain) chain->Add("data/AliAOD.root");
1104                   else            chain->Add("../data/AliAOD.root");
1105                }   
1106             } else {
1107                // Interactive AOD
1108                chain = CreateChainSingle(local_xmldataset, "aodTree");
1109             }
1110          } else {      
1111             if (!local_xmldataset.Length()) {
1112                // Local ESD
1113                chain = new TChain("esdTree");
1114                if (gSystem->AccessPathName("data/AliESDs.root")) 
1115                   ::Error("AnalysisTrainNew.C::CreateChain", "File: AliESDs.root not in ./data dir");
1116                else {
1117                   if (!saveTrain) chain->Add("data/AliESDs.root");
1118                   else            chain->Add("../data/AliESDs.root");
1119                }   
1120             } else {
1121                // Interactive ESD
1122                chain = CreateChainSingle(local_xmldataset, "esdTree");
1123             }   
1124          }
1125          break;
1126       case 1:
1127          break;
1128       case 2:
1129          if (usePLUGIN) {
1130 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
1131 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
1132          } else {
1133             TString           treeName = "esdTree";
1134             if (iAODanalysis) treeName = "aodTree";
1135             chain = CreateChainSingle("wn.xml", treeName);
1136          }
1137          break;      
1138       default:   
1139    }
1140    if (chain && chain->GetNtrees()) return chain;
1141    return NULL;
1142 }   
1143
1144 //______________________________________________________________________________
1145 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
1146 {
1147    printf("*******************************\n");
1148    printf("*** Getting the ESD Chain   ***\n");
1149    printf("*******************************\n");
1150    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
1151
1152    if (!myCollection) {
1153       ::Error("AnalysisTrainNew.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
1154       return NULL ;
1155    }
1156
1157    TChain* chain = new TChain(treeName);
1158    myCollection->Reset() ;
1159    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
1160    chain->ls();
1161    return chain;
1162 }
1163
1164 //______________________________________________________________________________
1165 Int_t SetupPar(char* pararchivename)
1166 {
1167    if (!pararchivename || !strlen(pararchivename)) return -1;
1168    char processline[1024];
1169    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
1170       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
1171          ::Info("AnalysisTrainNew.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
1172          TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
1173                    Form("%s.par",pararchivename));
1174       } else {
1175          ::Error("AnalysisTrainNew.C::SetupPar", "Cannot find %s.par", pararchivename);
1176          return -1;
1177       }   
1178    }
1179    if (usePLUGIN && saveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, train_name.Data()));
1180    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
1181
1182    TString ocwd = gSystem->WorkingDirectory();
1183    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
1184         
1185    // check for BUILD.sh and execute
1186    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
1187       printf("*******************************\n");
1188       printf("*** Building PAR archive    ***\n");
1189       printf("*******************************\n");          
1190       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
1191          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
1192          return -1;
1193       }
1194    }
1195
1196         // check for SETUP.C and execute
1197         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
1198             printf("*******************************\n");
1199             printf("*** Setup PAR archive       ***\n");
1200             printf("*******************************\n");
1201             gROOT->Macro("PROOF-INF/SETUP.C");
1202         }       
1203         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
1204    return 0;
1205 }
1206
1207 //______________________________________________________________________________
1208 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
1209 {
1210 // Check if user has a valid token, otherwise make one. This has limitations.
1211 // One can always follow the standard procedure of calling alien-token-init then
1212 //   source /tmp/gclient_env_$UID in the current shell.
1213    if (!AliAnalysisGrid::CreateToken()) return NULL;
1214    AliAnalysisAlien *plugin = new AliAnalysisAlien();
1215 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
1216    plugin->SetRunMode(plugin_mode);
1217    if (useProductionMode) plugin->SetProductionMode();
1218    if (!outputSingleFolder.IsNull()) {
1219       plugin->SetOutputSingleFolder(outputSingleFolder);
1220       plugin->SetOutputToRunNo();
1221    }   
1222    plugin->SetJobTag(job_tag);
1223    plugin->SetNtestFiles(1);
1224 //   plugin->SetPreferedSE("ALICE::NIHAM::File");
1225 // Set versions of used packages
1226 //   plugin->SetAPIVersion("V2.4");
1227    plugin->SetAPIVersion("V1.1x");
1228    plugin->SetROOTVersion(root_version);
1229    plugin->SetAliROOTVersion(aliroot_version);
1230 // Declare input data to be processed.
1231 // Method 1: Create automatically XML collections using alien 'find' command.
1232 // Define production directory LFN
1233    plugin->SetGridDataDir(alien_datadir);
1234 // Set data search pattern
1235    if (runOnData) {
1236       plugin->SetRunPrefix("000");
1237       plugin->SetDataPattern("*ESDs/pass1/*ESDs.root");
1238    } else {
1239       plugin->SetDataPattern("*ESDs.root");
1240    }   
1241 // ...then add run numbers to be considered
1242 //   if (!iAODanalysis) plugin->SetRunRange(run_range[0], run_range[1]);
1243    for (Int_t i=0; i<10; i++) {
1244       if (run_numbers[i]==0) break;
1245       plugin->AddRunNumber(run_numbers[i]);
1246    }   
1247 // Method 2: Declare existing data files (raw collections, xml collections, root file)
1248 // If no path mentioned data is supposed to be in the work directory (see SetGridWorkingDir())
1249 // XML collections added via this method can be combined with the first method if
1250 // the content is compatible (using or not tags)
1251 //   plugin->AddDataFile("tag.xml");
1252 //   plugin->AddDataFile("/alice/data/2008/LHC08c/000057657/raw/Run57657.Merged.RAW.tag.root");
1253 // Define alien work directory where all files will be copied. Relative to alien $HOME.
1254    plugin->SetGridWorkingDir(train_name);
1255 // Declare alien output directory. Relative to working directory.
1256    if (!alien_outdir.Length()) alien_outdir = Form("output_%s",train_name.Data());
1257    plugin->SetGridOutputDir(alien_outdir);
1258
1259    TString ana_sources = "";
1260    TString ana_add = "";
1261    if (usePAR && anaPars.Length()) {
1262       printf("%s\n", anaPars.Data());
1263       TObjArray *arr;
1264       TObjString *objstr;
1265       arr = anaPars.Tokenize(" ");
1266       TIter next(arr);
1267       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
1268       delete arr;
1269    } 
1270 // Add external packages
1271    if (iJETANdelta) {
1272       plugin->AddExternalPackage("boost::v1_38_0");
1273       plugin->AddExternalPackage("cgal::v3.3.1");
1274       plugin->AddExternalPackage("fastjet::v2.4.0");
1275    }   
1276    
1277 // Declare the analysis source files names separated by blancs. To be compiled runtime
1278 // using ACLiC on the worker nodes.
1279    ana_sources = ana_sources.Strip();
1280 // Declare all libraries (other than the default ones for the framework. These will be
1281 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
1282    anaLibs     = anaLibs.Strip();   
1283    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
1284    if (anaLibs.Length())     plugin->SetAdditionalLibs(anaLibs);
1285      
1286 // Declare the output file names separated by blancs.
1287 // (can be like: file.root or file.root@ALICE::Niham::File)
1288    plugin->SetDefaultOutputs();
1289    plugin->SetMergeExcludes(mergeExclude);
1290    plugin->SetMaxMergeFiles(maxMergeFiles);
1291    plugin->SetNrunsPerMaster(nRunsPerMaster);
1292 // Optionally define the files to be archived.
1293 //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
1294    
1295    
1296    // Put default output files to archive
1297    TString listhists = "";
1298    TString listaods  = "";
1299    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
1300    TIter next(mgr->GetOutputs());
1301    AliAnalysisDataContainer *output;
1302    while ((output=(AliAnalysisDataContainer*)next())) {
1303       const char *filename = output->GetFileName();
1304       if (!(strcmp(filename, "default"))) {
1305          if (!mgr->GetOutputEventHandler()) continue;
1306          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
1307          if (listaods.Length()) listaods += ",";
1308          listaods += filename;
1309          listaods += ",";
1310          listaods += "pyxsec_hists.root";
1311       } else {
1312          if (!strcmp(filename, "pyxsec_hists.root")) continue;
1313          if (listhists.Contains(filename)) continue;
1314          if (listhists.Length()) listhists += ",";
1315          listhists += filename;
1316       }
1317    }
1318    if (mgr->GetExtraFiles().Length()) {
1319       if (listaods.Length()) listaods += ",";
1320       listaods += mgr->GetExtraFiles();
1321       listaods.ReplaceAll(" ", ",");
1322    }
1323    if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), outputStorages.Data());
1324    if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), outputStorages.Data());
1325    if (!listhists.Length() && !listaods.Length()) {
1326       ::Fatal("AnalysisTrainNew", "No task output !");
1327    }
1328    TString outputArchive = Form("log_archive.zip:stderr@%s", outputStorages.Data());
1329    if (listaods.Length()) {
1330       outputArchive += " ";
1331       outputArchive += listaods;
1332    }   
1333    if (listhists.Length()) {
1334       outputArchive += " ";
1335       outputArchive += listhists;
1336    }   
1337 // Set friends
1338 //   if (iAODanalysis && iPWG3d2h) 
1339 //      plugin->SetFriendChainName("AliAOD.VertexingHF.root");
1340 //   plugin->SetOutputArchive(outputArchive);
1341 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
1342    plugin->SetAnalysisMacro(Form("%s.C", train_name.Data()));
1343 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
1344    plugin->SetSplitMaxInputFileNumber(nFilesPerJob);
1345 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
1346 //   plugin->SetMaxInitFailed(5);
1347 // Optionally resubmit threshold.
1348 //   plugin->SetMasterResubmitThreshold(90);
1349 // Optionally set time to live (default 30000 sec)
1350    plugin->SetTTL(70000);
1351 // Optionally set input format (default xml-single)
1352    plugin->SetInputFormat("xml-single");
1353 // Optionally modify the name of the generated JDL (default analysis.jdl)
1354    plugin->SetJDLName(Form("%s.jdl", train_name.Data()));
1355 // Optionally modify the executable name (default analysis.sh)
1356    plugin->SetExecutable(Form("%s.sh", train_name.Data()));
1357 // Optionally modify job price (default 1)
1358    plugin->SetPrice(1);      
1359 // Merge via JDL
1360    plugin->SetMergeViaJDL(useMergeViaJDL);
1361 // Use fastread option
1362    plugin->SetFastReadOption(useFastReadOption);
1363 // UseOverwrite mode
1364    plugin->SetOverwriteMode(useOverwriteMode);   
1365    plugin->SetExecutableCommand("aliroot -b -q");
1366 // Optionally modify split mode (default 'se')    
1367    plugin->SetSplitMode("se");
1368    return plugin;
1369 }
1370
1371 //______________________________________________________________________________
1372 void WriteConfig()
1373 {
1374 // Write train configuration in a file. The file name has the format:
1375 // train_[trainName]_ddMonthyyyy_time.C
1376    if (useDATE) {
1377       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
1378       ifstream fdate("date.tmp");
1379       if (!fdate.is_open()) {
1380          ::Error("AnalysisTrainNew.C::Export","Could not generate file name");
1381          return;
1382       }
1383       const char date[64];
1384       fdate.getline(date,64);
1385       fdate.close();
1386       gSystem->Exec("rm date.tmp");
1387       train_name = Form("%s_%s", train_name.Data(), date);
1388    }   
1389    TString cdir = gSystem->WorkingDirectory();
1390    gSystem->MakeDirectory(train_name);
1391    gSystem->ChangeDirectory(train_name);
1392    ofstream out;
1393    out.open(Form("%sConfig.C",train_name.Data()), ios::out); 
1394    if (out.bad()) {
1395       ::Error("AnalysisTrainNew.C::Export", "Cannot open ConfigTrain.C for writing");
1396       return;
1397    }
1398    out << "{" << endl;
1399    out << "   train_name      = " << "\"" << train_name.Data() << "\";" << endl;
1400    out << "   proof_cluster   = " << "\"" << proof_cluster.Data() << "\";" << endl;
1401    out << "   useAFPAR        = " << useAFPAR << ";" << endl;
1402    if (useAFPAR) 
1403       out << "   AFversion       = " << AFversion.Data() << ";" << endl;
1404    out << "   proof_dataset   = " << "\"" << proof_dataset.Data() << "\";" << endl;
1405    out << "   usePLUGIN       = " << usePLUGIN << ";" << endl;
1406    out << "   usePAR          = " << usePAR << ";" << endl;
1407    out << "   useCPAR         = " << useCPAR << ";" << endl;
1408    out << "   root_version    = " << "\"" << root_version.Data() << "\";" << endl;
1409    out << "   aliroot_version = " << "\"" << aliroot_version.Data() << "\";" << endl;
1410    out << "   alien_datadir   = " << "\"" << alien_datadir.Data() << "\";" << endl;
1411    if (!alien_outdir.Length()) alien_outdir = Form("output_%s",train_name.Data());
1412    out << "   alien_outdir    = " << "\"" << alien_outdir.Data() << "\";" << endl;
1413    out << "   maxMergeFiles   = " << maxMergeFiles << ";" << endl;
1414    out << "   mergeExclude    = " << "\"" << mergeExclude.Data() << "\";" << endl;
1415    out << "   nRunsPerMaster  = " << nRunsPerMaster << ";" << endl;
1416    out << "   nFilesPerJob    = " << nFilesPerJob << ";" << endl;
1417 //   for (Int_t i=0; i<10; i++) {
1418 //      if (run_numbers[i]) 
1419 //         out << "   run_numbers[" << i << "]  = " << run_numbers[i] << ";" << endl;
1420 //   }
1421 //   out << "   run_range[0]    = " << run_range[0] << ";" << endl;
1422 //   out << "   run_range[1]    = " << run_range[1] << ";" << endl;
1423    out << "   usePhysicsSelection = " << usePhysicsSelection << ";" << endl;
1424    out << "   useTender       = " << useTender << ";" << endl;
1425    out << "   useMergeViaJDL  = " << useMergeViaJDL << ";" << endl;
1426    out << "   useOverwriteMode  = " << useOverwriteMode << ";" << endl;
1427    out << "   useFastReadOption = " << useFastReadOption << ";" << endl;
1428    out << "   useDBG          = " << useDBG << ";" << endl;
1429    out << "   useMC           = " << useMC << ";" << endl;
1430    out << "   useTAGS         = " << useTAGS << ";" << endl;
1431    out << "   useKFILTER      = " << useKFILTER << ";" << endl;
1432    out << "   useTR           = " << useTR << ";" << endl;
1433    out << "   useCORRFW       = " << useCORRFW << ";" << endl;
1434    out << "   useAODTAGS      = " << useAODTAGS << ";" << endl;
1435    out << "   saveTrain       = " << "kFALSE;" << endl << endl;
1436    out << "   // Analysis modules" << endl;
1437    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
1438    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
1439    out << "   iESDfilter      = " << iESDfilter << ";" << endl;
1440    out << "   iMUONcopyAOD    = " << iMUONcopyAOD << ";" << endl;
1441    out << "   iJETAN          = " << iJETAN << ";" << endl;
1442    out << "   iJETANdelta     = " << iJETANdelta << ";" << endl;
1443    out << "   iPWG4partcorr   = " << iPWG4partcorr << ";" << endl;
1444    out << "   iPWG4gammaconv  = " << iPWG4gammaconv << ";" << endl;
1445    out << "   iPWG4omega3pi   = " << iPWG4omega3pi << ";" << endl;
1446    out << "   iPWG3vertexing  = " << iPWG3vertexing << ";" << endl;   
1447    out << "   iPWG3hfe        = " << iPWG3hfe << ";" << endl;   
1448    out << "   iPWG3d2h        = " << iPWG3d2h << ";" << endl;   
1449    out << "     iPWG3d0mass       = " << iPWG3d0mass << ";" << endl;
1450    out << "     iPWG3d0massLS     = " << iPWG3d0massLS << ";" << endl;
1451    out << "     iPWG3dplus        = " << iPWG3dplus << ";" << endl;
1452    out << "     iPWG3LSd0         = " << iPWG3LSd0 << ";" << endl;
1453    out << "     iPWG3LSjpsi       = " << iPWG3LSjpsi << ";" << endl;
1454    out << "     iPWG3CFd0         = " << iPWG3CFd0 << ";" << endl;
1455    out << "     iPWG3promptd0     = " << iPWG3promptd0 << ";" << endl;
1456    out << "   iPWG3MuonTrain      = " << iPWG3MuonTrain << ";" << endl;   
1457    out << "   iPWG2femto      = " << iPWG2femto << ";" << endl;
1458    out << "   iPWG2spectra    = " << iPWG2spectra << ";" << endl;
1459    out << "     iPWG2protons      = " << iPWG2protons << ";" << endl;
1460    out << "     iPWG2checkcascade = " << iPWG2checkcascade << ";" << endl;
1461    out << "     iPWG2perfcascade  = " << iPWG2perfcascade << ";" << endl;
1462    out << "     iPWG2checkv0      = " << iPWG2checkv0 << ";" << endl;
1463    out << "     iPWG2strange      = " << iPWG2strange << ";" << endl;
1464    out << "     iPWG2central      = " << iPWG2central << ";" << endl;
1465    out << "   iPWG2flow       = " << iPWG2flow << ";" << endl;
1466    out << "   iPWG2res        = " << iPWG2res << ";" << endl;
1467    out << "     iPWG2rsneff   = " << iPWG2rsneff << ";" << endl;
1468    out << "   iPWG2kink       = " << iPWG2kink << ";" << endl;
1469    out << "     iPWG2kinkESDMC    = " << iPWG2kinkESDMC << ";" << endl;
1470    out << "     iPWG2kinkLSKstar  = " << iPWG2kinkLSKstar << ";" << endl;
1471    out << "     iPWG2kinkLSL1520  = " << iPWG2kinkLSL1520 << ";" << endl;
1472    out << "     iPWG2kinkLSPhi    = " << iPWG2kinkLSPhi << ";" << endl;
1473    out << "     iPWG2kinkKstarESD = " << iPWG2kinkKstarESD << ";" << endl;
1474    out << "     iPWG2kinkKstarMC  = " << iPWG2kinkKstarMC << ";" << endl;
1475    out << "     iPWG2kinkL1520ESD = " << iPWG2kinkL1520ESD << ";" << endl;
1476    out << "     iPWG2kinkL1520MC  = " << iPWG2kinkL1520MC << ";" << endl;
1477    out << "     iPWG2kinkPhiESD   = " << iPWG2kinkPhiESD << ";" << endl;
1478    out << "     iPWG2kinkPhiMC    = " << iPWG2kinkPhiMC << ";" << endl;
1479    out << "   iPWG2unicor     = " << iPWG2unicor << ";" << endl;
1480    out << "   iPWG2evchar     = " << iPWG2evchar << ";" << endl;
1481    out << "   iPWG2forward    = " << iPWG2forward << ";" << endl << endl;
1482    out << "// Configuration fot the wagons" << endl;
1483    out << "   configPWG2femto = \"" << configPWG2femto << "\";" << endl;
1484    out << "   configPWG3d2h   = \"" << configPWG3d2h << "\";" << endl;
1485    out << "}" << endl;
1486    ::Info("AnalysisTrainNew.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", train_name.Data()));
1487    gSystem->ChangeDirectory(cdir);
1488 }   
1489
1490 //______________________________________________________________________________
1491 Bool_t LoadConfig(const char *filename)
1492 {
1493 // Read train configuration from file
1494    if (gSystem->AccessPathName(filename)) {
1495       ::Error("AnalysisTrainNew.C::LoadConfig", "Config file name not found");
1496       return kFALSE;
1497    }   
1498    gROOT->ProcessLine(Form(".x %s", filename));
1499    ::Info("AnalysisTrainNew.C::LoadConfig", "Train configuration loaded from file %s", filename);
1500    return kTRUE;
1501 }