| Geant4 User's Guide For Application Developers Getting Started with Geant4

2.1 How to Define the main() Program

## 2.1.1 A Sample `main()` Method

The contents of `main()` will vary according to the needs of a given simulation application and therefore must be supplied by the user. The Geant4 toolkit does not provide a `main()` method, but a sample is provided here as a guide to the beginning user. Source listing 2.1.1 is the simplest example of `main()` required to build a simulation program.

    #include "G4RunManager.hh"
    #include "G4UImanager.hh"

    #include "ExN01DetectorConstruction.hh"
    #include "ExN01PhysicsList.hh"
    #include "ExN01PrimaryGeneratorAction.hh"

    int main()
    {
      // construct the default run manager
      G4RunManager* runManager = new G4RunManager;

      // set mandatory initialization classes
      runManager->SetUserInitialization(new ExN01DetectorConstruction);
      runManager->SetUserInitialization(new ExN01PhysicsList);

      // set mandatory user action class
      runManager->SetUserAction(new ExN01PrimaryGeneratorAction);

      // initialize G4 kernel
      runManager->initialize();

      // get the pointer to the UI manager and set verbosities
      G4UImanager* UI = G4UImanager::GetUIpointer();
      UI->ApplyCommand("/run/verbose 1");
      UI->ApplyCommand("/event/verbose 1");
      UI->ApplyCommand("/tracking/verbose 1");

      // start a run
      int numberOfEvent = 3;
      runManager->BeamOn(numberOfEvent);

      // job termination
      delete runManager;
      return 0;
    }
Source listing 2.1.1

The `main()` method is implemented by two toolkit classes, G4RunManager and G4UImanager, and three classes, ExN01DetectorConstruction, ExN01PhysicsList and ExN01PrimaryGeneratorAction, which are derived from toolkit classes. Each of these are explained in the following sections.

## 2.1.2 G4RunManager

The first thing `main()` must do is create an instance of the G4RunManager class. This is the only manager class in the Geant4 kernel which should be explicitly constructed in the user's `main()`. It controls the flow of the program and manages the event loop(s) within a run. When G4RunManager is created, the other major manager classes are also created. They are deleted automatically when G4RunManager is deleted. The run manager is also responsible for managing initialization procedures, including methods in the user initialization classes. Through these the run manager must be given all the information necessary to build and run the simulation, including

1. how the detector should be constructed,
2. all the particles and all the physics processes to be simulated,
3. how the primary particle(s) in an event should be produced and
4. any additional requirements of the simulation.

In the sample `main()` the lines

           runManager->SetUserInitialization(new ExN01DetectorConstruction);
           runManager->SetUserInitialization(new ExN01PhysicsList);

create objects which specify the detector geometry and physics processes, respectively, and pass their pointers to the run manager. ExN01DetectorConstruction is an example of a user initialization class which is derived from G4VUserDetectorConstruction. This is where the user describes the entire detector setup, including

- its geometry,
- the materials used in its construction,
- a definition of its sensitive regions and
- the readout schemes of the sensitive regions.

Similarly ExN01PhysicsList is derived from G4VUserPhysicsList and requires the user to define

- the particles to be used in the simulation,
- the range cuts for these particles and
- all the physics processes to be simulated.

The next instruction in `main()`

           runManager->SetUserAction(new ExN01PrimaryGeneratorAction);

creates an instance of a particle generator and passes its pointer to the run manager. ExN01PrimaryGeneratorAction is an example of a user action class which is derived from G4VUserPrimaryGeneratorAction. In this class the user must describe the initial state of the primary event. This class has a public virtual method named `generatePrimaries()` which will be invoked at the beginning of each event. Details will be given in Section 2.6. Note that Geant4 does not provide any default behavior for generating a primary event.

The next instruction

           runManager->initialize();

performs the detector construction, creates the physics processes, calculates cross sections and otherwise sets up the run. The final run manager method in `main()`

           int numberOfEvent = 3;
           runManager->beamOn(numberOfEvent);

begins a run of three sequentially processed events. The `beamOn()` method may be invoked any number of times within `main()` with each invocation representing a separate run. Once a run has begun neither the detector setup nor the physics processes may be changed. They may be changed between runs, however, as described in Section 3.4.4. More information on G4RunManager in general is found in Section 3.4.

