]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG2/centraltrain/AnalysisTrainPWG2.C
Update PWG2 central train macro
[u/mrichter/AliRoot.git] / PWG2 / centraltrain / AnalysisTrainPWG2.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         = "PWG2"; // local folder name
20 TString     train_tag          = "_Pb-Pb_";        // 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("PWG2%s$2_$3", train_tag.Data()); //# FIXED #
24                // Add train composition and other comments
25 TString     job_comment        = "PWG2 tasks on ESDs";
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-06c";  // *CHANGE ME IF MORE RECENT IN GRID*
51 TString     aliroot_version    = "v4-21-15-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/PWG2/PWG2_$2";
56                // Data pattern - change as needed for test mode
57 // TString     data_pattern       = "*ESDs/pass1/AOD033/*AOD.root";
58 TString     data_pattern       = "*ESDs/pass1/*ESDs.root";
59 // Set the run range
60 Int_t run_numbers[10] = {137844}; // **********************!!!!!!!
61 // AliEn output directory. If blank will become output_<train_name>
62                // Output directory (DON'T CHANGE)
63 TString     alien_outdir       = "$1/PWG2OUT$2";
64                // Input collection (production mode)
65 TString     data_collection    = "$1/input.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      = 20;
71 // Files that should not be merged
72 TString     mergeExclude       = "AliAOD.root AliAOD.VertexingHF.root AliAOD.Jets.root deltaAODPartCorr.root AliAOD.Muons.root AliAOD.Dimuons.root AliAOD.Dielectron.root AliAODCentrality.root";
73 TString     mergeDirName       = "PWG2OUT$2";
74 // Make replicas on the storages below
75 TString     outputStorages      = "disk=4";
76 // Number of runs per master job
77 Int_t       nRunsPerMaster     = 10;
78 // Maximum number of files per job (gives size of AOD)
79 Int_t       nFilesPerJob       = 5;
80 // Int_t       nFilesPerJob       = 1; (AOD->delta AOD production case)
81 // ### Settings that make sense only for local analysis
82 //==============================================================================
83 // Change local xml dataset for local interactive analysis
84 TString     local_xmldataset   = "";
85
86 // ### Other flags to steer the analysis
87 //==============================================================================
88 Bool_t      usePhysicsSelection = kFALSE; // use physics selection
89 Bool_t      useBKrejection      = kFALSE; // use BK rejection
90 Bool_t      useCentrality       = kTRUE; // centrality delta AOD
91 Bool_t      useTender           = kFALSE; // use tender wagon
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           = kTRUE; // 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
113 Int_t       iPWG2fmd           = 0;      // FMD forward analysis (PWG2)
114 Int_t       iPWG2femto         = 1;      // Femtoscopy two-track analysis (PWG2)
115 Int_t       iPWG2spectra       = 1;      // Charge hadron spectra (PWG2)
116
117 // Temporaries.
118 TString anaPars = "";
119 TString anaLibs = "";
120 // Function signatures
121 class AliAnalysisAlien;
122
123 //______________________________________________________________________________
124 void AnalysisTrainPWG2(const char *analysis_mode="local", 
125                        const char *plugin_mode="full",
126                        const char *config_file="")
127 {
128 // Main analysis train macro. If a configuration file is provided, all parameters
129 // are taken from there but may be altered by CheckModuleFlags.
130    if (strlen(config_file) && !LoadConfig(config_file)) return;
131    TString smode(analysis_mode);
132    smode.ToUpper();
133    TString spmode(plugin_mode);
134    spmode.ToLower();
135    if (spmode == "test") useProductionMode = kFALSE;
136    // Check compatibility of selected modules
137    CheckModuleFlags(smode);
138    if (saveTrain)              WriteConfig();
139
140    printf("==================================================================\n");
141    printf("===========    RUNNING ANALYSIS TRAIN %s IN %s MODE   ==========\n", train_name.Data(),smode.Data());
142    printf("==================================================================\n");
143    printf("=  Configuring analysis train for:                               =\n");
144    if (iAODanalysis) printf("=  AOD analysis                                                  =\n");
145    else              printf("=  ESD analysis                                                  =\n");
146    if (usePhysicsSelection)   printf("=  Physics selection                                                =\n");
147    if (useTender)    printf("=  TENDER                                                        =\n");
148    if (iPWG2fmd)       printf("=  PWG2 FMD                                                      =\n");
149    if (iPWG2femto)      printf("=  PWG2 Femtoscopy                                               =\n");
150    if (iPWG2spectra)      printf("=  PWG2 Charged Spectra                                          =\n");
151    printf("==================================================================\n");
152    printf(":: use physics selection: %d\n", (UInt_t)usePhysicsSelection);
153    printf(":: use xrootd tweaks:     %d\n", (UInt_t)useFastReadOption);
154    printf(":: use overwrite xml    : %d\n", (UInt_t)useOverwriteMode);
155    printf(":: use merge via JDL:     %d\n", (UInt_t)useMergeViaJDL);
156    printf(":: use MC truth:          %d\n", (UInt_t)useMC);
157    printf(":: use KINE filter:       %d\n", (UInt_t)useKFILTER);
158    printf(":: use track references:  %d\n", (UInt_t)useTR);
159    printf(":: use tags:              %d\n", (UInt_t)useTAGS);
160    printf(":: use AOD tags:          %d\n", (UInt_t)useAODTAGS);
161    printf(":: use debugging:         %d\n", (UInt_t)useDBG);
162    printf(":: use PAR files:         %d\n", (UInt_t)usePAR);
163    printf(":: use AliEn plugin:      %d\n", (UInt_t)usePLUGIN);
164
165    //==========================================================================
166    // Connect to back-end system
167 //   if (!Connect(smode)) {
168 //      ::Error("AnalysisTrain", "Could not connect to %s back-end", analysis_mode);
169 //      return;
170 //   }   
171
172    // Load common libraries and set include path
173    if (!LoadCommonLibraries(smode)) {
174       ::Error("AnalysisTrain", "Could not load common libraries");
175       return;
176    }
177     
178    // Make the analysis manager and connect event handlers
179    AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
180    if (saveProofToAlien) mgr->SetSpecialOutputLocation(proof_outdir);
181    if (!strcmp(plugin_mode, "test")) mgr->SetNSysInfo(1);
182    // Load analysis specific libraries
183    if (!LoadAnalysisLibraries(smode)) {
184       ::Error("AnalysisTrain", "Could not load analysis libraries");
185       return;
186    }   
187
188    // Create input handler (input container created automatically)
189    if (iAODanalysis) {
190    // AOD input handler
191       AliAODInputHandler *aodH = new AliAODInputHandler();
192       mgr->SetInputEventHandler(aodH);
193    } else {   
194    // ESD input handler
195       AliESDInputHandler *esdHandler = new AliESDInputHandler();
196       if (useTAGS) esdHandler->SetReadTags();
197       mgr->SetInputEventHandler(esdHandler);       
198    }
199    // Monte Carlo handler
200    if (useMC && !iAODanalysis) {
201       AliMCEventHandler* mcHandler = new AliMCEventHandler();
202       mgr->SetMCtruthEventHandler(mcHandler);
203       mcHandler->SetReadTR(useTR); 
204    }   
205    // AOD output container, created automatically when setting an AOD handler
206    if (iAODhandler) {
207       // AOD output handler
208       AliAODHandler* aodHandler   = new AliAODHandler();
209       aodHandler->SetOutputFileName("AliAOD.root");
210       mgr->SetOutputEventHandler(aodHandler);
211       if (iAODanalysis) {
212          aodHandler->SetFillAOD(kFALSE);
213          aodHandler->SetCreateNonStandardAOD();
214 //         if (iPWG3vertexing) aodHandler->SetOutputFileName("AliAOD.VertexingHF.root");
215       } 
216    }
217    // Debugging if needed
218    if (useDBG) mgr->SetDebugLevel(3);
219    if (saveCanvases) mgr->SetSaveCanvases(kTRUE);
220
221    //==========================================================================
222    // Create the chain. In this example it is created only from ALIEN files but
223    // can be done to work in batch or grid mode as well.
224    TChain *chain = CreateChain(smode, plugin_mode);
225         
226    //==========================================================================
227    // Load the tasks configuration macros for all wagons. These files are supposed now to be
228    // in the current workdir, but in AliEn they will be in the file catalog, 
229    // mapped from AliRoot and pecified in the jdl input list.
230     
231    // For now connection to top input container and common AOD output container
232    // is done in this macro, but in future these containers will be connected
233    // from each task configuration macro.
234                                                                                                                                            
235    AddAnalysisTasks();                                                                                                                     
236                                                                                                                                            
237    // Run the analysis                                                                                                                     
238    //                                                                                                                                      
239    if (usePLUGIN) {                                                                                                                        
240       AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);                                                                     
241       AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);                                                              
242    }                                                                                                                                       
243                                                                                                                                            
244    if (mgr->InitAnalysis()) {                                                                                                              
245       mgr->PrintStatus();                                                                                                                  
246       if (saveTrain || strlen(config_file)) gSystem->ChangeDirectory(train_name);                                                          
247       StartAnalysis(smode, chain);                                                                                                         
248    }                                                                                                                                       
249 }                                                                                                                                          
250                                                                                                                                             
251 //______________________________________________________________________________                                                           
252 void AddAnalysisTasks()                                                                                                                    
253 {                                                                                                                                          
254 // Add all analysis task wagons to the train                                                                                               
255    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();                                                                    
256
257   //
258   // Tender and supplies. Needs to be called for every event.
259   //
260    if (useTender) {
261       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/TenderSupplies/AddTaskTender.C");
262       // IF V0 tender needed, put kTRUE below
263       AliAnalysisTaskSE *tender = AddTaskTender(useV0tender);
264 //      tender->SetDebugLevel(2);
265    }
266
267    if (usePhysicsSelection) {
268    // Physics selection task
269       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
270       mgr->RegisterExtraFile("event_stat.root");
271       AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(useMC,useBKrejection);
272       mgr->AddStatisticsTask(AliVEvent::kMB);
273    }
274    
275    if (useCentrality) {
276    // Common Centrality task
277      AliCentralitySelectionTask *centralityTask = new AliCentralitySelectionTask("CentralitySelection");
278      mgr->AddTask(centralityTask);
279      mgr->ConnectInput(centralityTask, 0, mgr->GetCommonInputContainer());
280 //       gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPhysicsSelection.C");
281 //       mgr->RegisterExtraFile("event_stat.root");
282 //       AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(useMC,useBKrejection);
283 //       mgr->AddStatisticsTask(AliVEvent::kMB);
284    }
285    
286    // AOD tags
287    if (useAODTAGS) {
288       AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator("AOD Tag Creator");
289       mgr->AddTask(tagTask);
290       AliAnalysisDataContainer *coutTags = mgr->CreateContainer("cTag",  TTree::Class(), 
291                                            AliAnalysisManager::kOutputContainer, "AOD.tag.root");
292       mgr->ConnectInput (tagTask, 0, mgr->GetCommonInputContainer());
293       mgr->ConnectOutput(tagTask, 1, coutTags);
294    }   
295     
296
297 // ********** PWG2 wagons ******************************************************
298    AliAnalysisManager::SetCommonFileName("PWG2histograms.root");
299            
300    // PWG2 FMD
301    if (iPWG2fmd) {
302       gROOT->LoadMacro("$ALICE_ROOT/PWG2/FORWARD/analysis2/AddTaskFMD.C");
303       AliAnalysisTask *taskFMD = AddTaskFMD(useMC, iCollision+1, iCollision?7000:2750, 0.5);
304       if (!taskFMD) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFMD cannot run for this train conditions - EXCLUDED");
305    }  
306     
307    // PWG2 Femtoscopy
308    if (iPWG2femto) {
309      gROOT->LoadMacro("$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/AddTaskFemto.C");
310      AliAnalysisTask *taskFemto = AddTaskFemto("$ALICE_ROOT/PWG2/FEMTOSCOPY/macros/Train/TwoTrackQA/ConfigFemtoAnalysisCentral.C",Form("%i, %i, %i", iAODanalysis?0:1, iCollision, 0));
311      if (!taskFemto) ::Warning("AnalysisTrainNew", "AliAnalysisTaskFemto cannot run for this train conditions - EXCLUDED");
312    }         
313
314    // PWG2 Spectra
315    if (iPWG2spectra) {
316      gROOT->LoadMacro("$ALICE_ROOT/PWG2/SPECTRA/macros/AddTaskChargedHadronSpectraITSTruncatedMean.C");
317      AliAnalysisTask *taskSpectraITSTPC = AddTaskChargedHadronSpectraITSTruncatedMean(-1,-1,useMC,iCollision,"$ALICE_ROOT/PWG2/SPECTRA/macros/configChargedHadronSpectraITSTruncatedMeanTask.C");
318      if (!taskSpectraITSTPC) ::Warning("AnalysisTrainNew", "AliAnalysisTaskSpectraITSTPC cannot run for this train conditions - EXCLUDED");
319    }         
320 }
321
322 //______________________________________________________________________________
323 void StartAnalysis(const char *mode, TChain *chain) {
324 // Start analysis.
325    Int_t imode = -1;
326    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
327    if (!strcmp(mode, "LOCAL")) imode = 0;
328    if (!strcmp(mode, "PROOF")) imode = 1;
329    if (!strcmp(mode, "GRID"))  imode = 2;
330    switch (imode) {
331       case 0:
332          if (!chain) {
333             ::Error("AnalysisTrainNew.C::StartAnalysis", "Cannot create the chain");
334             return;
335          }   
336          mgr->StartAnalysis(mode, chain);
337          return;
338       case 1:
339          if (!proof_dataset.Length()) {
340             ::Error("AnalysisTrainNew.C::StartAnalysis", "proof_dataset is empty");
341             return;
342          }   
343          mgr->StartAnalysis(mode, proof_dataset, 1000);
344          return;
345       case 2:
346          if (usePLUGIN) {
347             if (!mgr->GetGridHandler()) {
348                ::Error("AnalysisTrainNew.C::StartAnalysis", "Grid plugin not initialized");
349                return;
350             }   
351             mgr->StartAnalysis("grid");
352          } else {
353             if (!chain) {
354                ::Error("AnalysisTrainNew.C::StartAnalysis", "Cannot create the chain");
355                return;
356             }   
357             mgr->StartAnalysis(mode, chain);
358          }   
359          return;
360    }      
361 }          
362     
363 //______________________________________________________________________________
364 void CheckModuleFlags(const char *mode) {
365 // Checks selected modules and insure compatibility
366    Int_t imode = -1;
367    if (!strcmp(mode, "LOCAL")) imode = 0;
368    if (!strcmp(mode, "PROOF")) imode = 1;
369    if (!strcmp(mode, "GRID"))  imode = 2;
370    if (imode==1) {
371       if (!usePAR) {
372          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "PAR files enabled due to PROOF analysis");
373          usePAR = kTRUE;
374       }   
375    }  
376    if (imode != 2) {
377       ::Info("AnalysisTrainNew.C::CheckModuleFlags", "AliEn plugin disabled since not in GRID mode");
378       usePLUGIN = kFALSE; 
379    }   
380    if (iAODanalysis) {
381    // AOD analysis
382       if (useMC)
383          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "MC usage disabled in analysis on AOD's");
384       if (useAODTAGS)
385          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "AOD tags usage disabled in analysis on AOD's");
386       useMC = kFALSE;
387       useTR = kFALSE;
388       useAODTAGS = kFALSE;
389    } else {   
390    // ESD analysis
391       if (!useMC) useTR = kFALSE;
392       if (!useTR) {
393          ::Info("AnalysisTrainNew.C::CheckModuleFlags", "iPWG2evchar disabled if not reading track references");
394          iPWG2evchar = 0;
395       }   
396    }
397    if (useKFILTER && !useMC) useKFILTER = kFALSE;
398    if (useAODTAGS && !iAODhandler) useAODTAGS = kFALSE;
399 }
400
401 //______________________________________________________________________________
402 Bool_t Connect(const char *mode) {
403 // Connect <username> to the back-end system.
404    Int_t imode = -1;
405    if (!strcmp(mode, "LOCAL")) imode = 0;
406    if (!strcmp(mode, "PROOF")) imode = 1;
407    if (!strcmp(mode, "GRID"))  imode = 2;
408    TString username = gSystem->Getenv("alien_API_USER");
409    switch (imode) {
410       case 0:
411          break;
412       case 1:
413          if  (!username.Length()) {
414             ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), "Make sure you:\n \
415                            1. Have called: alien-token-init <username>\n \
416                            2. Have called: >source /tmp/gclient_env_$UID");
417             return kFALSE;
418          }
419          ::Info("AnalysisTrainNew.C::Connect", "Connecting user <%s> to PROOF cluster <%s>", 
420                 username.Data(), proof_cluster.Data());
421          gEnv->SetValue("XSec.GSI.DelegProxy", "2");
422 //         TProof::Open(Form("%s@%s:31093", username.Data(), proof_cluster.Data()));       
423          TProof::Open(Form("%s@%s", username.Data(), proof_cluster.Data()));       
424          if (!gProof) {
425             if (strcmp(gSystem->Getenv("XrdSecGSISRVNAMES"), "lxfsrd0506.cern.ch"))
426                ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), "Environment XrdSecGSISRVNAMES different from lxfsrd0506.cern.ch");
427             return kFALSE;
428          }
429          TGrid::Connect("alien://");
430          if (gGrid) {
431             TString homedir = gGrid->GetHomeDirectory();
432             TString workdir = homedir + train_name;
433             if (!gGrid->Cd(workdir)) {
434                gGrid->Cd(homedir);
435                if (gGrid->Mkdir(workdir)) {
436                   gGrid->Cd(train_name);
437                   ::Info("AnalysisTrainNew::Connect()", "Directory %s created", gGrid->Pwd());
438                }
439             }
440             gGrid->Mkdir("proof_output");
441             gGrid->Cd("proof_output");
442             proof_outdir = Form("alien://%s", gGrid->Pwd());
443          }   
444          break;
445       case 2:      
446          if (usePLUGIN && !gSystem->Getenv("alien_CLOSE_SE")) {
447             ::Error(Form("AnalysisTrainNew.C::Connect <%s>", mode), 
448                            "When using the AliEn plugin it is preferable to define the \
449                            variable alien_CLOSE_SE in your environment.");
450             return kFALSE;
451          }
452          ::Info("AnalysisTrainNew.C::Connect", "Connecting user <%s> to AliEn ...", 
453                 username.Data());
454          TGrid::Connect("alien://");
455          if (!gGrid || !gGrid->IsConnected()) return kFALSE;
456          break;
457       default:
458          ::Error("AnalysisTrainNew.C::Connect", "Unknown run mode: %s", mode);
459          return kFALSE;
460    }
461    ::Info("AnalysisTrainNew.C::Connect","Connected in %s mode", mode);
462    return kTRUE;
463 }
464
465 //______________________________________________________________________________
466 Bool_t LoadCommonLibraries(const char *mode)
467 {
468 // Load common analysis libraries.
469    Int_t imode = -1;
470    if (!strcmp(mode, "LOCAL")) imode = 0;
471    if (!strcmp(mode, "PROOF")) imode = 1;
472    if (!strcmp(mode, "GRID"))  imode = 2;
473    if (!gSystem->Getenv("ALICE_ROOT")) {
474       ::Error("AnalysisTrainNew.C::LoadCommonLibraries", "Analysis train requires that analysis libraries are compiled with a local AliRoot"); 
475       return kFALSE;
476    }   
477    Bool_t success = kTRUE;
478    // ROOT libraries
479    gSystem->Load("libTree.so");
480    gSystem->Load("libGeom.so");
481    gSystem->Load("libVMC.so");
482    gSystem->Load("libPhysics.so");
483    gSystem->Load("libMinuit.so");
484    
485    // Load framework classes. Par option ignored here.
486    switch (imode) {
487       case 0:
488       case 2:
489          if (useCPAR) {
490             success &= LoadLibrary("STEERBase", mode, kTRUE);
491             success &= LoadLibrary("ESD", mode, kTRUE);
492             success &= LoadLibrary("AOD", mode, kTRUE);
493             success &= LoadLibrary("ANALYSIS", mode, kTRUE);
494             success &= LoadLibrary("ANALYSISalice", mode, kTRUE);
495             if (useCORRFW) success &= LoadLibrary("CORRFW", mode, kTRUE);
496          } else {   
497             success &= LoadLibrary("libSTEERBase.so", mode);
498             success &= LoadLibrary("libESD.so", mode);
499             success &= LoadLibrary("libAOD.so", mode);
500             success &= LoadLibrary("libANALYSIS.so", mode);
501             success &= LoadLibrary("libANALYSISalice.so", mode);
502             if (useCORRFW) success &= LoadLibrary("libCORRFW.so", mode);
503             gROOT->ProcessLine(".include $ALICE_ROOT/include");
504          }   
505          break;
506       case 1:
507          Int_t ires = -1;
508          if (useAFPAR && !gSystem->AccessPathName(AFversion)) ires = gProof->UploadPackage(AFversion);
509          if (ires < 0) {
510             success &= LoadLibrary("STEERBase", mode);
511             success &= LoadLibrary("ESD", mode);
512             success &= LoadLibrary("AOD", mode);
513             success &= LoadLibrary("ANALYSIS", mode);
514             success &= LoadLibrary("ANALYSISalice", mode);
515             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
516          } else { 
517             ires = gProof->EnablePackage(AFversion);
518             if (ires<0) success = kFALSE;
519             if (useCORRFW) success &= LoadLibrary("CORRFW", mode);
520          }
521          break;         
522       default:
523          ::Error("AnalysisTrainNew.C::LoadCommonLibraries", "Unknown run mode: %s", mode);
524          return kFALSE;
525    }
526    if (success) {
527       ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Load common libraries:    SUCCESS");
528       ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Include path for Aclic compilation:\n%s",
529               gSystem->GetIncludePath());
530    } else {           
531       ::Info("AnalysisTrainNew.C::LoadCommodLibraries", "Load common libraries:    FAILED");
532    }   
533       
534    return success;
535 }
536
537 //______________________________________________________________________________
538 Bool_t LoadAnalysisLibraries(const char *mode)
539 {
540 // Load common analysis libraries.
541    Bool_t success = kTRUE;
542    if (useTender) {
543       if (!LoadLibrary("TENDER", mode, kTRUE) ||
544           !LoadLibrary("TENDERSupplies", mode, kTRUE)) return kFALSE;
545    }       
546    // PWG2 fmd
547    if (iPWG2fmd) {
548       if (!LoadLibrary("PWG2forward", mode, kTRUE)) return kFALSE;
549    }   
550    // PWG2 femtoscopy
551    if (iPWG2femto) {
552       if (!LoadLibrary("PWG2AOD", mode, kTRUE) ||
553           !LoadLibrary("PWG2femtoscopy", mode, kTRUE) ||
554           !LoadLibrary("PWG2femtoscopyUser", mode, kTRUE)) return kFALSE;
555    }   
556    // PWG2 spectra
557    if (iPWG2spectra) {
558       if (!LoadLibrary("PWG2spectra", mode, kTRUE)) return kFALSE;
559    }
560    ::Info("AnalysisTrainNew.C::LoadAnalysisLibraries", "Load other libraries:   SUCCESS");
561    return kTRUE;
562 }
563
564 //______________________________________________________________________________
565 Bool_t LoadLibrary(const char *module, const char *mode, Bool_t rec=kFALSE)
566 {
567 // Load a module library in a given mode. Reports success.
568    Int_t imode = -1;
569    Int_t result;
570    TString smodule(module);
571    if (!strcmp(mode, "LOCAL")) imode = 0;
572    if (!strcmp(mode, "PROOF")) imode = 1;
573    if (!strcmp(mode, "GRID"))  imode = 2;
574    TString mod(module);
575    if (!mod.Length()) {
576       ::Error("AnalysisTrainNew.C::LoadLibrary", "Empty module name");
577       return kFALSE;
578    }   
579    // If a library is specified, just load it
580    if (smodule.EndsWith(".so")) {
581       mod.Remove(mod.Index(".so"));
582       result = gSystem->Load(mod);
583       if (result < 0) {
584          ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not load library %s", module);
585          return kFALSE;
586       }
587       if (rec) anaLibs += Form("%s.so ",mod.Data()); 
588       return kTRUE;
589    } 
590    // Check if the library is already loaded
591    if (strlen(gSystem->GetLibraries(Form("%s.so", module), "", kFALSE)) > 0)
592       return kTRUE;    
593    switch (imode) {
594       case 0:
595       case 2:
596          if (usePAR) {
597             result = SetupPar(module);
598             if (rec) anaPars += Form("%s.par ", module);
599          } else {
600             result = gSystem->Load(Form("lib%s.so", module));
601             if (rec) anaLibs += Form("lib%s.so ", module);
602          }   
603          break;
604       case 1:
605          result = gProof->UploadPackage(module);
606          if (result<0) {
607             result = gProof->UploadPackage(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", module)));
608             if (result<0) {
609                ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not find module %s.par in current directory nor in $ALICE_ROOT", module);
610                return kFALSE;
611             }
612          }   
613          result = gProof->EnablePackage(module);
614          break;
615       default:
616          return kFALSE;
617    }         
618    if (result < 0) {
619       ::Error("AnalysisTrainNew.C::LoadLibrary", "Could not load module %s", module);
620       return kFALSE;
621    }
622    return kTRUE;
623 }           
624
625
626 //______________________________________________________________________________
627 TChain *CreateChain(const char *mode, const char *plugin_mode)
628 {
629 // Create the input chain
630    Int_t imode = -1;
631    if (!strcmp(mode, "LOCAL")) imode = 0;
632    if (!strcmp(mode, "PROOF")) imode = 1;
633    if (!strcmp(mode, "GRID"))  imode = 2;
634    TChain *chain = NULL;
635    // Local chain
636    switch (imode) {
637       case 0:
638          if (iAODanalysis) {
639             if (!local_xmldataset.Length()) {
640                // Local AOD
641                chain = new TChain("aodTree");
642                if (gSystem->AccessPathName("data/AliAOD.root")) 
643                   ::Error("AnalysisTrainNew.C::CreateChain", "File: AliAOD.root not in ./data dir");
644                else {
645                   if (!saveTrain) chain->Add("data/AliAOD.root");
646                   else            chain->Add("../data/AliAOD.root");
647                }   
648             } else {
649                // Interactive AOD
650                chain = CreateChainSingle(local_xmldataset, "aodTree");
651             }
652          } else {      
653             if (!local_xmldataset.Length()) {
654                // Local ESD
655                chain = new TChain("esdTree");
656                if (gSystem->AccessPathName("data/AliESDs.root")) 
657                   ::Error("AnalysisTrainNew.C::CreateChain", "File: AliESDs.root not in ./data dir");
658                else {
659                   if (!saveTrain) chain->Add("data/AliESDs.root");
660                   else            chain->Add("../data/AliESDs.root");
661                }   
662             } else {
663                // Interactive ESD
664                chain = CreateChainSingle(local_xmldataset, "esdTree");
665             }   
666          }
667          break;
668       case 1:
669          break;
670       case 2:
671          if (usePLUGIN) {
672 //            AliAnalysisGrid *alienHandler = CreateAlienHandler(plugin_mode);
673 //            AliAnalysisManager::GetAnalysisManager()->SetGridHandler(alienHandler);
674          } else {
675             TString           treeName = "esdTree";
676             if (iAODanalysis) treeName = "aodTree";
677             chain = CreateChainSingle("wn.xml", treeName);
678          }
679          break;      
680       default:   
681    }
682    if (chain && chain->GetNtrees()) return chain;
683    return NULL;
684 }   
685
686 //______________________________________________________________________________
687 TChain* CreateChainSingle(const char* xmlfile, const char *treeName)
688 {
689    printf("*******************************\n");
690    printf("*** Getting the ESD Chain   ***\n");
691    printf("*******************************\n");
692    TAlienCollection * myCollection  = TAlienCollection::Open(xmlfile);
693
694    if (!myCollection) {
695       ::Error("AnalysisTrainNew.C::CreateChainSingle", "Cannot create an AliEn collection from %s", xmlfile) ;
696       return NULL ;
697    }
698
699    TChain* chain = new TChain(treeName);
700    myCollection->Reset() ;
701    while ( myCollection->Next() ) chain->Add(myCollection->GetTURL("")) ;
702    chain->ls();
703    return chain;
704 }
705
706 //______________________________________________________________________________
707 Int_t SetupPar(char* pararchivename)
708 {
709    if (!pararchivename || !strlen(pararchivename)) return -1;
710    char processline[1024];
711    if (gSystem->AccessPathName(Form("%s.par", pararchivename))) {
712       if (!gSystem->AccessPathName(Form("%s/%s.par", gSystem->Getenv("ALICE_ROOT"),pararchivename))) {
713          ::Info("AnalysisTrainNew.C::SetupPar", "Getting %s.par from $ALICE_ROOT", pararchivename);
714          TFile::Cp(gSystem->ExpandPathName(Form("$ALICE_ROOT/%s.par", pararchivename)), 
715                    Form("%s.par",pararchivename));
716       } else {
717          ::Error("AnalysisTrainNew.C::SetupPar", "Cannot find %s.par", pararchivename);
718          return -1;
719       }   
720    }
721    if (usePLUGIN && saveTrain) gSystem->Exec(Form("ln -s ../%s.par %s",pararchivename, train_name.Data()));
722    gSystem->Exec(Form("tar xvzf %s.par", pararchivename));
723
724    TString ocwd = gSystem->WorkingDirectory();
725    if (!gSystem->ChangeDirectory(pararchivename)) return -1;
726         
727    // check for BUILD.sh and execute
728    if (!gSystem->AccessPathName("PROOF-INF/BUILD.sh")) {
729       printf("*******************************\n");
730       printf("*** Building PAR archive    ***\n");
731       printf("*******************************\n");          
732       if (gSystem->Exec("PROOF-INF/BUILD.sh")) {
733          Error("runProcess","Cannot Build the PAR Archive! - Abort!");
734          return -1;
735       }
736    }
737
738         // check for SETUP.C and execute
739         if (!gSystem->AccessPathName("PROOF-INF/SETUP.C")) {
740             printf("*******************************\n");
741             printf("*** Setup PAR archive       ***\n");
742             printf("*******************************\n");
743             gROOT->Macro("PROOF-INF/SETUP.C");
744         }       
745         if (!gSystem->ChangeDirectory(ocwd.Data())) return -1;
746    return 0;
747 }
748
749 //______________________________________________________________________________
750 AliAnalysisAlien* CreateAlienHandler(const char *plugin_mode)
751 {
752 // Check if user has a valid token, otherwise make one. This has limitations.
753 // One can always follow the standard procedure of calling alien-token-init then
754    AliAnalysisAlien *plugin = new AliAnalysisAlien();
755 // Set the run mode (can be "full", "test", "offline", "submit" or "terminate")
756    plugin->SetRunMode(plugin_mode);
757    if (useProductionMode) {
758       plugin->SetProductionMode();
759       plugin->AddDataFile(data_collection);
760    }   
761       
762    if (!outputSingleFolder.IsNull()) {
763       plugin->SetOutputSingleFolder(outputSingleFolder);
764       plugin->SetOutputToRunNo();
765    } 
766    plugin->SetJobTag(job_tag);
767    plugin->SetNtestFiles(5);
768    plugin->SetCheckCopy(kFALSE);
769    plugin->SetMergeDirName(mergeDirName);
770 // Set versions of used packages
771    plugin->SetAPIVersion("V1.1x");
772    plugin->SetROOTVersion(root_version);
773    plugin->SetAliROOTVersion(aliroot_version);
774 // Declare input data to be processed.
775 // Method 1: Create automatically XML collections using alien 'find' command.
776 // Define production directory LFN
777    plugin->SetGridDataDir(alien_datadir);
778 // Set data search pattern
779    plugin->SetDataPattern(data_pattern);
780    if (!useProductionMode) {
781       if (runOnData) {
782          plugin->SetRunPrefix("%09d");
783       }   
784 //   if (!iAODanalysis) plugin->SetRunRange(run_range[0], run_range[1]);
785       for (Int_t i=0; i<10; i++) {
786          if (run_numbers[i]==0) break;
787          plugin->AddRunNumber(run_numbers[i]);
788       }   
789    }   
790 // Define alien work directory where all files will be copied. Relative to alien $HOME.
791    plugin->SetGridWorkingDir(grid_workdir);
792 // Declare alien output directory. Relative to working directory.
793    if (alien_outdir.IsNull()) alien_outdir = Form("output_%s",train_name.Data());
794    plugin->SetGridOutputDir(alien_outdir);
795
796    TString ana_sources = "";
797    TString ana_add = "";
798    if (usePAR && anaPars.Length()) {
799       printf("%s\n", anaPars.Data());
800       TObjArray *arr;
801       TObjString *objstr;
802       arr = anaPars.Tokenize(" ");
803       TIter next(arr);
804       while ((objstr=(TObjString*)next())) plugin->EnablePackage(objstr->GetString());
805       delete arr;
806    } 
807    
808 // Declare the analysis source files names separated by blancs. To be compiled runtime
809 // using ACLiC on the worker nodes.
810    ana_sources = ana_sources.Strip();
811 // Declare all libraries (other than the default ones for the framework. These will be
812 // loaded by the generated analysis macro. Add all extra files (task .cxx/.h) here.
813    anaLibs     = anaLibs.Strip();   
814    if (ana_sources.Length()) plugin->SetAnalysisSource(ana_sources);
815    if (anaLibs.Length())     plugin->SetAdditionalLibs(anaLibs);
816      
817 // Declare the output file names separated by blancs.
818 // (can be like: file.root or file.root@ALICE::Niham::File)
819    plugin->SetDefaultOutputs();
820    plugin->SetMergeExcludes(mergeExclude);
821    plugin->SetMaxMergeFiles(maxMergeFiles);
822    plugin->SetNrunsPerMaster(nRunsPerMaster);
823 // Optionally define the files to be archived.
824 //   plugin->SetOutputArchive("log_archive.zip:stdout,stderr@ALICE::NIHAM::File root_archive.zip:AliAOD.root,AOD.tag.root@ALICE::NIHAM::File");
825    
826    
827    // Put default output files to archive
828    TString listhists = "";
829    TString listaods  = "";
830    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
831    TIter next(mgr->GetOutputs());
832    AliAnalysisDataContainer *output;
833    while ((output=(AliAnalysisDataContainer*)next())) {
834       const char *filename = output->GetFileName();
835       if (!(strcmp(filename, "default"))) {
836          if (!mgr->GetOutputEventHandler()) continue;
837          filename = mgr->GetOutputEventHandler()->GetOutputFileName();
838          if (listaods.Length()) listaods += ",";
839          listaods += filename;
840          listaods += ",";
841          listaods += "pyxsec_hists.root";
842       } else {
843          if (!strcmp(filename, "pyxsec_hists.root")) continue;
844          if (listhists.Contains(filename)) continue;
845          if (listhists.Length()) listhists += ",";
846          listhists += filename;
847       }
848    }
849    if (mgr->GetExtraFiles().Length()) {
850       if (listaods.Length()) listaods += ",";
851       listaods += mgr->GetExtraFiles();
852       listaods.ReplaceAll(" ", ",");
853    }
854    if (listhists.Length()) listhists = Form("hist_archive.zip:%s@%s", listhists.Data(), outputStorages.Data());
855    if (listaods.Length())  listaods  = Form("aod_archive.zip:%s@%s", listaods.Data(), outputStorages.Data());
856    if (!listhists.Length() && !listaods.Length()) {
857       ::Fatal("AnalysisTrainNew", "No task output !");
858    }
859    TString outputArchive = Form("log_archive.zip:stderr@%s", outputStorages.Data());
860    if (listaods.Length()) {
861       outputArchive += " ";
862       outputArchive += listaods;
863    }   
864    if (listhists.Length()) {
865       outputArchive += " ";
866       outputArchive += listhists;
867    }   
868 // Set friends
869 //   if (iAODanalysis && iPWG3d2h) 
870 //      plugin->SetFriendChainName("AliAOD.VertexingHF.root");
871 //   plugin->SetOutputArchive(outputArchive);
872 // Optionally set a name for the generated analysis macro (default MyAnalysis.C)
873    plugin->SetAnalysisMacro(Form("%s.C", train_name.Data()));
874 // Optionally set a name for the generated validation script
875    plugin->SetValidationScript("PWG2validation.sh");
876 // Optionally set maximum number of input files/subjob (default 100, put 0 to ignore)
877    plugin->SetSplitMaxInputFileNumber(nFilesPerJob);
878 // Optionally set number of failed jobs that will trigger killing waiting sub-jobs.
879 //   plugin->SetMaxInitFailed(5);
880 // Optionally modify the number of replicas
881    plugin->SetNumberOfReplicas(4);
882 // Optionally resubmit threshold.
883 //   plugin->SetMasterResubmitThreshold(90);
884 // Optionally set time to live (default 30000 sec)
885    plugin->SetTTL(70000);
886 // Optionally set input format (default xml-single)
887    plugin->SetInputFormat("xml-single");
888 // Optionally modify the name of the generated JDL (default analysis.jdl)
889    plugin->SetJDLName(Form("%s.jdl", train_name.Data()));
890 // Optionally modify the executable name (default analysis.sh)
891    plugin->SetExecutable(Form("%s.sh", train_name.Data()));
892 // Optionally modify job price (default 1)
893    plugin->SetPrice(1);      
894 // Merge via JDL
895    plugin->SetMergeViaJDL(useMergeViaJDL);
896 // Use fastread option
897    plugin->SetFastReadOption(useFastReadOption);
898 // UseOverwrite mode
899    plugin->SetOverwriteMode(useOverwriteMode);   
900    plugin->SetExecutableCommand("aliroot -b -q");
901 // Optionally modify split mode (default 'se')    
902    plugin->SetSplitMode("se");
903    return plugin;
904 }
905
906 //______________________________________________________________________________
907 void WriteConfig()
908 {
909 // Write train configuration in a file. The file name has the format:
910 // train_[trainName]_ddMonthyyyy_time.C
911    if (useDATE) {
912       gSystem->Exec("date +%d%b%Y_%Hh%M > date.tmp");
913       ifstream fdate("date.tmp");
914       if (!fdate.is_open()) {
915          ::Error("AnalysisTrainNew.C::Export","Could not generate file name");
916          return;
917       }
918       const char date[64];
919       fdate.getline(date,64);
920       fdate.close();
921       gSystem->Exec("rm date.tmp");
922       train_name = Form("%s_%s", train_name.Data(), date);
923    }   
924    TString cdir = gSystem->WorkingDirectory();
925    gSystem->MakeDirectory(train_name);
926    gSystem->ChangeDirectory(train_name);
927    ofstream out;
928    out.open(Form("%sConfig.C",train_name.Data()), ios::out); 
929    if (out.bad()) {
930       ::Error("AnalysisTrainNew.C::Export", "Cannot open ConfigTrain.C for writing");
931       return;
932    }
933    out << "{" << endl;
934    out << "   train_name      = " << "\"" << train_name.Data() << "\";" << endl;
935    out << "   proof_cluster   = " << "\"" << proof_cluster.Data() << "\";" << endl;
936    out << "   useAFPAR        = " << useAFPAR << ";" << endl;
937    if (useAFPAR) 
938       out << "   AFversion       = " << AFversion.Data() << ";" << endl;
939    out << "   proof_dataset   = " << "\"" << proof_dataset.Data() << "\";" << endl;
940    out << "   usePLUGIN       = " << usePLUGIN << ";" << endl;
941    out << "   usePAR          = " << usePAR << ";" << endl;
942    out << "   useCPAR         = " << useCPAR << ";" << endl;
943    out << "   root_version    = " << "\"" << root_version.Data() << "\";" << endl;
944    out << "   aliroot_version = " << "\"" << aliroot_version.Data() << "\";" << endl;
945    out << "   alien_datadir   = " << "\"" << alien_datadir.Data() << "\";" << endl;
946    if (!alien_outdir.Length()) alien_outdir = Form("output_%s",train_name.Data());
947    out << "   alien_outdir    = " << "\"" << alien_outdir.Data() << "\";" << endl;
948    out << "   maxMergeFiles   = " << maxMergeFiles << ";" << endl;
949    out << "   mergeExclude    = " << "\"" << mergeExclude.Data() << "\";" << endl;
950    out << "   nRunsPerMaster  = " << nRunsPerMaster << ";" << endl;
951    out << "   nFilesPerJob    = " << nFilesPerJob << ";" << endl;
952 //   for (Int_t i=0; i<10; i++) {
953 //      if (run_numbers[i]) 
954 //         out << "   run_numbers[" << i << "]  = " << run_numbers[i] << ";" << endl;
955 //   }
956 //   out << "   run_range[0]    = " << run_range[0] << ";" << endl;
957 //   out << "   run_range[1]    = " << run_range[1] << ";" << endl;
958    out << "   usePhysicsSelection = " << usePhysicsSelection << ";" << endl;
959    out << "   useTender       = " << useTender << ";" << endl;
960    out << "   useMergeViaJDL  = " << useMergeViaJDL << ";" << endl;
961    out << "   useOverwriteMode  = " << useOverwriteMode << ";" << endl;
962    out << "   useFastReadOption = " << useFastReadOption << ";" << endl;
963    out << "   useDBG          = " << useDBG << ";" << endl;
964    out << "   useMC           = " << useMC << ";" << endl;
965    out << "   useTAGS         = " << useTAGS << ";" << endl;
966    out << "   useKFILTER      = " << useKFILTER << ";" << endl;
967    out << "   useTR           = " << useTR << ";" << endl;
968    out << "   useCORRFW       = " << useCORRFW << ";" << endl;
969    out << "   useAODTAGS      = " << useAODTAGS << ";" << endl;
970    out << "   saveTrain       = " << "kFALSE;" << endl << endl;
971    out << "   // Analysis modules" << endl;
972    out << "   iAODanalysis    = " << iAODanalysis << ";" << endl;
973    out << "   iAODhandler     = " << iAODhandler << ";" << endl;
974    out << "   iPWG2fmd        = " << iPWG2fmd << ";" << endl;   
975    out << "   iPWG2femto      = " << iPWG2femto << ";" << endl;   
976    out << "   iPWG2spectra    = " << iPWG2spectra << ";" << endl;   
977    out << "}" << endl;
978    ::Info("AnalysisTrainNew.C::WriteConfig", "Train configuration wrote to file %s", Form("config_%s.C", train_name.Data()));
979    gSystem->ChangeDirectory(cdir);
980 }   
981
982 //______________________________________________________________________________
983 Bool_t LoadConfig(const char *filename)
984 {
985 // Read train configuration from file
986    if (gSystem->AccessPathName(filename)) {
987       ::Error("AnalysisTrainNew.C::LoadConfig", "Config file name not found");
988       return kFALSE;
989    }   
990    gROOT->ProcessLine(Form(".x %s", filename));
991    ::Info("AnalysisTrainNew.C::LoadConfig", "Train configuration loaded from file %s", filename);
992    return kTRUE;
993 }