\page ExampleB5 Example B5

  Example B5 implements a double-arm spectrometer with wire chambers,
  hodoscopes and calorimeters.  Event simulation and collection are
  enabled, as well as event display and analysis.


## GEOMETRY

   The spectrometer consists of two detector arms
   (see B5::DetectorConstruction).  One arm provides
   position and timing information of the incident particle while the
   other collects position, timing and energy information of the particle
   after it has been deflected by a magnetic field centered at the
   spectrometer pivot point.

     - First arm:  box filled with air, also containing:
         - 1 hodoscope (15 vertical strips of plastic scintillator)
         - 1 drift chamber (5 horizontal argon gas layers with a
                          "virtual wire" at the center of each layer)

     - Second arm:  box filled with air, also containing:
         - 1 hodoscope (25 vertical strips of plastic scintillator)
         - 1 drift chamber (5 horizontal argon gas layers with a
                          "virtual wire" at the center of each layer)
         - 1 electromagnetic calorimeter:
               a box sub-divided along x,y and z
               axes into cells of CsI
         - 1 hadronic calorimeter:
               a box sub-divided along x,y, and z axes
               into cells of lead, with a layer of
               plastic scintillator placed at the center
               of each cell

     - Magnetic field region: air-filled cylinder which contains
                              the field (see B5::MagneticField)

   The maximum step limit in the magnetic field region is also set
   via the G4UserLimits class in a similar way as in Example B2
   (see \ref B2_s6 in B2 example documentation).

   The rotation angle of the second arm and the magnetic field value
   can be set via the interactive commands defined using the G4GenericMessenger
   class.

## PHYSICS

   This example uses the reference hadronic physics list, FTFP_BERT,
   and also adds the G4StepLimiter process.

## ACTION INITALIZATION

   B5::ActionInitialization class
   instantiates and registers to Geant4 kernel all user action classes.

   While in sequential mode the action classes are instatiated just once,
   via invoking the method:
      B5::ActionInitialization::Build()
   in multi-threading mode the same method is invoked for each thread worker
   and so all user action classes are defined thread-local.

   A run action class is instantiated both thread-local
   and global that's why its instance is created also in the method
      B5::ActionInitialization::BuildForMaster()
   which is invoked only in multi-threading mode.

## PRIMARY GENERATOR

   The primary generator action class employs the G4ParticleGun.
   The primary kinematics consists of a single particle which is
   is sent in the direction of the first spectrometer arm.

   The type of the particle and its several properties can be changed
   via the  G4 built-in commands of  the G4ParticleGun class or
   this example command defined using the G4GenericMessenger class.


## EVENT

   An event consists of the generation of a single particle which is
   transported through the first spectrometer arm.  Here, a scintillator
   hodoscope records the reference time of the particle before it passes
   through a drift chamber where the particle position is measured.
   Momentum analysis is performed as the particle passes through a magnetic
   field at the spectrometer pivot and then into the second spectrometer
   arm.  In the second arm, the particle passes through another hodoscope
   and drift chamber before interacting in the electromagnetic calorimeter.
   Here it is likely that particles will induce electromagnetic showers.
   The shower energy is recorded in a three-dimensional array of CsI
   crystals.  Secondary particles from the shower, as well as primary
   particles which do not interact in the CsI crystals, pass into the
   hadronic calorimeter.  Here, the remaining energy is collected in a
   three-dimensional array of scintillator-lead sandwiches.

   Several aspects of the event may be changed interactively by the user:
     - angle of the second spectrometer arm
     - strength of magnetic field
     - initial particle type
     - initial momentum and angle
     - momentum and angle spreads
     - type of initial particle may be randomized

   The initial particle type can be changed using the G4ParticleGun command:
```
/gun/particle particleName
```

   The UI commands specific to this example are available in /B5 command
   directory:
```
/B5/detector/armAngle angle unit
/B5/field/value field unit
/B5/generator/momentum  value unit
/B5/generator/sigmaMomentum value unit
/B5/generator/sigmaAngle value unit
/B5/generator/randomizePrimary [true|false]
```

   They are implemented in
    - B5::DetectorConstruction::DefineCommands(),
    - B5::MagneticField::DefineCommands() and
    - B5::PrimaryGeneratorAction::DefineCommands() methods
   using G4GenericMessenger class.

   In first execution of B5::EventAction::BeginOfEventAction()
   the hits collections identifiers are saved in data members of the class
   and used in B5::EventAction::EndOfEventAction() for accessing
   the hists collections and filling the accounted information in defined
   histograms and ntuples and printing its summary in a log file.
   The frequency of printing can be tuned with the built-in command
