/*! @page  howg4 How Does Geant4 Runs?

<BR>
<B> Previous:</B> @ref Useraction
<B> Up:</B> @ref Main
<B> Next:</B>  @ref howg4
<BR>

In this section we describe how Geant4 proceeds to run a simulation, which are the successive classes involved in the process of a run and what is the interplay between them.

\section how_runmgr The G4RunManager
As written precedently, the main component of the simulation is the \b G4RunManager object which is instanciated at the very beginning of the LEMuSR.cc file. <b>It is the class in charge of the simulation control</b>. 

\cd
//! 1  The run manager construction
G4RunManager* runManager = new G4RunManager;
\ec

The simulation procedure will be launched when the user invokes the method  <tt>BeamOn(#NumberOfEvents)</tt>.


\section how_init Initialization of the mandatory and user action classes.
The class G4RunManager features the following important pointers: 

\code
210   protected:
211     G4RunManagerKernel * kernel;
212     G4EventManager * eventManager;
213 
214     G4VUserDetectorConstruction * userDetector;
215     G4VUserPhysicsList * physicsList;
216     G4UserRunAction * userRunAction;
217     G4VUserPrimaryGeneratorAction * userPrimaryGeneratorAction;
218     G4UserEventAction * userEventAction;
219     G4UserStackingAction * userStackingAction;
220     G4UserTrackingAction * userTrackingAction;
221     G4UserSteppingAction * userSteppingAction;
222 
23   private:
224     G4RunMessenger* runMessenger;
\endcode Transcript of G4RunManager.hh

* - The G4RunManagerKernel is responsible for controlling the state of the simulation at the different stages of the run. It contains the following methods 
*   - DefineWorldVolume
*   - InitializePhysics
*   - RunInitialization
*   - RunTermination
*.
*which will be called by the run manager successively in this order.
*.
* - @anchor eventManager The G4EventManager is responsible for the control of the current event of the simulation. More details are given later about it.

* - The G4VUser classes are @ref virtual_classes "virtual classes": this means that they consist in virtual methods which have to be entirely implemented by the user. During the simulation, those methods are called by the simulation managers in order to execute precise operations personalized by the user. 

For example, the geometry initialization method of the kernel will call the <tt>userDetector->Construct()</tt> method in order to setup the desired geometry. It is now clear that when the user defines his own geometry class he \b must implement the detector description method Construct() with the same name (cf. \ref geometry).

Now one understands the big advantage of the object oriented language and of the use of @ref virtual_classes "virtual classes" and methods: the \gf package can be regarded as a plug-and-play simulation where the communication with virtual user parameters like the geometry, the physics to take into account or the actions to operate at different stages (plotting, histogramming...) relies on pre-established commands.



After instanciation of the mandatory classes in the LEMuSR.cc file, 
\cd
     //! 2.1  LEMuSR Initialization classes
  LEMuSRDetectorConstruction*    lemuDetector    = new  LEMuSRDetectorConstruction(); 
  
  LEMuSRPhysicsList*      lemuPhysicsList        = new  LEMuSRPhysicsList();
      
     //! 2.2  LEMuSR Action class
  LEMuSRPrimaryGeneratorAction* lemuPGA          = new  LEMuSRPrimaryGeneratorAction();
\ec

the following methods are called:
* - \cd
//! 2.3  Setting the mandatory Initialization classesrunManager->SetUserInitialization(MandatoryDetectorClass);
runManager->SetUserInitialization(MandatoryPhysicsListClass);
//! 2.4  Setting the mandatory Action class
runManager->SetUserAction(MandatoryPrimaryGeneratorActionClass);
\ec
* for the initilization of the mandatory action class and
* - \cd
   //! 2.4  Setting the mandatory Action class
  runManager ->SetUserAction( lemuPGA );
  
  //! 3  The optionnal classes
  runManager ->SetUserAction( new  LEMuSRRunAction());
  runManager ->SetUserAction( new  LEMuSREventAction());
  runManager ->SetUserAction( new  LEMuSRTrackingAction());
  (...)
  runManager ->SetUserAction( new  LEMuSRSteppingAction()); 
\ec
* for the initialization of the action classes.


When those methods are called, the run manager assigns its pointers to the classes defined by the user.

\cd
255     inline void SetUserInitialization(G4VUserDetectorConstruction* userInit)
256     { userDetector = userInit; }
257     inline void SetUserInitialization(G4VUserPhysicsList* userInit)
258     {
259       physicsList = userInit;
260       kernel->SetPhysics(userInit);
261     }
        (...)
276     inline void SetUserAction(G4UserTrackingAction* userAction)
277     { 
278       eventManager->SetUserAction(userAction); 
279       userTrackingAction = userAction;
280     }
\ec

In this transcript one sees that the pointers to the users classes are also given to the other classes like the G4RunManagerKernel (initialization classes) or the G4EventManager (action classes). 


\section how_rminit Initialization of the Run Manager

The run manager is initialized in the main() by calling the <tt>Initialize()</tt> method
 \cd
 //! 5  Initialize G4 kernel
 runManager -> Initialize();
 \ec

 The role of this method is to initialize the detector and the physics list
\cd 
298 void G4RunManager::Initialize()
299 {
      (...)
309   if(!geometryInitialized) InitializeGeometry();
310   if(!physicsInitialized) InitializePhysics();
311   initializedAtLeastOnce = true;
312 }
313 
314 void G4RunManager::InitializeGeometry()
315 {
316 	  if(!userDetector)
317   {
318     G4Exception
319     ("G4RunManager::InitializeGeometry - G4VUserDetectorConstruction is not defined.");
320   }
321 
322   if(verboseLevel>1) G4cout << "userDetector->Construct() start." << G4endl;
323   kernel->DefineWorldVolume(userDetector->Construct(),false);
324   geometryInitialized = true;
325 }
326 
327 void G4RunManager::InitializePhysics()
328 {
329   if(physicsList)
330   {
331     if(verboseLevel>1) G4cout << "physicsList->Construct() start." << G4endl;
332     kernel->InitializePhysics();
333   }
334   else
335   {
336     G4Exception("G4VUserPhysicsList is not defined");
337   }
338   physicsInitialized = true;
339 }
340 
\ec
what is done by calling the <tt>Construct()</tt> methods via the kernel initialization methods.

Once this initialization is complete, the simulation is ready to be launched by calling the <tt>beamOn()</tt> method.


\anchor beamOn
\section how_beamon beamOn()

The <tt>beamOn()</tt> method is called by tue user in the terminal. Once called, this method will start the simulation procedure, generating as many events as given in argument. If the user gives no argument, only one event will be generated.

\cd
122 void G4RunManager::BeamOn(G4int n_event,const char* macroFile,G4int n_select)
123 {
124   G4bool cond = ConfirmBeamOnCondition();
125   if(cond)
126   {
127     numberOfEventToBeProcessed = n_event;
128     RunInitialization();
129     if(n_event>0) DoEventLoop(n_event,macroFile,n_select);
130     RunTermination();
131   }
\ec

The <tt>beamOn()</tt> method invokes tree important methods of the run manager:
* -# First, the <tt>RunInitialization()</tt> method for the run preparation:
*    -# The kernel run initialization method is called: it will confirm the correct definition of the geometry, physics etc. and create a G4StateManager object, which is responsible for handling and updating the running state of the Geant4 application during its different phases.
*    -# A new G4Run object is instanciated.
*    -# If a \b user \b run \b action class is defined, the G4run object is created by calling the <tt>G4UserRunAction::GenerateRun()</tt> method and the <tt>G4UserRunAction::BeginOfRunAction()</tt> method is called to take user actions at the beginning of the run (cf. \ref runaction ). 
\cd 
166 void G4RunManager::RunInitialization()
167 {
168   if(!(kernel->RunInitialization())) return; 
      // Check if user classes are initialized
      (...) 
171   if(userRunAction) currentRun = userRunAction->GenerateRun();
172   if(!currentRun) currentRun = new G4Run();
      // Create new G4Run object
182   if(userRunAction) userRunAction->BeginOfRunAction(currentRun);
      // Perform the user's actions for the beginning of the run
      (...)
197   if(verboseLevel>0) G4cout << "Start Run processing." << G4endl;
198 }
\ec 
In the case of the \lemu simulation the <tt>LEMuSRRunAction::BeginOfRunAction()</tt> method is used to initialize the user interface terminal.
* -# Second, the <tt>DoEventLoop()</tt> method is called to simulate as many event as wanted. The event loop is described in the next section.
* -# Finally, the <tt>RunTermination()</tt> method is called and simply consists in the execution of the <tt>RunTermination()</tt> from the kernel, and makes the simulation ready for a new run. 
\cd
303 void G4RunManagerKernel::RunTermination()
304 { G4StateManager::GetStateManager()->SetNewState(G4State_Idle); }
\ec




\section how_evtloop The Event Loop

The following transcript shows how an event loop is organised. The loop iteration number (the number of events to simulate) is provided by the user.
\cd
200 void G4RunManager::DoEventLoop(G4int n_event,const char* macroFile,G4int n_select)
201 {
     (...)
215 // Event loop
216   G4int i_event;
217   for( i_event=0; i_event<n_event; i_event++ )
218   {
219     currentEvent = GenerateEvent(i_event);
220     eventManager->ProcessOneEvent(currentEvent);
221     AnalyzeEvent(currentEvent);
222     if(i_event<n_select) G4UImanager::GetUIpointer()->ApplyCommand(msg);
223     StackPreviousEvent(currentEvent);
224     currentEvent = 0;
225     if(runAborted) break;
226   }
     (...)
239 }
\ec

Once the event is generated by calling the <tt>GeneratePrimaries()</tt> method of the user primary generator action (cf. LEMuSRPrimaryGeneratorAction), the \ref eventManager will simulate one event, propagating a particle through the described detector and making it interact according to the defined interaction and processes.


\subsection how_processevent ProcessOneEvent()

The <A HREF="http://www-geant4.kek.jp/lxr/source/event/src/G4EventManager.cc"><strong>G4EventManager::ProcessOneEvent()</strong></A> method prepare the G4EventManager::DoProcessing() method, which is actually responsible for the event simulation. The procedure is the following:
* -# Initialization of the state of the run via the G4StateManager
* -# Instanciation of the <A href="http://www-geant4.kek.jp/lxr/source/geometry/navigation/include/G4Navigator.hh"><strong>navigator</strong></A> object. * It is the class responsible for the calculation of time and distances during the navigation of the particle in the different volumes of the geometry. The <A href="http://www-geant4.kek.jp/lxr/source/geometry/navigation/include/G4Navigator.hh">navigator</A> object is created by the <A href="http://www-geant4.kek.jp/lxr/source/geometry/navigation/include/G4TransportationManager.hh">G4TransportationManager</A>, itself created at the very beginning of the simulation, before the main() method is called.
* -# Initialization of the <A href="http://www-geant4.kek.jp/lxr/source/digits_hits/detector/include/G4SDManager.hh">sensitive detector manager</a>. 
* -# Initialization of the track container, which is an object of the <A HREF="http://www-geant4.kek.jp/lxr/source/event/src/G4StackManager.cc">G4StackManager</A> class. It stores the initial track and its secondaries  until they are all simulated. The UserStackingAction can be used to segregate the secondary particles tracks to stack or not.
* -# Stack tracks from the pimary event. This is done by calling the GimmePrimaries() method from the <A href="http://www-geant4.kek.jp/lxr/source/event/src/G4PrimaryTransformer.cc">G4PrimaryTransformer class</A>. This class performs the conversion of the primary particle object generated by the primary generator action into a dynamic particle, which is the particle object for the tracking.
* -# Do the following loop while the track container is not empty:
* -# Creation of a track pointer.
* -# Execution of the User Event Actions.
* -# Loop the folowing for each track in the container:
*      -# Assing the current track to the created track pointer
*      -# Call of the <A href="http://www-geant4.kek.jp/lxr/ident?i=ProcessOneTrack">G4TrackingManager::ProcessOneTrack()</A> method to simulate the track
*      -# Collect the track trajectory and stack (under conditions) the secondary tracks in the container
* -# Call the termination of the sensitive detector manager.
* -# Initialization of the state manager for a new run.
*.

\subsection how_processtrack ProcessOneTrack()
Let us now decribe the next step in the simulation hierarchy, which is the simulation of a track. This is done by calling the ProcessOneTrack() method which is a member of the <A href="http://www-geant4.kek.jp/lxr/source/tracking/include/G4TrackingManager.hh?v=7.0.p1">G4TrackingManager</A>.

After initialization of the new track taken from the stack manager, the Stepping Manager is called to set the initial step of the track. The Pre User Tracking Actions are taken and the step by step tracking is performed until the particle stops or dies. This is done by calling the G4SteppingManager::Stepping() method.

At each step, the user actions are taken before and after the step, and the process is selected according to cross section and priority given by the user. The Sensitive Detectors are also called at the step stage of the simulation.




*/