]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWGLF/FORWARD/trains/TrainSetup.C
Merge branch 'TPCdev' of https://git.cern.ch/reps/AliRoot into TPCdev
[u/mrichter/AliRoot.git] / PWGLF / FORWARD / trains / TrainSetup.C
1 /**
2  * @defgroup pwglf_forward_trains Trains.
3  * 
4  * Train specifications. 
5  * See also @ref train_setup_doc
6  */
7 /**
8  * @file   TrainSetup.C
9  * @author Christian Holm Christensen <cholm@master.hehi.nbi.dk>
10  * @date   Tue Oct 16 17:56:57 2012
11  * 
12  * @brief  Base classs for train specifications 
13  * 
14  * @ingroup pwglf_forward_trains
15  */
16 #ifndef TRAINSETUP_C
17 #define TRAINSETUP_C
18 #ifndef __CINT__
19 # include "Helper.C"
20 # include "Option.C"
21 # include <TDatime.h>
22 # include <TUrl.h>
23 # include <TString.h>
24 # include <TApplication.h>
25 # include <TStopwatch.h>
26 # include <AliAnalysisManager.h>
27 # include <AliVEventHandler.h>
28 # include <AliPhysicsSelection.h>
29 # include <AliPhysicsSelectionTask.h>
30 # include <AliCentralitySelectionTask.h>
31 # include <AliESDInputHandler.h>
32 # include <AliAODInputHandler.h>
33 # include <AliAODHandler.h>
34 # include <AliMCEventHandler.h>
35 # include <ctime>
36 #else 
37 struct Helper;
38 struct OptionList;
39 class TDatime;
40 class TUrl;
41 class TString;
42 class TStopwatch;
43 class AliVEventHandler;
44 class AliAnalysisManager;
45 class AliInputEventHandler;
46 #endif
47
48 //====================================================================
49 /** 
50  * Generic set-up of an analysis train 
51  *
52  * See also @ref train_setup_doc
53  *
54  * @ingroup pwglf_forward_trains
55  * 
56  */
57 struct TrainSetup
58 {
59   /** 
60    * Constructor 
61    * 
62    * @param name Name of the train
63    */
64   TrainSetup(const TString& name)
65     : fName(name), 
66       fEscapedName(name),
67       fDatimeString(""),
68       fOptions(),
69       fHelper(0),
70       fMonitored("")
71   {
72     fOptions.Add("help", "Show help", false);
73     fOptions.Add("date", "YYYY-MM-DD HH:MM", "Set date", "now");
74     fOptions.Add("bare-ps", "Use bare physics selection w/o task", false);
75     fOptions.Add("verbose", "LEVEL", "Set verbosity level", 0);
76     fOptions.Add("url", "URL", "Job location & input URL", "");
77     fOptions.Add("overwrite", "Allow overwrite", false);
78     fOptions.Add("events", "N", "Number of events to analyse", -1);
79     fOptions.Add("type", "ESD|AOD|USER", "Input data stype", "");
80     fOptions.Add("setup", "Only do the setup", false);
81     fOptions.Add("branches", "Load only requested branches", false);
82     fDatimeString = "";
83     fEscapedName  = EscapeName(fName, fDatimeString);
84   }
85   /** 
86    * Copy constructor 
87    * 
88    * @param o Object to copy from 
89    */
90   TrainSetup(const TrainSetup& o) 
91     : fName(o.fName), 
92       fEscapedName(o.fEscapedName), 
93       fDatimeString(o.fDatimeString),
94       fOptions(o.fOptions), 
95       fHelper(o.fHelper),
96       fMonitored(o.fMonitored)
97   {}
98   /** 
99    * Assignment operator
100    * 
101    * @param o Object to assign from 
102    * 
103    * @return Reference to this object
104    */
105   TrainSetup& operator=(const TrainSetup& o) 
106   {
107     if (&o == this) return *this;
108     fName         = o.fName;
109     fEscapedName  = o.fEscapedName;
110     fDatimeString = o.fDatimeString;
111     fOptions      = o.fOptions;
112     fHelper       = o.fHelper;
113     fMonitored    = o.fMonitored;
114     return *this;
115   }
116   
117   /** 
118    * Destructor
119    */
120   virtual ~TrainSetup() {}
121   /* @} */
122   //__________________________________________________________________
123   /** 
124    * @{ 
125    * @name Execution 
126    */
127   /** 
128    * Initialize 
129    * 
130    * @return true on success 
131    */
132   Bool_t Init()
133   {
134     // --- Create the helper -----------------------------------------
135     TString  url     = fOptions.Get("url");
136     Int_t    verbose = fOptions.AsInt("verbose");
137
138     fHelper = Helper::Create(url.Data(), verbose);
139     if (!fHelper) { 
140       Error("Init", "Failed to make the worker for URL %s", url.Data());
141       return false;
142     }
143
144     // --- Check the type, if possible -------------------------------
145     UShort_t type    = fHelper->InputType();
146     Bool_t   mc      = fHelper->IsMC();
147     if (fOptions.Has("type")) { 
148       const TString& it = fOptions.Get("type");
149       if      (it.EqualTo("ESD",TString::kIgnoreCase)) type = Helper::kESD;
150       else if (it.EqualTo("AOD",TString::kIgnoreCase)) type = Helper::kAOD;
151       else if (it.EqualTo("user",TString::kIgnoreCase)) 
152         type = Helper::kUser;
153     }
154
155     // --- Rewrite the escpaed name ----------------------------------
156     if (fOptions.Has("date")) { 
157       fDatimeString = fOptions.Get("date");
158       fEscapedName  = EscapeName(fName, fDatimeString);
159     }
160     
161     // --- Get current directory and set-up sub-directory ------------
162     TString cwd = gSystem->WorkingDirectory();
163     if (!SetupWorkingDirectory()) return false;
164
165     // --- Do initial helper setup -----------------------------------
166     if (!fHelper->PreSetup()) return false;
167
168     // --- Load ROOT libraries ---------------------------------------
169     if (!fHelper->LoadROOT()) return false;
170     
171     // --- Load AliROOT libraries ------------------------------------
172     if (!fHelper->LoadAliROOT()) return false;
173
174     // --- Create analysis manager -----------------------------------
175     AliAnalysisManager *mgr  = CreateAnalysisManager(fEscapedName);
176
177     // In test mode, collect system information on every event 
178     // if (oper == kTest)  mgr->SetNSysInfo(1); 
179     if (verbose  >  0)      mgr->SetDebugLevel(verbose);
180     mgr->SetAutoBranchLoading(!fOptions.Has("branches"));
181     if (fHelper->Mode() == Helper::kLocal) 
182       mgr->SetUseProgressBar(kTRUE, 100);
183    
184     // --- ESD input handler ------------------------------------------
185     AliVEventHandler*  inputHandler = CreateInputHandler(type);
186     if (inputHandler) mgr->SetInputEventHandler(inputHandler);
187     
188     // --- Monte-Carlo ------------------------------------------------
189     AliVEventHandler*  mcHandler = CreateMCHandler(type,mc);
190     if (mcHandler) mgr->SetMCtruthEventHandler(mcHandler);
191     
192     // --- AOD output handler -----------------------------------------
193     AliVEventHandler*  outputHandler = CreateOutputHandler(type);
194     if (outputHandler) mgr->SetOutputEventHandler(outputHandler);
195
196     // --- Include analysis macro path in search path ----------------
197     gROOT->SetMacroPath(Form("%s:%s:$ALICE_ROOT/ANALYSIS/macros",
198                              cwd.Data(), gROOT->GetMacroPath()));
199
200     // --- Physics selction - only for ESD ---------------------------
201     if (type == Helper::kESD) CreatePhysicsSelection(mc, mgr);
202     
203     // --- Create centrality task ------------------------------------
204     CreateCentralitySelection(mc, mgr);
205
206     // --- Create tasks ----------------------------------------------
207     CreateTasks(mgr);
208
209     // --- Create monitor objects ------------------------------------
210     CreateMonitors();
211
212     // --- Post set-up initialization of helper ----------------------
213     if (!fHelper->PostSetup()) return false;
214
215     // --- Set debug level on defined tasks --------------------------
216     if (verbose > 0) {
217       TIter next(mgr->GetTasks());
218       AliAnalysisTask* sub = 0;
219       while ((sub = static_cast<AliAnalysisTask*>(next()))) { 
220         AliAnalysisTaskSE* se = dynamic_cast<AliAnalysisTaskSE*>(sub);
221         if (!se) continue;
222         se->SetDebugLevel(verbose);
223       }
224     }
225
226     // --- Print this setup ------------------------------------------
227     Print();
228
229     // --- Initialise the train --------------------------------------
230     if (!mgr->InitAnalysis())  {
231       gSystem->ChangeDirectory(cwd.Data());
232       Error("Init","Failed to initialise train");
233       return false;
234     }
235
236     // --- Enable progress bar ---------------------------------------
237     if (fHelper->Mode() != Helper::kGrid) 
238       mgr->SetUseProgressBar(true, 100);
239
240     // --- Save setup to disk ----------------------------------------
241     SaveSetup(true);
242
243     // --- Some information ------------------------------------------
244     mgr->PrintStatus();
245     if (fHelper->Mode() != Helper::kLocal) {
246       TIter next(mgr->GetTasks());
247       AliAnalysisTask* sub = 0;
248       while ((sub = static_cast<AliAnalysisTask*>(next()))) { 
249         sub->Print();
250       }
251     }
252     return true;
253   }
254   /** 
255    * Print timer information
256    * 
257    * @param timer The timer
258    * @param where Where this was called from 
259    */
260   void PrintTimer(TStopwatch& timer, const char* where)
261   {
262     timer.Stop();
263     Double_t t = timer.RealTime();
264     Int_t    h = Int_t(t / 3600); t -= h * 3600;
265     Int_t    m = Int_t(t /   60); t -= m *   60;
266     if (t < 0) t = 0;
267     Info(where, "took %4d:%02d:%06.3f", h, m, t);
268   }
269   /** 
270    * Run this train 
271    * 
272    * @return true on success 
273    */    
274   Bool_t Run()
275   {
276     TString cwd = gSystem->WorkingDirectory();
277     Bool_t status = false;
278     TStopwatch timer;
279     timer.Start();
280     try {
281       if (!Init()) throw TString("Failed to intialize the train");
282       PrintTimer(timer, "Initialization");
283       timer.Continue();
284       
285       // Check if we're asked to only do the setup 
286       if (fOptions.Has("setup")) {
287         status = true;
288         throw TString("Only did setup, no running");
289       }
290
291       // if (r) SaveSetup(*r, nEvents, asShell);
292       
293       Long64_t nEvents = fOptions.AsLong("events", -1);
294       Long64_t ret     = fHelper->Run(nEvents);
295       PrintTimer(timer, "Processing");
296       timer.Continue();
297       
298       // Make sure we go back 
299       gSystem->ChangeDirectory(cwd.Data());
300       
301       // Return. 
302       if (ret < 0) throw TString("Analysis failed");
303
304       status = true;
305     }
306     catch (TString& e) {
307       if (status) Warning("Run", "%s", e.Data());
308       else        Error("Run", "%s", e.Data());
309     }
310     if (fOptions.Has("date")) {
311       TString tmp     = "";
312       TString escaped = EscapeName(fName, tmp);
313       gSystem->Exec(Form("rm -f last_%s", escaped.Data()));
314       gSystem->Exec(Form("ln -sf %s last_%s", 
315                          fEscapedName.Data(), escaped.Data()));
316     }
317     PrintTimer(timer, "Finish");
318     timer.Continue();
319     return status;
320   }
321   /** 
322    * Get the options 
323    * 
324    * 
325    * @return Reference ot the options 
326    */
327   OptionList& Options() { return fOptions; }
328   /** 
329    * Print information to standard output 
330    * 
331    */
332   void Print(Option_t* ="") const
333   {
334     std::cout << "Train: " << fName << " (" << fEscapedName << ")" 
335               << std::endl;
336     fOptions.Show(std::cout);
337     if (fHelper) fHelper->Print();
338   }
339   /** 
340    * Show the help 
341    * 
342    * @param o      Output stream
343    * @param asProg If true, output as program options 
344    * 
345    * @return 
346    */
347   Bool_t Help(std::ostream& o=std::cout, bool asProg=false)
348   {
349     if (!fOptions.Has("help")) return true;
350
351     if (!asProg) 
352       o << "Usage: RunTrain(NAME, CLASS, OPTIONS)";
353     
354     o << "\n\nTrain Options:\n";
355     fOptions.Help(o, asProg ? "  --" : "  ");
356     o << "\n";
357
358     if (!fHelper && fOptions.Has("url")) {
359       TString url = fOptions.Get("url");
360       fHelper = Helper::Create(url.Data());
361     }
362     if (fHelper) { 
363       o << fHelper->Desc() << " URL form:\n\n"
364         << "    " << fHelper->UrlHelp() << "\n\n"
365         << "Options:\n";
366       fHelper->Options().Help(o, "    ");
367       o << "\n";
368     }
369     else { 
370       o << "Possible URL forms:\n\n";
371       Helper::ShowUrlHelp("LocalHelper");
372       Helper::ShowUrlHelp("ProofHelper");
373       Helper::ShowUrlHelp("LiteHelper");
374       Helper::ShowUrlHelp("AAFHelper");
375       Helper::ShowUrlHelp("AAFPluginHelper");
376       Helper::ShowUrlHelp("GridHelper");
377       o << "\n";
378     }
379     return false;
380   }
381   /** 
382    * Run train.  This will AcLic compile the setup script, create
383    * an object of that type with the given name, and then pass the 
384    * options to it.  Then, it will run the setup.
385    * 
386    * @param name   Train name 
387    * @param cls    Class name 
388    * @param opts   Comma seperated list of options
389    * @param asProg Run as program 
390    * @param spawn  Spawn ROOT shell after execution 
391    * 
392    * @return true on success
393    */
394   static Bool_t Main(const TString& name, const TString& cls, 
395                      const TCollection* opts, 
396                      Bool_t asProg=true,
397                      Bool_t spawn=false)
398   {
399     Bool_t ret = false;
400     try {
401       if (cls.IsNull()) 
402         throw TString("No class name specified");
403       if (name.IsNull()) 
404         throw TString("No train name specified");
405
406       gROOT->ProcessLine("gSystem->RedirectOutput(\"build.log\",\"w\");");
407       Int_t error = 0;
408       Int_t r1 = gROOT->LoadMacro(Form("%s.C+g", cls.Data()), &error);
409       gROOT->ProcessLine("gSystem->RedirectOutput(0);");
410       if (r1 < 0 || error) 
411         throw TString::Format("Failed to load setup %s: %d - see build.log", 
412                               cls.Data(), error);
413
414       // Make our object using the interpreter 
415       TString create = TString::Format("new %s(\"%s\")", 
416                                        cls.Data(), name.Data());
417       gROOT->ProcessLine("gSystem->RedirectOutput(\"build.log\",\"a\");");
418       Long_t retP = gROOT->ProcessLine(create, &error);
419       gROOT->ProcessLine("gSystem->RedirectOutput(0);");
420       if (!retP || error) 
421         throw TString::Format("Failed to make object of class %s "
422                               "(see build.log): 0x%08lx/%d\n\t%s", 
423                               cls.Data(), retP, error, create.Data());
424
425       TrainSetup* train = reinterpret_cast<TrainSetup*>(retP);
426     
427       // Now parse the options 
428       if (!train->Options().Parse(opts)) 
429         throw TString("Failed to parse options");
430
431       // Info("", "URL=%s", train->Options().Get("url").Data());
432
433       // Check if we got a help request
434       if (train->Options().Has("help")) { 
435         train->Help(std::cout, asProg);
436         ret = true;
437         throw TString("");
438       }
439
440       // return train->Init();
441       ret = train->Run();
442     }
443     catch (TString& e) { 
444       if (!e.IsNull()) Error("Main", "%s", e.Data());
445     }
446     // Info("Main", "End of main loop (app=%p, asProg=%s, spawn=%s)",
447     //   gApplication, asProg ? "true" : "false", spawn ? "true" : "false");
448     if (gApplication && asProg) {
449       if (!spawn) {
450         gSystem->Sleep(3);
451         gApplication->Terminate(ret ? 0 : 1);
452       }
453     }
454     return ret;
455   }
456 protected:
457   //__________________________________________________________________
458   /** 
459    * @{ 
460    * @name Overloadable behaviour 
461    */
462   //------------------------------------------------------------------
463   /** 
464    * Create the analysis manager 
465    * 
466    * @param name Name of the analysis 
467    * 
468    * @return Created analysis manager 
469    */
470   virtual AliAnalysisManager* CreateAnalysisManager(const char* name)
471   {
472     return new AliAnalysisManager(name,"Analysis Train");
473   }
474   //------------------------------------------------------------------
475   /** 
476    * Create input handler 
477    * 
478    * @param type 
479    * 
480    * @return 
481    */
482   virtual AliVEventHandler* CreateInputHandler(UShort_t type)
483   {
484     switch (type) {
485     case Helper::kESD:  return new AliESDInputHandler(); 
486     case Helper::kAOD:  return new AliAODInputHandler(); 
487     case Helper::kUser: return 0;
488     }
489     return 0;
490   }
491   //------------------------------------------------------------------
492   /** 
493    * Create MC input handler 
494    * 
495    * @param mc    Assume monte-carlo input 
496    * 
497    * @return 
498    */
499   virtual AliVEventHandler* CreateMCHandler(UShort_t /*type*/, bool mc)
500   {
501     if (!mc) return 0;
502     AliMCEventHandler* mcHandler = new AliMCEventHandler();
503     mcHandler->SetReadTR(true); 
504     return mcHandler;
505   }
506   //------------------------------------------------------------------
507   /** 
508    * Create output event handler 
509    * 
510    * @param type 
511    * 
512    * @return 
513    */
514   virtual AliVEventHandler* CreateOutputHandler(UShort_t type)
515   {
516     AliAODHandler* ret = new AliAODHandler();
517     switch (type) { 
518     case Helper::kESD: 
519       ret->SetOutputFileName("AliAOD.root");
520       break;
521     case Helper::kAOD: 
522       ret->SetOutputFileName("AliAOD.pass2.root");
523       break;
524     case Helper::kUser: 
525       break;
526     }
527     
528     return ret;
529   }
530   //------------------------------------------------------------------
531   /** 
532    * Create physics selection, and add to manager
533    * 
534    * @param mc Whether this is for MC 
535    * @param mgr Manager
536    */
537   virtual void CreatePhysicsSelection(Bool_t mc, AliAnalysisManager* mgr)
538   {
539     if (fOptions.Has("bare-ps")) {
540       AliInputEventHandler* input = 
541         dynamic_cast<AliInputEventHandler*> (mgr->GetInputEventHandler());
542       if (!input) return;
543
544       AliPhysicsSelection* ps = new AliPhysicsSelection();
545       if (mc) ps->SetAnalyzeMC();
546
547       input->SetEventSelection(ps);
548
549       return;
550     }
551     gROOT->Macro(Form("AddTaskPhysicsSelection.C(%d)", mc));
552     mgr->RegisterExtraFile("event_stat.root");
553     mgr->AddStatisticsTask(AliVEvent::kAny);
554   }
555   //------------------------------------------------------------------
556   /** 
557    * Create centrality selection, and add to manager
558    * 
559    * @param mc Whether this is for MC 
560    * @param mgr Manager
561    */
562   virtual void CreateCentralitySelection(Bool_t mc, AliAnalysisManager* mgr)
563   {
564     gROOT->Macro("AddTaskCentrality.C(true)");
565     const char* name = "CentralitySelection";
566     AliCentralitySelectionTask* ctask = 
567       dynamic_cast<AliCentralitySelectionTask*>(mgr->GetTask(name));
568     if (!ctask) return;
569     if (mc) ctask->SetMCInput();
570   }
571   //------------------------------------------------------------------
572   /** 
573    * Create analysis tasks.  Must be overloaded by sub-class
574    * 
575    * @param mgr  Manager
576    */
577   virtual void CreateTasks(AliAnalysisManager* mgr)=0;
578   /** 
579    * Add a task using a script and possibly some arguments 
580    * 
581    * @param macro Script to execute 
582    * @param args  Optional arguments to the script 
583    * 
584    * @return Created task or null
585    */
586   virtual AliAnalysisTask* AddTask(const TString& macro, 
587                                    const TString& args)
588   {
589     TString p = gSystem->Which(gROOT->GetMacroPath(), macro.Data());
590     if (p.IsNull()) { 
591       Error("AddTask", "Macro %s not found", macro.Data());
592       return 0;
593     }
594     TString cmd(p);
595     if (!args.IsNull()) 
596       cmd.Append(TString::Format("(%s)", args.Data()));
597     
598     Int_t err;
599     Long_t ret = gROOT->Macro(cmd.Data(), &err, false);
600     if (!ret) { 
601       Error("AddTask", "Failed to execute %s (%ld)", cmd.Data(), ret);
602       return 0;
603     }
604     return reinterpret_cast<AliAnalysisTask*>(ret);
605   }
606   /** 
607    * Add a task to the train with no arguments passed to the script 
608    * 
609    * @param macro The <b>AddTask</b> macro. 
610    * 
611    * @return The added task, if any
612    */
613   virtual AliAnalysisTask* AddTask(const TString& macro)
614   {
615     TString args;
616     return AddTask(macro, args);
617   }
618   /** 
619    * Add a single event analysis task to the train, passing the
620    * specified arguments to the macro.
621    * 
622    * @param macro The <b>AddTask</b> macro 
623    * @param args  Arguments to pass the macro 
624    * 
625    * @return The added task, if any 
626    */
627   virtual AliAnalysisTaskSE* AddSETask(const TString& macro, 
628                                        const TString& args)
629   {
630     return dynamic_cast<AliAnalysisTaskSE*>(AddTask(macro, args));
631   }
632   /** 
633    * Add a single event task to the train with no arguments passed to
634    * the script
635    * 
636    * @param macro The <b>AddTask</b> macro. 
637    * 
638    * @return The added task, if any
639    */
640   virtual AliAnalysisTaskSE* AddSETask(const TString& macro)
641   {
642     TString args;
643     return AddSETask(macro, args);
644   }
645   /** 
646    * Check if we have an MC handler attached 
647    * 
648    * @return True if MC handler is found in a valid manager.  False if
649    * manager is not defined, or has no MC handler.
650    */
651   virtual Bool_t HasMCHandler() const 
652   {
653     AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
654     if (!mgr) return false;
655     return mgr->GetMCtruthEventHandler() != 0;
656   }
657   /** 
658    * Set the name of the train - should be name of the class.  Must be
659    * overloaded.
660    * 
661    * @return Class name as a constant C string 
662    */
663   virtual const Char_t* ClassName() const = 0;
664   /* @} */
665   //__________________________________________________________________
666   virtual void AddMonitor(const TString& name)
667   {
668     if (!fMonitored.IsNull()) fMonitored.Append(":");
669     fMonitored.Append(name);
670   }
671   virtual void CreateMonitors() 
672   {
673     if (fMonitored.IsNull()) return;
674     if (fHelper->Mode() != Helper::kProof) return;
675
676     TObjArray* tokens = fMonitored.Tokenize(":");
677     TObject*   token  = 0;
678     TIter      next(tokens);
679     while ((token = next())) {
680       gROOT->ProcessLine(Form("gProof->AddFeedback(\"%s\");", 
681                               token->GetName()));
682       
683     }
684     tokens->Delete();
685   }
686   //__________________________________________________________________
687   /** 
688    * @{ 
689    * @name Utility functions 
690    */
691   /** 
692    * Escape bad elements of the name 
693    * 
694    * @param name      Name to escape 
695    * @param datimeStr Date and Time string 
696    * 
697    * @return escaped name 
698    */  
699   static TString EscapeName(const char* name, TString& datimeStr)
700   {
701     TString escaped = name;
702     char  c[] = { ' ', '/', '@', 0 };
703     char* p   = c;
704     while (*p) { 
705       char tmp[] = { *p, '\0' };
706       escaped.ReplaceAll(tmp, "_");
707       p++;
708     }
709     if (!datimeStr.IsNull() && 
710         !datimeStr.EqualTo("none", TString::kIgnoreCase)) {
711       TDatime datime;
712       if (datimeStr.EqualTo("now", TString::kIgnoreCase)) 
713         datime.Set();
714       else {
715         // Try various formats 
716         struct tm t;
717         const char* formats[] = { "%Ec", // Locale 
718                                   "%c", // Locale 
719                                   "%Ex EX", // Locale 
720                                   "%x %X", // Locale 
721                                   "%Y%m%d_%H%M", // YYYYMMDD_HHMM
722                                   "%F %R", // ISO standard, no seconds 
723                                   0 };
724         const char** f = formats;
725         Bool_t found = false;
726         while (*f && !found) { 
727           // Reset needed fields 
728           t.tm_year  = 0;
729           t.tm_mon   = 0;
730           t.tm_mday  = 0;
731           t.tm_hour  = 0;
732           t.tm_min   = 0;
733           // Stop processing on first match 
734           if (strptime(datimeStr.Data(), *f, &t) != 0) found = true;
735           f++;
736         }
737         if (found) {
738           t.tm_mon += 1; // Return 0-based month
739           datime.Set(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, 0); 
740         }
741       }
742       if (datime.GetYear() <= 1995 ||
743           datime.GetMonth() == 0 || 
744           datime.GetDay() == 0) return escaped;
745       datimeStr = Form("%04d%02d%02d_%02d%02d", 
746                        datime.GetYear(), 
747                        datime.GetMonth(), 
748                        datime.GetDay(), 
749                        datime.GetHour(), 
750                        datime.GetMinute());
751       escaped.Append(Form("_%s", datimeStr.Data()));
752     }
753     return escaped;
754   }    
755   /** 
756    * Make our working directory if so requested 
757    * 
758    * @return true on success
759    */
760   Bool_t SetupWorkingDirectory()
761   {
762     // Get the name of the target directory 
763     TString& nam = fEscapedName;
764
765     // Check if the directory exists already 
766     Bool_t exists = gSystem->AccessPathName(nam.Data()) == 0;
767     if (fHelper->Operation() == Helper::kTerminate && !exists) {
768       Error("SetupWorkingDirectory", "File/directory %s does not exists", 
769             nam.Data());
770       return false;
771     }
772
773     Bool_t overwrite = fOptions.Has("overwrite");
774     // If we're not allowed to overwrite, then complain
775     if (!overwrite && exists) {
776       Error("SetupWorkingDirectory", "File/directory %s already exists", 
777             nam.Data());
778       return false;
779     }
780
781     // Make the target directory if it doesn't exists 
782     if (!exists) {
783       if (gSystem->MakeDirectory(nam.Data())) {
784         Error("SetupWorkingDirectory", "Failed to make directory '%s'", 
785               nam.Data());
786         return false;
787       }
788     }
789       
790     // Change directory to target directory 
791     if (!gSystem->ChangeDirectory(nam.Data())) { 
792       Error("SetupWorkingDirectory", "Failed to change directory to %s", 
793             nam.Data());
794       return false;
795     }
796     // Info("SetupWorkingDirectory", "Made subdirectory %s, and cd'ed there", 
797     //      nam.Data());
798     return true;
799   }
800   /** 
801    * Save the setup as a ROOT script and possibly also a shell script
802    * 
803    * @param asShellScript If true, also save as shell script
804    */
805   virtual void SaveSetup(Bool_t asShellScript)
806   {
807     OptionList tmp(fOptions);
808     const OptionList* uopts = (fHelper ? &fHelper->Options() : 0);
809     if (tmp.Find("overwrite")) tmp.Set("overwrite");
810     if (tmp.Find("date") && fEscapedName.Length() > fName.Length()+1) {
811       Int_t n = fName.Length()+1;
812       tmp.Set("date", fEscapedName(n, fEscapedName.Length()-n));
813     }
814     if (asShellScript) 
815       SaveSetupShell("rerun", ClassName(), fName, tmp, uopts);
816     SaveSetupROOT("ReRun", ClassName(), fName, tmp, uopts);
817     if (fHelper) fHelper->AuxSave(fEscapedName, asShellScript);
818     SavePostShellScript();
819   }
820   /** 
821    * Save a setup as a shell script 
822    * 
823    * @param out   Output name of shell script 
824    * @param cls   Class of the train 
825    * @param name  Name of the train
826    * @param opts  Option list
827    * @param uopts Url options 
828    */
829   static void SaveSetupShell(const TString& out, const TString& cls,
830                              const TString& name, const OptionList& opts,
831                              const OptionList* uopts)
832   {
833     std::ofstream o(Form("%s.sh", out.Data()));
834     o << "#!/bin/bash\n\n"
835       << "class=\"" << cls << "\"\n"
836       << "name=\"" << name << "\"\n\n"
837       << "# Available options\n"
838       << "# \n";
839     opts.Help(o, "#    --");
840     if (uopts) {
841       o << "#\n"
842         << "# Available URI options\n"
843         << "# \n";
844       uopts->Help(o, "#      ");
845     }
846     o << "#\n"
847       << "opts=(--class=$class \\\n"
848       << "  --name=$name";
849     opts.Store(o, " \\\n  --", "", true);
850     o << ")\n\n"
851       << "echo \"Running runTrain ${opts[@]} $@\"\n"
852       << "runTrain \"${opts[@]}\" $@\n\n"
853       << "# EOF" << std::endl;
854     o.close();
855     gSystem->Exec(Form("chmod a+x %s.sh", out.Data()));
856   }
857   /** 
858    * Save a setup as a ROOT script 
859    * 
860    * @param out   Output name of shell script 
861    * @param cls   Class of the train 
862    * @param name  Name of the train
863    * @param opts  Option list
864    * @param uopts Url options 
865    */
866   static void SaveSetupROOT(const TString& out, const TString& cls,
867                             const TString& name, const OptionList& opts,
868                             const OptionList* uopts)
869   {
870     OptionList tmp(opts);
871     tmp.Remove("url");
872
873     std::ofstream o(Form("%s.C", out.Data()));
874     o << "// Available options:\n"
875       << "// \n";
876     tmp.Help(o, "//     ");
877     if (uopts) {
878       o << "// \n"
879         << "// Available URI options\n";
880       uopts->Help(o, "//      ");
881     }
882     o << "//\n"
883       << "Bool_t " << out << "()\n" 
884       << "{\n"
885       << "  TString name(\"" << name << "\");\n"
886       << "  TString cls(\"" << cls << "\");\n"
887       << "  TUrl    uri(\"" << opts.Get("url") << "\");\n"
888       << "  \n"
889       << "  TString opts(";
890     tmp.Store(o, "\"", ",\"\n               ", false);
891     o << ");\n\n"
892       << "  TString path(";
893     TString     path(gROOT->GetMacroPath());
894     TObjArray*  elements = path.Tokenize(":");
895     TObjString* element = 0;
896     TIter       next(elements);
897     while ((element = static_cast<TObjString*>(next()))) {
898       if (element->String().IsNull()) continue;
899       o << "\n               \"" << element->GetName() << ":\"";
900     }
901     elements->Delete();
902     o << ");\n"
903       << "  path.Append(\"$ALICE_ROOT/PWGLF/FORWARD/trains\");\n"
904       << "  gROOT->SetMacroPath(path);\n\n"
905       << "  gROOT->LoadMacro(\"RunTrain.C\");\n\n"
906       << "  return RunTrain(name, cls, uri, opts);\n"
907       << "}\n" 
908       << "//\n"
909       << "// EOF\n" 
910       << "//" << std::endl;
911     o.close();
912   }    
913   /** 
914    * Write shell code to do post processing after terminate.  This
915    * code should deal with a single run (or run range).  The following
916    * shell variables are available to the code:
917    *
918    * - @c $prefix  Relative path to job directory or empty 
919    * - @c $dest    Destination for output to be stored
920    * 
921    * Note, the code is injected into a shell function, and should
922    * therefor not define new functions or the like.
923    * 
924    * @param o The output stream.  
925    */
926   virtual void PostShellCode(std::ostream& o)
927   {
928     o << "  echo \"Nothing to do for " << ClassName() 
929       << " train\"" << std::endl;
930   }
931   /** 
932    * Save a script to do post processing after terminate on each run
933    * or run-range. 
934    * 
935    * The shell script will execute the train defined code (in
936    * PostShellCode) for each run or run-range.  The train defined code
937    * and call drawing and summarizing macros or the like.
938    *
939    * In case of Grid analysis, this script will download and extract
940    * the appropriate ZIP files to separate directories, and then
941    * change directory to these directories and execute the train
942    * defined shell code there.  In this case, the script defines the
943    * shell variable @c $prefix as the relative path to the job
944    * directory.
945    * 
946    */
947   void SavePostShellScript()
948   {
949     std::ofstream f("post.sh");
950     if (!f) { 
951       Error("SavePostAll", "Failed to open post.sh script");
952       return;
953     }
954     f << "#!/bin/bash\n"
955       << "# Generated by " << ClassName() << "\n"
956       << "set -e\n"
957       << "\n"
958       << "dest=$1\n"
959       << "prefix=\n"
960       << "\n"
961       << "doall() {"
962       << std::endl;
963     PostShellCode(f);
964     f << "}\n"
965       << "\n"
966       << "if test ! -f Download.C ;then\n"
967       << "  doall\n"
968       << "  exit\n"
969       << "fi\n"
970       << "\n"
971       << "if test ! -f .download ; then\n"
972       << "  aliroot -l -b -q Download.C\\(1\\)\n"
973       << "  touch .download\n"
974       << "fi\n"
975       << "prefix=../\n"
976       << "\n"
977       << "for i in root_archive_*.zip ; do\n"
978       << "  d=`basename $i .zip` \n"
979       << "  if test ! -d $d ; then\n"
980       << "    echo \"Directory $d missing\"\n"
981       << "    continue\n"
982       << "  fi\n"
983       << "  \n"
984       << "  (cd $d && doall)\n"
985       << "done\n"
986       << "# EOF"
987       << std::endl;
988     f.close();
989     gSystem->Exec("chmod a+x post.sh");
990   }
991     
992   /* @} */
993   TString      fName;
994   TString      fEscapedName;
995   TString      fDatimeString;
996   OptionList   fOptions;
997   Helper*      fHelper;
998   TString      fMonitored;
999 };
1000 #endif