```
/run/printProgress  frequency
```

## DETECTOR RESPONSE

  All the information required to simulate and analyze an event is
  recorded in hits.  This information is recorded in the following
  sensitive detectors:

    - hodoscope:
        - particle time
        - strip ID, position and rotation
          - see B5::HodoscopeSD, B5::HodoscopeHit

    - drift chamber:
        - particle time
        - particle position
        - layer ID
          - see B5::DriftChamberSD, B5::DriftChamberHit classes

    - electromagnetic calorimeter:
        - energy deposited in cell
        - cell ID, position and rotation
          - see B5::EmCalorimeterSD, B5::EmCalorimeterHit classes

    - hadronic calorimeter:
        - energy deposited in cell
        - cell column ID and row ID, position and rotation
          - see B5::HadCalorimeterSD, B5::HadCalorimeterHit classes

     The hit classes include methods GetAttDefs and CreateAttValues to define
     and then fill extra "HepRep-style" Attributes that the visualization system
     can use to present extra information about the hits.
     For example, if you pick a B5::HadCalorimeterHit in a viewer instrumented for picking,
     you will be shown the hit's "Hit Type", "Column ID", "Row ID",
     "Energy Deposited" and "Position".
     These attributes are essentially arbitrary extra pieces of information
     (integers, doubles or strings) that are carried through the visualization.
     Each attribute is defined once in G4AttDef object and then is filled for
     each hit in a G4AttValue object.
     These attributes can also be used by commands to filter which hits are drawn:
     /vis/filtering/hits/drawByAttribute
     Detector Geometry and trajectories also carry HepRep-style attributes,
     but these are filled automatically in the base classes.
     HepRep is further described at the
     <a href="https://web.archive.org/web/20240702104514/https://www.slac.stanford.edu/~perl/heprep/"> HepRep Home Page </a>.

## ANALYSIS

   The analysis tools are used to accumulate statistics.
   Histograms and an ntuple are created in B5::RunAction::RunAction()
   constructor for the following quantities:

   - 1D histograms:
     - Number of hits in Chamber 1
     - Number of hits in Chamber 2

   - 2D histograms:
     - Drift Chamber 1 X vs Y positions
     - Drift Chamber 2 X vs Y positions

   - Ntuple:
     - Number of hits in Chamber 1
     - Number of hits in Chamber 2
     - Total energy deposit in EM calorimeter
     - Total energy deposit in Hadronic calorimeter
     - Time of flight in Hodoscope 1
     - Time of flight in Hodoscope 2
     - Vector of energy deposits in EM calorimeter cells
     - Vector of energy deposits in Hadronic calorimeter cells

   The histograms and ntuple are saved in two output files in a default
   (Root) file format.

   Another file format (for example xml) can be selected either by
   changing the generic analysis manager default file type:
```
analysisManager->SetDefaultFileType("xml");
```
   or by providing the file names with the extension:
```
analysisManager->SetFileName("B5.xml");
analysisManager->SetNtupleFileName(0, "B5ntuple.xml");
```

   When running in multi-threading mode, the histograms and ntuple accumulated
   on threads are automatically merged in a single output file.

## PLOTTING:

  This example comes with a commented plotter.mac that shows how to use the
  plotting coming with some of the visualization drivers (for example the
  ToolsSG ones) to see the histograms. In it you will see how to activate
  the vis driver (create a "scene handler"), create a viewer, create a scene
  containing a plotter model object, create plotting "regions" (here 2x2
  regions) and attach the histograms to each region. When done, each
  run beamOn should display at end the content of the histograms.

  In the second part of plotter.mac, is shown various ways to customize the
  regions, for example changing the bins color, the axis labels fonts, etc...
  This could be done by using default embedded styles, defining styles with commands,
  or setting up directly parameters of the various parts of a plot by using a
  dedicated command.

  By default the fonts used are the Hershey vectorial ones that do not need
  an extra package, but you can use some freetype fonts if building with the
  cmake flag -DGEANT4_USE_FREETYPE=ON. Two embedded ttf fonts comes with the
  ToolsSG plotting: roboto_bold (some open source kind of the Microsoft arialbd)
  and lato_regular (close to an helvetica). You can use your own .ttf files by
  using the TOOLS_FONT_PATH environment variable to specify the directory where
  they could be found.

