KAHIBARO
Discord Login Register

35.9. Run the Simulation

Preparing to Run

Running the final project simulation is not just calling a single command. You prepare the build, choose how you will control the simulation, select input parameters, and decide how long to run. This section focuses on the practical steps and habits that let you run your finished application reliably and repeatably, without changing the physics, geometry, or analysis you already implemented.

You should already have a compiled Geant4 application that includes your final project geometry, physics list, particle source, sensitive detectors, and analysis. Here, you will see how to execute it, control it with macros, manage multiple runs, and organize large-scale production.

Building and Rebuilding Before a Run

Before running, always make sure the executable you use actually reflects your latest source code. In an out-of-source build, you typically have a build directory that contains compiled objects and the executable. Whenever you modify C++ source or headers, rerun the build step before running new simulations.

A common workflow on Linux is to enter the build directory, invoke CMake configuration if needed, and then compile. After compilation, the executable in the build directory is the one you will run. If you change only macro files, there is no need to rebuild. The executable loads macros at runtime, so editing a macro does not require recompilation.

For nontrivial simulations, it is useful to define a convention where the build directory is dedicated to a given version of your project. When you perform big refactors in geometry or physics, consider cleaning the build (for example by deleting cached build files) and rebuilding completely, to avoid problems from stale objects.

Interactive Versus Batch Execution

Your finished application can usually be run in two distinct modes. In interactive mode, you launch a session where you can type Geant4 commands or load macros incrementally. In batch mode, you provide one or more macro files at the command line and let the simulation run with no further user interaction.

For exploratory work and debugging, interactive mode is very useful. You can display your geometry, visualize tracks, change source parameters, or adjust cuts between runs without restarting the program. For production and for the final project deliverable, batch mode is usually preferable, because it is reproducible, scriptable, and easier to document.

Choose one mode as your primary mode for the final project report, and make sure all important results can be reproduced from a clean environment with a single command that runs in batch. You can still rely on interactive sessions to debug and to understand the detector response.

Using Macro Files to Control Runs

In a mature Geant4 application, almost everything you want to change between runs is configured through macro files, not hard coded in C++. For the final project, you should already have macros that configure your geometry options, beam or source parameters, physics list options if they are exposed, production cuts, visualization settings, and analysis output.

A typical top-level macro for a production run will initialize the run manager, configure your detector and physics, set up the primary source, and then call the run commands. It is useful to separate concerns. For example, use one macro for global initialization and visualization, another that defines the source, and a small macro that only sets the number of events and starts the run. You can then combine these via /control/execute commands so that a single batch macro fully defines the conditions of the run.

A macro that produces physics results must contain all settings that affect the outcome, including geometry options, physics configuration, source definition, cuts, and analysis configuration. Do not rely on defaults set by a previous interactive session, or you will not be able to reproduce your results.

For the final project, store all macros in a dedicated directory and name them systematically so that their purpose and configuration are clear when you later document or re-run the simulation.

Initializing and Starting a Run

Before you can simulate any events, the run manager must be initialized. This is usually done with a run macro that calls /run/initialize after your user initialization classes are registered in C++ and after any configuration commands that affect the geometry or physics have been issued.

Once the run manager is initialized, you can start a run by using the beam-on command. The standard sequence is:

  1. Initialize the run manager via /run/initialize.
  2. Optionally reinitialize geometry or physics if you have changed related settings.
  3. Configure your primary particle source and any other run-level parameters.
  4. Start the run with /run/beamOn N, where $N$ is the number of primary events.

You can repeat the beam-on command multiple times within the same session. Each call creates a new run as seen by your RunAction, with its own run ID and its own beginning and end-of-run hooks. Make sure your analysis code and output file handling are consistent with this behavior. Either open the analysis output once for all runs, or close and re-open files explicitly if you use separate output per run.

Always call /run/initialize after any command that changes geometry or physics configuration and before /run/beamOn. Failing to reinitialize after a configuration change can silently lead to inconsistent or incorrect simulations.

When you design your macros, make sure that initialization occurs at the correct point and is not hidden in an earlier macro that might or might not have been executed.

Choosing the Number of Events

The number of events you simulate controls both the statistical precision and the computational cost of your final project. For first tests of your setup, use a small number of events to check correctness. Once the setup is stable, increase the event count until your key observables have sufficiently small statistical uncertainties.

A simple rule of thumb is that the relative statistical uncertainty in a count $N$ behaves like $1/\sqrt{N}$. If you want an uncertainty of about 1 percent, you need on the order of $10^4$ effective counts in the relevant detector or bin. Depending on your source and geometry, this may require far more simulated primary events. For spectra or multi-dimensional distributions, each histogram bin has its own statistics, so you often need more events than you might first expect.

For the final project you should:

  1. Perform quick test runs with a very small number of events to check that output files are created, histograms are filled, and no warnings or geometry overlaps occur.
  2. Run intermediate-size jobs to inspect spectra and distributions visually and confirm that your setup behaves qualitatively as expected.
  3. Decide on a final event count based on the desired precision of the quantity you will present in your report, such as a peak position, efficiency, or depth-dose curve.

Document the final number of events you use for production, and keep the exact value in your macro instead of in the command line history.

Organizing Multiple Runs and Parameter Scans

