source: JEM-EUSO/esaf_cc_at_lal/packages/simulation/framework/src/SimuApplication.cc @ 114

Last change on this file since 114 was 114, checked in by moretto, 11 years ago

actual version of ESAF at CCin2p3

File size: 24.0 KB
Line 
1// implementation of SimuApplication
2// $Id: SimuApplication.cc 2956 2011-06-28 18:54:32Z mabl $
3// M. Pallavicini - created 28-12-2001
4//
5
6#include <iostream>
7
8#include "SimuApplication.hh"
9#include "EsafMsgDispatcher.hh"
10#include "Config.hh"
11
12#include "Detector.hh"
13#include "DetectorGeometry.hh"
14#include "EEventGeoFiller.hh"
15#include "LightToEuso.hh"
16#include "EusoElectronics.hh"
17#include "ElectronicsFactory.hh"
18#include "LightFactory.hh"
19#include "Telemetry.hh"
20#include "PhotonsOnPupil.hh"
21#include "EsafRandom.hh"
22#include "EsafSys.hh"
23
24#include "EEvent.hh"
25#include "EDetector.hh"
26#include "EHeader.hh"
27#include "EAtmosphere.hh"
28#include "EShower.hh"
29
30#include <TBenchmark.h>
31#include <TTree.h>
32#include <TSysEvtHandler.h>
33#include <TSystem.h>
34#include <TTimeStamp.h>
35
36#include <TObjectTable.h>
37
38ClassImp (SimuApplication)
39     using TMath::Max;
40
41// static pointer to SimuApplication
42     SimuApplication *gSimuApplication = NULL;
43
44//----- Interrupt signal handler -----------------------------------------------
45//______________________________________________________________________________
46     class SimuInterruptHandler:public TSignalHandler, EsafMsgSource
47     {
48     public:
49       SimuInterruptHandler ():TSignalHandler (kSigInterrupt, kFALSE)
50       {
51       }
52       Bool_t Notify ();
53     };
54
55//______________________________________________________________________________
56Bool_t
57SimuInterruptHandler::Notify ()
58{
59  // TRint interrupt handler.
60
61  Msg (EsafMsg::Panic) << "Esaf execution aborted" << MsgDispatch;
62
63  return kTRUE;;
64}
65
66//______________________________________________________________________________
67SimuApplication::SimuApplication (Int_t argc, char **argv):
68TRint ("Euso Detector Simulation", &argc, argv, 0, 0, kTRUE),
69fLightToEuso (0), fDetector (0), fLock (0), fEvCount (0), fEvMax (1),
70fRunName ("Simu"), fManager (0)
71{
72  //
73  // Constructor.
74  // Parse inline parameters, build the detector and electronics
75  // reload random seed if required
76  //
77
78  // Install interrupt handler
79  SimuInterruptHandler *ih = new SimuInterruptHandler;
80  ih->Add ();
81  SetSignalHandler (ih);
82
83  fWriteTelemetry = kFALSE;
84  fWriteRoot = kTRUE;
85
86
87  //
88  // re-build command line and look for local
89  //
90  string cmd;
91  Bool_t isLocal (kFALSE);      //FIXME: this should be handled by a CmdLineParser object.
92  for (Int_t i (0); i < argc; i++)
93    {
94      string str = argv[i];
95      cmd += str + " ";
96      if (str == "--local")
97        isLocal = kTRUE;
98    }
99
100
101
102
103  //
104  // FIXME: wrong way to decide when the local/global path to esaf has to be used.
105  // Is it possible? Or must be done via cmdline?
106  //
107  const char esafsys[] = "ESAFSYS";
108  string esafCfgPath;
109
110  TString esafPath;
111  if (gSystem->Getenv (esafsys) && !isLocal)
112    esafPath = gSystem->Getenv (esafsys);
113  else
114    esafPath = gSystem->WorkingDirectory ();
115
116  gEsafSys = new EsafSys (esafPath);
117
118
119  esafCfgPath = gEsafSys->GetCfgPath ();
120
121  ConfigFileParser::ChangeConfigDir (esafCfgPath);
122
123  // initialize message dispatcher
124  EsafMsgDispatcher::Get ()->LoadConfig ();
125
126  // load standard configs
127  Config::Get ()->LoadStandardConfigs ();
128
129
130
131  Msg (EsafMsg::Debug) << "Simu command line:" << MsgDispatch;
132  Msg (EsafMsg::Debug) << cmd << MsgDispatch;
133
134  ParseCmdLine (argc, argv);
135
136  Init ();
137
138  // force all elements of the chain to be built (if required by Config)
139  SetChanged (kESAFLight);
140  SetChanged (kESAFDetector);
141
142
143  Int_t len = 80;
144  TString head ('_', len);
145  try
146  {
147    Build ();
148  }
149  catch (exception & e)
150  {
151    Msg (EsafMsg::Error) << head << MsgDispatch;
152    Msg (EsafMsg::Error) << MsgDispatch;
153    Msg (EsafMsg::
154         Error) << "An error has occurred during Build()" << MsgDispatch;
155    Msg (EsafMsg::Error) << "Message:" << MsgDispatch;
156    Msg (EsafMsg::Error) << MsgDispatch;
157    Msg (EsafMsg::Error) << "  " << e.what () << MsgDispatch;
158    Msg (EsafMsg::Error) << MsgDispatch;
159    Msg (EsafMsg::Error) << "ESAF Stopped" << MsgDispatch;
160    Msg (EsafMsg::Error) << head << MsgDispatch;
161    Msg (EsafMsg::Error) << MsgDispatch;
162    exit (999);
163  }
164  catch (EsafMsg & msg)
165  {
166    Msg (EsafMsg::Error) << head << MsgDispatch;
167    Msg (EsafMsg::Error) << MsgDispatch;
168    Msg (EsafMsg::Error) << "An error in " << msg.
169      GetSender () << " has occurred during Build()" << MsgDispatch;
170    Msg (EsafMsg::Error) << "Message:" << MsgDispatch;
171    Msg (EsafMsg::Error) << MsgDispatch;
172    Msg (EsafMsg::Error) << "  " << msg.GetText () << MsgDispatch;
173    Msg (EsafMsg::Error) << MsgDispatch;
174    Msg (EsafMsg::Error) << "ESAF Stopped" << MsgDispatch;
175    Msg (EsafMsg::Error) << head << MsgDispatch;
176    Msg (EsafMsg::Error) << MsgDispatch;
177    exit (999);
178  }
179
180
181  gSimuApplication = this;
182}
183
184//______________________________________________________________________________
185SimuApplication::~SimuApplication ()
186{
187  // destructor
188  // close output file if open
189  // save random engine status
190
191  EndJob ();
192  if (fManager)
193    {
194      delete fManager;
195      Msg (EsafMsg::Debug) << "Manager deleted" << MsgDispatch;
196    }
197}
198
199//______________________________________________________________________________
200void
201SimuApplication::ParseCmdLine (Int_t argc, char **argv)
202{
203  //
204  // Parse the commandline and set the corresponding variables
205  //
206
207  for (Int_t i = 1; i < argc; i++)
208    {                           //FIXME parser is too stupid....
209      if (strlen (argv[i]) >= 2 && (argv[i][0] == '-') && (argv[i][0] != '-'))
210        {
211          MsgForm (EsafMsg::Warning, "Simu usage:");
212          MsgForm (EsafMsg::Warning, "");
213          MsgForm (EsafMsg::Warning,
214                   "     Simu [-b --events=<n> --seed=<n> --ofile=<fname> \
215                    --no-telemetry --no-root --no-files--stdcfg=<cfg> --usrcfg=<cfg> \
216                    --ClassName.VarName=val] ");
217
218        }
219      else if (strncmp (argv[i], "--local", 7) == 0)
220        {
221          Msg (EsafMsg::
222               Info) << "ESAF-Simu running from the Current Working Directory"
223            << MsgDispatch;
224        }
225      else if (strncmp (argv[i], "--events=", 9) == 0)
226        {
227          // Number of events
228          sscanf (argv[i] + 9, "%d", &fEvMax);
229
230        }
231      else if (strncmp (argv[i], "--seed=", 7) == 0)
232        {
233          // Set random seed
234          string key = "EsafRandom";
235          string value = key + ".fSeed=" + (argv[i] + 7);
236          fUsrKeys.push_back (key);
237          fUsrValues.push_back (value);
238
239        }
240      else if (strncmp (argv[i], "--ofile=", 8) == 0)
241        {
242          // Superseed output file name
243
244          string key = "Run";
245          string value = key + ".fFilesPrefix=" + (argv[i] + 8);
246          fUsrKeys.push_back (key);
247          fUsrValues.push_back (value);
248
249          Msg (EsafMsg::Info) << "Output file name set to: " << (argv[i] +
250                                                                 8) <<
251            MsgDispatch;
252
253        }
254      else if (strncmp (argv[i], "--odir=", 7) == 0)
255        {
256          // Set Custom output directory
257
258          string key = "Run";
259          string value = key + ".fOutputPath=" + (argv[i] + 7);
260          fUsrKeys.push_back (key);
261          fUsrValues.push_back (value);
262
263          Msg (EsafMsg::Info) << "Output directory set to: " << (argv[i] +
264                                                                 7) <<
265            MsgDispatch;
266
267
268        }
269      else if (strncmp (argv[i], "--runname=", 10) == 0)
270        {
271          // Add run name to the truth
272          fRunName = argv[i] + 10;
273
274        }
275      else if (strncmp (argv[i], "--no-telemetry", 14) == 0)
276        {
277          // Don't write telemery
278          fWriteTelemetry = kFALSE;
279
280        }
281      else if (strncmp (argv[i], "--no-root", 8) == 0)
282        {
283          // Don't save rootfile
284          fWriteRoot = kFALSE;
285
286        }
287      else if (strncmp (argv[i], "--no-files", 8) == 0)
288        {
289          // Don't write root AND telemetry
290          fWriteTelemetry = kFALSE;
291          fWriteRoot = kFALSE;
292
293        }
294      else if (strncmp (argv[i], "--stdcfg", 8) == 0)
295        {
296          //Standard Configuration
297          string s = argv[i] + 8;
298          size_t pos = s.find ('=');
299          if (pos != string::npos)
300            {
301              string stdcfg = s.substr (pos + 1);
302              if (!Config::Get ()->UseConfig (stdcfg))
303                FatalError (stdcfg + " standard config not defined");
304            }
305          else
306            FatalError ("Invalid parameter " + string (argv[i]));
307
308        }
309      else if (strncmp (argv[i], "--usrcfg", 8) == 0)
310        {
311          // User Configuration
312          string s = argv[i] + 7;
313          size_t pos = s.find ('=');
314          if (pos != string::npos)
315            fUsrCfgs.push_back (s.substr (pos + 1));
316          else
317            FatalError ("Invalid parameter " + string (argv[i]));
318
319        }
320      else if (strncmp (argv[i], "--", 2) == 0)
321        {
322          // Ok, it seems to be user-defined var
323          string s = argv[i] + 2;
324
325          size_t pos = s.find ('.');
326          if (pos == string::npos)
327            FatalError ("Invalid parameter " + string (argv[i]));
328          else
329            // user defined variable syntax
330            // ClassName::VarName
331            fUsrKeys.push_back (s.substr (0, pos));
332          fUsrValues.push_back (s);
333
334        }
335    }
336
337  // load user definition file first
338  vector < string >::const_iterator itCfg;
339  for (itCfg = fUsrCfgs.begin (); itCfg != fUsrCfgs.end (); itCfg++)
340    Config::Get ()->LoadUserConfig (itCfg->c_str ());
341
342  // the apply custom parameters
343  for (size_t i (0); i < fUsrKeys.size (); i++)
344    {
345      Config::Get ()->AddUserDefinition (fUsrKeys[i], fUsrValues[i]);
346    }
347}
348
349//______________________________________________________________________________
350void
351SimuApplication::Init ()
352{
353  //
354  // Initialize Config and the message system
355  //
356
357  // initialize the file names.
358  fOutPrefix =
359    Config::Get ()->GetCF ("General",
360                           "Run")->GetStr ("Run.fFilesPrefix").c_str ();
361
362  TString outdir =
363    Config::Get ()->GetCF ("General",
364                           "Run")->GetStr ("Run.fOutputPath").c_str ();
365
366  gEsafSys->SetOutPath (outdir);
367
368  fFileNames[kLog] =
369    gEsafSys->AbsolutePath (gEsafSys->GetOutPath () + fOutPrefix + ".log");
370  fFileNames[kDump] =
371    gEsafSys->AbsolutePath (gEsafSys->GetOutPath () + fOutPrefix +
372                            ".ConfigDump.cfg");
373  fFileNames[kRoot] =
374    gEsafSys->AbsolutePath (gEsafSys->GetOutPath () + fOutPrefix + ".root");
375  fFileNames[kTelemetry] =
376    gEsafSys->AbsolutePath (gEsafSys->GetOutPath () + fOutPrefix +
377                            ".Telemetry.dat.gz");
378
379  // open logfile
380  EsafMsgDispatcher::Get ()->OpenLog (fFileNames[kLog]);
381
382  Msg (EsafMsg::Info) << "Logging to file " + fFileNames[kLog] +
383    " started" << MsgDispatch;
384
385  // header data
386  UInt_t len = 80;
387
388  TString head1 ('_', 80);
389  head1[0] = ' ';
390  head1[len - 1] = ' ';
391  TString head2 (' ', 80);
392  head2[0] = '|';
393  head2[len - 1] = '|';
394  TString head3 ('_', 80);
395  head3[0] = '|';
396  head3[len - 1] = '|';
397  TString line, msg;
398
399  Msg (EsafMsg::Info) << head1 << MsgDispatch;
400  Msg (EsafMsg::Info) << head2 << MsgDispatch;
401
402  line = head2;
403  msg = "ESAF Run Starting";
404  line.Replace (3, msg.Length (), msg.Data (), msg.Length ());
405
406  Msg (EsafMsg::Info) << line << MsgDispatch;
407
408  TTimeStamp tStart;
409  line = head2;
410  msg = Form ("Local time: %s", tStart.AsString ("l"));
411  line.Replace (5, msg.Length (), msg.Data (), msg.Length ());
412
413  Msg (EsafMsg::Info) << line << MsgDispatch;
414
415  Msg (EsafMsg::Info) << head3 << MsgDispatch;
416  Msg (EsafMsg::Info) << MsgDispatch;
417
418
419  MsgForm (EsafMsg::Info, "ESAF Environment:");
420  Msg (EsafMsg::Info) << MsgDispatch;
421  MsgForm (EsafMsg::Info, "   Current Directory: %s",
422           gSystem->WorkingDirectory ());
423  MsgForm (EsafMsg::Info, "   Simu Config Path : %s",
424           gEsafSys->GetCfgPath ());
425  MsgForm (EsafMsg::Info, "   Simu Auxilar Path: %s",
426           gEsafSys->GetAuxPath ());
427  MsgForm (EsafMsg::Info, "   Simu Tmp Path    : %s",
428           gEsafSys->GetTmpPath ());
429  MsgForm (EsafMsg::Info, "   Simu Output Path : %s",
430           gEsafSys->GetOutPath ());
431  MsgForm (EsafMsg::Info, "   Host Machine     : %s", gSystem->HostName ());
432  Msg (EsafMsg::Info) << MsgDispatch;
433
434
435  // set config dump
436  Config::Get ()->SetCfgDump (fFileNames[kDump].c_str ());
437
438  vector < string >::const_iterator itCfg;
439  for (itCfg = fUsrCfgs.begin (); itCfg != fUsrCfgs.end (); itCfg++)
440    Msg (EsafMsg::Debug) << "Using custom config: " + (*itCfg) << MsgDispatch;
441
442  // add the user defined variables to the logfile
443  for (size_t i (0); i < fUsrKeys.size (); i++)
444    Msg (EsafMsg::Debug) << "Cmd line option: class " +
445      fUsrKeys[i] + ", value " + fUsrValues[i] << MsgDispatch;
446
447
448
449}
450
451//______________________________________________________________________________
452void
453SimuApplication::EndJob ()
454{
455  // final clean up
456
457  // delete Euso detector if it exists
458  if (Euso ())
459    {
460      delete fDetector;
461      fDetector = NULL;
462    }
463
464  // delete LightToEuso
465  if (Light ())
466    {
467      delete fLightToEuso;
468      fLightToEuso = NULL;
469    }
470
471  // save trees and close file
472  if (Manager ())
473    Manager ()->Close ();
474
475  // save standard config if required
476  Config::Get ()->SaveConfig ();
477
478  UInt_t len = 80;
479
480  TString head1 ('_', 80);
481  head1[0] = ' ';
482  head1[len - 1] = ' ';
483  TString head2 (' ', 80);
484  head2[0] = '|';
485  head2[len - 1] = '|';
486  TString head3 ('_', 80);
487  head3[0] = '|';
488  head3[len - 1] = '|';
489  TString line, msg;
490
491  Msg (EsafMsg::Info) << head1 << MsgDispatch;
492  Msg (EsafMsg::Info) << head2 << MsgDispatch;
493
494  line = head2;
495  msg = "ESAF Run Completed";
496  line.Replace (3, msg.Length (), msg.Data (), msg.Length ());
497
498  Msg (EsafMsg::Info) << line << MsgDispatch;
499
500  TTimeStamp tEnd;
501  line = head2;
502  msg = Form ("Local time: %s", tEnd.AsString ("l"));
503  line.Replace (5, msg.Length (), msg.Data (), msg.Length ());
504
505  Msg (EsafMsg::Info) << line << MsgDispatch;
506
507  Msg (EsafMsg::Info) << head3 << MsgDispatch;
508  Msg (EsafMsg::Info) << MsgDispatch;
509
510}
511
512
513//______________________________________________________________________________
514void
515SimuApplication::Build ()
516{
517  // build (or rebuild) application chain
518
519  //FIXME: When Config is reset all ESAF modules must be rebuilt due to
520  //   the ConfigFileParser pointers.
521  //   Config::Reset must be modified to reset just one module at time.
522
523  Config::Get ()->Reset (kFALSE);
524
525  SafeDelete (fManager);
526  if (fWriteRoot)
527    fManager = new SimuRootFileManager ();
528
529
530  // rebuild euso detector if required
531  // set gEusoDetector to right value (global pointer defined in EusoDetector.hh)
532  if (HasChanged (kESAFDetector))
533    {
534      if (fDetector)
535        delete fDetector;
536      fDetector = NULL;
537
538      // parameters are filled
539      if (Manager ())
540        Manager ()->ResetRunPars ();
541      fDetector = ElectronicsFactory::Get ()->MakeDetector ();
542
543      DetectorGeometry *detGeo = fDetector->GetGeometry ();
544      ConfigFileParser *p = Config::Get ()->GetCF ("General", "Euso");
545      Double_t alt = p->GetNum ("Euso.fAltitude") * sou::km;
546      TVector3 pos (0, 0, alt);
547      detGeo->SetPos (pos);
548
549      /*             // Detector's orientation
550       *             // diabled until further tests.
551       *
552       *             Double_t phi, theta, psi;
553       *             phi = p->GetNum("Euso.fXPhi");
554       *             theta = p->GetNum("Euso.fXTheta");
555       *             psi = p->GetNum("Euso.fXPsi");
556       *             geo->SetXEulerRotation(phi, theta, psi);
557       */
558
559      SetChanged (kESAFDetector, kFALSE);
560    }
561
562  // rebuild shower generator if required
563  if (HasChanged (kESAFLight))
564    {
565      if (fLightToEuso)
566        delete fLightToEuso;
567      fLightToEuso = NULL;
568      fLightToEuso = LightFactory::Get ()->GetLightToEuso ();
569
570      SetChanged (kESAFLight, kFALSE);
571    }
572}
573
574
575//______________________________________________________________________________
576void
577SimuApplication::Help (const char *line)
578{
579  TApplication::Help (line);
580}
581
582//______________________________________________________________________________
583Bool_t
584SimuApplication::DoEvent ()
585{
586  // simulate and (if required) display a single event
587  // WriteTelemetry=true     : writes in Telemetry (ASCII) file
588
589
590  UInt_t len = 80;
591  TString divider ('_', len);
592  TString head1 ('_', len);
593  head1[0] = ' ';
594  head1[len - 1] = ' ';
595  TString head2 (' ', len);
596  head2[0] = '|';
597  head2[len - 1] = '|';
598  TString head3 ('_', len);
599  head3[0] = '|';
600  head3[len - 1] = '|';
601  TString line, msg;
602
603  msg = Form ("Event %d Started", fEvCount);
604  line = head2;
605  line.Replace (3, msg.Length (), msg.Data (), msg.Length ());
606
607  Msg (EsafMsg::Info) << head1 << MsgDispatch;
608  Msg (EsafMsg::Info) << head2 << MsgDispatch;
609  Msg (EsafMsg::Info) << line << MsgDispatch;
610  Msg (EsafMsg::Info) << head2 << MsgDispatch;
611  Msg (EsafMsg::Info) << MsgDispatch;
612
613  // time info
614  TString s = Form ("Event %d", fEvCount);
615  TBenchmark gB;
616  gB.Start (s);
617
618  if (isLocked ())
619    {
620      MsgForm (EsafMsg::Warning,
621               "Cannot run because application is locked\n");
622      MsgForm (EsafMsg::Warning,
623               "Close configuration windows before running\n");
624      return kFALSE;
625    }
626
627  try
628  {
629    Euso ()->ClearMemory ();
630    if (Light ())
631      Light ()->ClearMemory ();
632    // clear root event
633    if (Event ())
634      {
635        Event ()->ClearAndShrink ("C");
636        Event ()->Build (GetRunNumber (), fEvCount, fRunName);
637        // save the status of the random number generator before simulating the new event
638        Event ()->GetHeader ()->SetRandom (EsafRandom::Get ());
639
640
641        if (Euso ())
642          {
643            EEventGeoFiller a (Euso ()->GetGeometry ());
644            Event ()->Fill (a);
645          }
646      }
647  }
648  catch (exception & e)
649  {
650
651    Msg (EsafMsg::Warning) << divider << endl;
652    Msg (EsafMsg::Warning) << MsgDispatch;
653    Msg (EsafMsg::
654         Error) <<
655      "An exception without sender has been catched while cleaning memory." <<
656      MsgDispatch;
657    Msg (EsafMsg::Error) << "Rethrowing..." << MsgDispatch;
658    Msg (EsafMsg::Warning) << MsgDispatch;
659    throw e;
660
661
662  }
663  catch (EsafMsg & msg)
664  {
665
666    if (msg.GetSeverity () >= EsafMsg::Panic)
667      throw runtime_error (msg.GetText ());
668
669    string msgtxt = msg.GetText ();
670    Msg (EsafMsg::Warning) << divider << endl;
671    Msg (EsafMsg::Warning) << MsgDispatch;
672    Msg (EsafMsg::Warning) << "An Exception message sent by " << msg.
673      GetSender () << " has been catched while cleaning memory" <<
674      MsgDispatch;
675    Msg (EsafMsg::Warning) << "Message:" << MsgDispatch;
676    Msg (EsafMsg::Warning) << MsgDispatch;
677    Msg (EsafMsg::Warning) << "  " << msgtxt << MsgDispatch;
678    Msg (EsafMsg::Warning) << MsgDispatch;
679
680    Msg (EsafMsg::Warning) << "Event status set to failed" << MsgDispatch;
681    if (Event ())
682      Event ()->GetHeader ()->SetStatus (EHeader::kFailed, msgtxt.c_str ());
683    MsgForm (EsafMsg::Warning, "Exception message saved into Event %d",
684             fEvCount);
685    Msg (EsafMsg::Warning) << divider << endl;
686    Msg (EsafMsg::Warning) << MsgDispatch;
687
688  }
689
690  Bool_t failed = kFALSE;
691
692  // event generation and radiative transport through atmosphere
693  MCTruth *truth = 0;
694  PhotonsOnPupil *photons = 0;
695  Telemetry *data = 0;
696
697  try
698  {
699    if (Light () && Euso ())
700      {
701        Light ()->Reset ();
702        photons = Light ()->Get (Euso ()->GetGeometry ());
703        if (photons == NULL)
704          {
705            MsgForm (EsafMsg::Info, "PhotonsOnPupil object is null");
706            return kTRUE;
707          }
708        truth = Light ()->GetTruth ();
709      }
710    else
711      MsgForm (EsafMsg::Info, "LightToEuso is null.");
712
713    // detector response simulation
714    if ((Euso () && photons && Light ()) || (Euso () && (!Light ())))
715      {
716        Euso ()->Reset ();
717        data = Euso ()->Get (photons);
718      }
719  }
720  catch (exception & e)
721  {
722
723    failed = kTRUE;
724    Msg (EsafMsg::Warning) << divider << endl;
725    Msg (EsafMsg::Warning) << MsgDispatch;
726    Msg (EsafMsg::
727         Error) << "An exception without sender has been catched." <<
728      MsgDispatch;
729
730    Msg (EsafMsg::Error) << "Message:" << MsgDispatch;
731    Msg (EsafMsg::Error) << "  " << e.what () << MsgDispatch;
732    Msg (EsafMsg::Error) << "Rethrowing..." << MsgDispatch;
733    Msg (EsafMsg::Warning) << MsgDispatch;
734    throw e;
735
736
737  }
738  catch (EsafMsg & msg)
739  {
740
741    if (msg.GetSeverity () >= EsafMsg::Panic)
742      throw runtime_error (msg.GetText ());
743
744    string msgtxt = msg.GetText ();
745    failed = kTRUE;
746    Msg (EsafMsg::Warning) << divider << endl;
747    Msg (EsafMsg::Warning) << MsgDispatch;
748    Msg (EsafMsg::Warning) << "An Exception message sent by " << msg.
749      GetSender () << " has been catched" << MsgDispatch;
750    Msg (EsafMsg::Warning) << "Message:" << MsgDispatch;
751    Msg (EsafMsg::Warning) << MsgDispatch;
752    Msg (EsafMsg::Warning) << "  " << msgtxt << MsgDispatch;
753    Msg (EsafMsg::Warning) << MsgDispatch;
754
755    Msg (EsafMsg::Warning) << "Event status set to failed" << MsgDispatch;
756    if (Event ())
757      Event ()->GetHeader ()->SetStatus (EHeader::kFailed, msgtxt.c_str ());
758    MsgForm (EsafMsg::Warning, "Exception message saved into Event %d",
759             fEvCount);
760    Msg (EsafMsg::Warning) << divider << endl;
761    Msg (EsafMsg::Warning) << MsgDispatch;
762
763  }
764
765  // dump time info on screen
766  gB.Stop (s);
767
768  msg = Form ("Event %d %s, REAL=%6.2f s  CPU=%6.2f s",
769              fEvCount, failed ? "Failed" : "Completed",
770              gB.GetRealTime (s), gB.GetCpuTime (s));
771  line.Replace (3, msg.Length (), msg.Data (), msg.Length ());
772
773  Msg (EsafMsg::Info) << MsgDispatch;
774  Msg (EsafMsg::Info) << head2 << MsgDispatch;
775  Msg (EsafMsg::Info) << line << MsgDispatch;
776  Msg (EsafMsg::Info) << head3 << MsgDispatch;
777  Msg (EsafMsg::Info) << MsgDispatch;
778
779  // write output data file (Telemetry format)
780  if (data && fWriteTelemetry)
781    {
782      data->SetTruth (truth);
783
784      if (!data->IsOpen ())
785        data->Open (fFileNames[kTelemetry].c_str ());
786      data->Write ();
787    }
788
789  // fill root file if enabled
790  if (Manager ())
791    Manager ()->FillEvent ();
792
793  fEvCount++;
794  return kTRUE;
795
796
797}
798
799//______________________________________________________________________________
800Bool_t
801SimuApplication::DoAll ()
802{
803  //
804  // Simulate all events available from the data source
805  // DoEvent returns kFalse in case of error so the run will stop
806  // if fEvMax is -1 it never stops until error or end of file
807  //
808
809  Int_t ev = fEvMax;
810  ResetEvCounter ();
811
812  // OpenFile
813  if (Manager ())
814    Manager ()->Open (fFileNames[kRoot]);
815  if (Event ())
816    Event ()->GetHeader ()->SetRandom (EsafRandom::Get ());
817
818  // Lock the Event
819  if (Manager ())
820    Manager ()->LockEvent ();
821
822  ////////////////////////////////////////////////////////
823
824  TString jobname = Form ("Job with %d events", fEvMax);
825  TBenchmark gB;
826  gB.Start (jobname);
827  SetRunNumber ((Int_t) Config::Get ()->GetCF ("General", "Run")->
828                GetNum ("Run.fRunNumber"));
829  try
830  {
831    while (ev--)
832      {
833        if (!DoEvent ())
834          return kFALSE;
835      }
836  }
837  catch (exception & e)
838  {
839    UInt_t len = 80;
840    TString head ('_', len);
841
842    Msg (EsafMsg::Error) << head << MsgDispatch;
843    Msg (EsafMsg::Error) << MsgDispatch;
844    Msg (EsafMsg::Error) << "A Critical error has occurred" << MsgDispatch;
845    Msg (EsafMsg::Error) << "Message:" << MsgDispatch;
846    Msg (EsafMsg::Error) << MsgDispatch;
847    Msg (EsafMsg::Error) << "  " << e.what () << MsgDispatch;
848    Msg (EsafMsg::Error) << MsgDispatch;
849    Msg (EsafMsg::Error) << "EventLoop stopped" << MsgDispatch;
850    Msg (EsafMsg::Error) << head << MsgDispatch;
851    Msg (EsafMsg::Error) << MsgDispatch;
852  }
853  gB.Stop (jobname);
854  MsgForm (EsafMsg::Info,
855           "Average time per event:  REAL=%6.2f s   CPU=%6.2f s",
856           gB.GetRealTime (jobname) / fEvMax,
857           (gB.GetCpuTime (jobname) / fEvMax));
858  MsgForm (EsafMsg::Info, "Total time:  REAL=%6.2f s   CPU=%6.2f s",
859           gB.GetRealTime (jobname), gB.GetCpuTime (jobname));
860
861  // Unlock Event
862  if (Manager ())
863    Manager ()->UnlockEvent ();
864  // Close File
865  if (Manager ())
866    Manager ()->Close ();
867  //
868  return kTRUE;
869}
870
871//______________________________________________________________________________
872void
873SimuApplication::SetLock (Bool_t lk)
874{
875  //
876  // Lock the application.
877  // If locked, events are not processed
878  //
879
880  if (lk)
881    fLock++;
882  else
883    fLock--;
884  if (fLock < 0)
885    fLock = 0;
886}
887
888//______________________________________________________________________________
889Bool_t
890SimuApplication::DumpLastEvent (string * buffer)
891{
892  //
893  // dump event on stdout or into a buffer
894  // buffer must be large enough
895  // if buffer is NULL, dump on cout
896  // return kFALSE if no data is available
897  //
898
899  //  if ( ! E()->Data() )
900  //    return kFALSE;
901  //  if ( buffer )
902  //    *buffer = E()->Data()->Dump();
903  //  else {
904  //    cout << endl << endl;
905  //    cout << "EUSO DETECTOR SIMULATION DUMP.   Event=" << EventCounter() << endl;
906  //    cout << E()->Data()->Dump() << endl << endl;
907  //    cout.flush();
908  //  }
909  return kTRUE;
910}
911
912//
913////______________________________________________________________________________
914//void SimuApplication::EnableModule(EsafElement e, Bool_t val) {
915//    fEnModule[e]=val;
916//    SetChanged(e);
917//    //Build();
918//}
919
920//______________________________________________________________________________
921void
922SimuApplication::ResetCopies ()
923{
924  // reset list of event copies
925  // used for re-rerunning the same event with different parameters
926
927  for (Int_t i = 0; i < fEventCopies.GetEntriesFast (); i++)
928    {
929      EEvent *pEv = (EEvent *) (fEventCopies[i]);
930      if (pEv)
931        delete pEv;
932    }
933}
Note: See TracBrowser for help on using the repository browser.