<hr>

The following paragraphs are common to all basic examples

## VISUALISATION

   The visualization manager is set via the G4VisExecutive class
   in the main () function in exampleB5.cc.
   The initialisation of the drawing is done via a set of /vis/ commands
   in the macro vis.mac. This macro is automatically read from
   the main function when the example is used in interactive running mode.

   By default, vis.mac opens the default viewer (/vis/open).
   This chooses a graphics system (in order of priority):
   - by argument in G4VisExecutive construction.
   - by environment variable, G4VIS_DEFAULT_DRIVER.
   - by information in ~/.g4session.
   - by mode (batch/interactive) and if interactive, by your build flags.

   The user can change the initial viewer
   - with environment variable G4VIS_DEFAULT_DRIVER. The format is
     ```
     <graphics-system> [<window-size-hint>]
     ```
     Set this, e.g:
     - (bash) export G4VIS_DEFAULT_DRIVER=TSG
     - (tcsh) setenv G4VIS_DEFAULT_DRIVER OI
       - The window-size-hint can optionally be added, e.g:
       - (bash) export G4VIS_DEFAULT_DRIVER="RayTracerQt 1000x1000-0+0"
   - on the command line, precede the app invocation, e.g:
     - ```
       G4VIS_DEFAULT_DRIVER=Vtk ./<application-name>
       ```
   - with ~/.g4session.

   For other suggestions for G4VIS_DEFAULT_DRIVER (see list of registered
   graphics systems printed at the start):
   - DAWNFILE: to create a .prim file suitable for viewing in DAWN.
   - VRML2FILE: to create a .wrl file suitable for viewing in a VRML viewer.
   - "TSG_OFFSCREEN 1200x1200": to create an image file with TSG.
     - See the tsg_offscreen.mac in examples/basic/B5 for more commands
       to change the file format, file name, picture size, etc.

   See "Choosing a graphics viewer" in the Application Guide for details.

   Of course you can change the viewer by editing the /vis/open line in vis.mac.

   Also, after the initial viewer opens, you may open a different viewer by typing
   on the command line, e.g:
```
/vis/open DAWNFILE
```
   or
```
/vis/open RayTraceQt
```
   (if you are using the Qt GUI).

   The view parameters of the existing viewer are copied.

   The DAWNFILE and similar drivers are always available
   (since they require no external libraries), but the OGL driver requires
   that the Geant4 libraries have been built with the OpenGL option.

   Since 11.1, the TSG visualization driver can also produce the "offscrean"
   file output in png, jpeg, gl2ps formats without drawing on the screen.
   It can be controlled via UI commands provided in '/vis/tsg' which are
   demonstrated in the tsg_offscreen.mac macro in example B5.

   For more information on visualization, including information on how to
   install and run DAWN, OpenGL and TSG see the visualization tutorials,
   for example,\n
   - <a href="http://geant4.slac.stanford.edu/Presentations/vis/G4OpenGLTutorial/G4OpenGLTutorial.html">
     OpenGL Tutorial </a>
   - <a href="http://geant4.slac.stanford.edu/Presentations/vis/G4DAWNTutorial/G4DAWNTutorial.html">
     DAWN Tutorial </a>

   The tracks are automatically drawn at the end of each event, accumulated
   for all events and erased at the beginning of the next run.

## USER INTERFACES

  The user command interface is set via the G4UIExecutive class
  in the main () function in exampleB5.cc

  The selection of the user command interface is then done automatically
  according to the Geant4 configuration or it can be done explicitly via
  the third argument of the G4UIExecutive constructor (see exampleB4a.cc).

  The gui.mac macros are provided in examples B2, B4 and B5. This macro
  is automatically executed if Geant4 is built with any GUI session.
  It is also possible to customise the icons menu bar which is
  demonstrated in the icons.mac macro in example B5.

## HOW TO RUN

   - Execute exampleB5 in the 'interactive mode' with visualization
```
% exampleB5
and type in the commands from run1.mac line by line:
Idle> /control/verbose 2
Idle> /tracking/verbose 1
Idle> /run/beamOn 10
Idle> ...
Idle> exit
```
      or
```
Idle> /control/execute run1.mac
....
Idle> exit
```

   - Execute exampleB5 in the 'batch' mode from macro files
   (without visualization)
```
% exampleB5 run2.mac
% exampleB5 exampleB5.in > exampleB5.out
```
