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