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