As mentioned above, other manager classes are created when the run manager is created. One of these is the user interface manager, G4UImanager. In `main()` a pointer to the interface manager must be obtained

          G4UImanager* UI = G4UImanager::getUIpointer();

in order for the user to issue commands to the program. In the present example the `applyCommand()` method is called three times to direct the program to print out information at the run, event and tracking levels of simulation. A wide range of commands is available which allows the user detailed control of the simulation. A list of these commands can be found in Section 7.1.

## 2.1.3 User Initialization and Action Classes

Mandatory User Classes

There are three classes which must be defined by the user. Two of them are user initialization classes, and the other is a user action class. They must be derived from the abstract base classes provided by Geant4: G4VUserDetectorConstruction, G4VuserPhysicsList and G4VuserPrimaryGeneratorAction. Geant4 does not provide default behavior for these classes. G4RunManager checks for the existence of these mandatory classes when the `initialize()` and `BeamOn()` methods are invoked.

As mentioned in the previous section, G4VUserDetectorConstruction requires the user to define the detector and G4VUserPhysicsList requires the user to define the physics. Detector definition will be discussed in Sections 2.2 and 2.3. Physics definition will be discussed in Sections 2.4 and 2.5. The user action class G4VuserPrimaryGeneratorAction requires that the initial event state be defined. Primary event generation will be discussed in Section 2.6.

Optional User Action Classes

Geant4 provides five user hook classes:

- G4UserRunAction
- G4UserEventAction
- G4UserStackingAction
- G4UserTrackingAction
- G4UserSteppingAction

There are several virtual methods in each of these classes which allow the specification of additional procedures at all levels of the simulation application. Details of the user initialization and action classes are provided in Section 6.

## 2.1.4. G4UImanager and UI Command Submission

Geant4 provides a category named intercoms. G4UImanager is the manager class of this category. Using the functionalities of this category, you can invoke set methods of class objects of which you do not know the pointer. In Source listing 2.1.1, the verbosities of various Geant4 manager classes are set. Detailed mechanism description and usage of intercoms will be given in the next chapter, with a list of available commands. Command submission can be done all through the application.

    #include "G4RunManager.hh"
    #include "G4UImanager.hh"
    #include "G4UIterminal.hh"
    #include "G4VisExecutive.hh"

    #include "N02DetectorConstruction.hh"
    #include "N02PhysicsList.hh"
    #include "N02PrimaryGeneratorAction.hh"
    #include "N02RunAction.hh"
    #include "N02EventAction.hh"
    #include "N02SteppingAction.hh"

    #include "g4templates.hh"

    int main(int argc,char** argv)
    {
      // construct the default run manager
      G4RunManager * runManager = new G4RunManager;

      // set mandatory initialization classes
      N02DetectorConstruction* detector = new N02DetectorConstruction;
      runManager->SetUserInitialization(detector);
      runManager->SetUserInitialization(new N02PhysicsList);

      // visualization manager
      G4VisManager* visManager = new G4VisExecutive;
      visManager->initialize();

      // set user action classes
      runManager->SetUserAction(new N02PrimaryGeneratorAction(detector));
      runManager->SetUserAction(new N02RunAction);
      runManager->SetUserAction(new N02EventAction);
      runManager->SetUserAction(new N02SteppingAction);

      // get the pointer to the User Interface manager
      G4UImanager* UI = G4UImanager::GetUIpointer();

      if(argc==1)
      // Define (G)UI terminal for interactive mode
      {
        G4UIsession * session = new G4UIterminal;
        UI->ApplyCommand("/control/execute prerun.g4mac");
        session->sessionStart();
        delete session;
      }
      else
      // Batch mode
      {
        G4String command = "/control/execute ";
        G4String fileName = argv[1];
        UI->ApplyCommand(command+fileName);
      }

      // job termination
      delete visManager;
      delete runManager;

      return 0;
    }
Source list 2.1.2 An example of `main()` using interactive terminal and visualization. Code modified from 2.1.1. are shown in blue.

## 2.1.5 G4cout and G4cerr

Although not yet included in the above examples, output streams will be needed. G4cout and G4cerr are iostream objects defined by Geant4. The usage of these objects is exactly the same as the ordinary cout and cerr, except that the output streams will be handled by G4UImanager. Thus, output strings may be displayed on another window or stored in a file. Manipulation of these output streams will be described in Section 7.2.4. These objects should be used instead of the ordinary cout and cerr.

About the authors