For a final project, you will often need to compare configurations. You might vary a material, thickness, detector position, source energy, or any other parameter. Doing this manually through an interactive session is error prone and hard to reproduce. Instead, organize your runs as a set of batch macros, each encoding a specific configuration.

One common approach is to create a macro template with comments indicating where a parameter value appears. You then copy the template for each configuration and modify only the parameter values, such as shield thickness, beam energy, or geometry option flags. Your output file names should reflect the configuration, for example by embedding the parameter value in the path or filename.

If you run many configurations, integrate the Geant4 executable into external scripts. Shell scripts, Python scripts, or simple batch systems can loop over parameter values, construct command lines that call the executable in batch mode with a selected macro, and store outputs in an organized directory structure. This approach keeps your Geant4 code unchanged while you explore many scenarios.

For the final project, aim to have a clear mapping from configuration to macro to output file so that later analysis and figures can be traced back unambiguously.

Managing Output Files and Data Integrity

Your analysis system should already be set up to produce output files in a format suited to your downstream tools, such as ROOT or CSV. When running the full simulation, you must ensure that each run produces valid, closed files that can be read without errors.

Two points are especially important:

First, confirm that your analysis manager opens the output file before the run begins and writes and closes it at the end of the run or at the end of the job. If you rely on RunAction hooks, check that you do not accidentally close the file too early when you run multiple beam-on commands in one process. Decide whether you want one file per run or one file per job, and implement your analysis and macros accordingly.

Second, ensure that output filenames do not silently overwrite previous results. For the final project, choose file names that encode the main configuration and, if necessary, a time stamp or run number. If you perform test runs and final runs, store them in separate directories, for example "test" and "production", to avoid confusion.

Always verify that the analysis file is properly closed before you inspect or use it. Incomplete files can appear to exist but contain truncated or corrupted data. Closing the file explicitly at the end of the job protects against this problem.

Before committing to long runs, perform a small run, then immediately open the output with your analysis tool to check that histograms, ntuples, and metadata look correct.

Monitoring Progress and Performance

Long runs can take minutes to hours, depending on your physics and event count. To avoid wasting time, monitor progress and performance as you run. Geant4 provides basic run statistics and timing, and you can complement these with operating system tools.

During execution, look for the messages that indicate how many events have been processed and how long the run has taken. For multithreaded jobs, be aware that output from different threads can interleave. It is helpful to reduce unnecessary verbose output once the simulation is stable, so that performance messages remain readable.

If you find that performance is inadequate for the chosen event count, consider whether you can simplify the geometry for the specific observable you need, relax some physics options that are not important for your final quantity, or adjust production cuts appropriately. However, do not change physics or geometry solely for speed without checking the impact on your results, because such changes can invalidate your validation work.

For the final project, record approximate run times for your main production runs. Including these in your report helps show that you understand the computational cost of your simulation and have chosen reasonable parameters.

Ensuring Reproducibility of Runs

A core requirement of a good final project is that you, and someone else, can reproduce your results later. This involves making sure that your random number settings, macros, and executable version are all controlled.

For random numbers, use an explicit seed strategy. Either set a fixed seed for runs whose results you want to reproduce exactly, or document any variable seeding scheme. Store the seed or a random state tag in your output or run log so that a particular run can be rerun identically if needed.

Couple this with a strict habit that any production run used in the final project is performed using a committed version of your code and macros. Do not change macros, geometry, or physics midway through a production sequence without versioning those changes. If you must modify the setup, clearly separate results obtained with the old configuration from those with the new one.

A reproducible run requires:

  1. A fixed code version.
  2. A complete set of macros for configuration.
  3. A known random seed or seeding method.
    Changing any of these without recording the change means the run cannot be faithfully reproduced.

For your final submission, keep a small text file in the project directory that lists the executable build date or version, the main macros used for production, the event counts, and any seeds for key runs. This serves as a concise run log.

Running on Multicore and External Systems

If you have configured your application to support multithreading, you can speed up the simulation by using several CPU cores. Use the appropriate Geant4 commands or command-line options to set the number of threads before the run begins. For the final project, test the simulation with multiple threads on a small number of events first, to verify that your user code and analysis remain thread safe.

If you have access to a computing cluster or batch system, you can run many independent Geant4 jobs in parallel. Each job should have its own macro and output path and, ideally, a distinct random seed. At the end, you merge the output files during analysis. Make sure that your macros and scripts do not cause two jobs to write to the same output file.

Even if you run only on a laptop, learn and apply the same discipline. Use organized directories for runs, separate test and production data, and keep batch macros under version control.

Final Checks Before Production Runs

Before launching your final, long production runs for the project, perform a short checklist:

Confirm that the geometry visualizes correctly with a small test run, and that any overlaps have been checked earlier. Verify that the physics list is the one you intend and that any cuts and special options are set by the macros you will use in production. Check that the primary source matches the physical scenario you want to model in the final project.

Run a small number of events with the exact production macro, then inspect the output file with your analysis tool to confirm that all quantities you plan to use in your report are present and have reasonable shapes and values. If all tests are satisfied, keep the production macro and code unchanged, launch the full run, and record in your run log the date, macro name, event count, and any seed information.

By following this structured approach to running your simulation, you make your final project robust, traceable, and scientifically credible.

Views: 9

Comments

Please login to add a comment.

Don't have an account? Register now!