32.6. Exporting Geometry with GDML
Table of Contents
Why Export Geometry with GDML
Exporting your Geant4 geometry to GDML lets you save the detector description in a text-based, human readable, and tool independent format. Once exported, the same geometry can be reused in other Geant4 applications, shared with collaborators, archived for future versions of your code, or loaded into external tools that understand GDML.
In practice, exporting with GDML is especially helpful when geometry development is much more time consuming than running simulations. You can freeze a particular geometry configuration as a GDML file, then run many different physics or source configurations on the same geometry without recompiling or even without including the original C++ geometry code.
Important: GDML export only stores the geometry. It does not save physics lists, primary generators, user actions, or analysis code. You must still configure these parts of the simulation in C++ or macros.
Basic GDML Support in Geant4
Geant4 provides a dedicated class, G4GDMLParser, to read and write GDML files. This class is part of the GDML module that must be enabled when Geant4 is built. If you installed Geant4 from a precompiled package, GDML support is usually enabled by default. If you built Geant4 from source, you need to turn on the GDML option in CMake.
At the CMake configuration stage for Geant4 itself, GDML support is controlled with an option similar to:
cmake -DGEANT4_USE_GDML=ON ...or through the CMake GUI. When this option is enabled, the GDML headers and libraries become available to your application.
Inside your own Geant4 application, you access GDML through:
#include "G4GDMLParser.hh"
and you must link against Geant4 with GDML support. If you use find_package(Geant4 REQUIRED ...) in your CMakeLists.txt and have a properly built Geant4 with GDML, the linking is normally automatic. You do not need to add special libraries by hand.
If you see compilation errors that mention missing G4GDMLParser.hh, this usually means your Geant4 installation was built without GDML support. Rebuild Geant4 with GDML enabled or install a version that includes GDML.
Using G4GDMLParser to Export Geometry
The central operation for geometry export is calling G4GDMLParser::Write(). This function takes the name of the output file and the pointer to your world physical volume. Typically, you already have the world volume from your DetectorConstruction class.
A very common pattern is to export the geometry after it is fully constructed and before you start the main simulation run. One simple way is to use a small snippet in main() after you have created and initialized your detector:
#include "G4RunManagerFactory.hh"
#include "G4GDMLParser.hh"
#include "DetectorConstruction.hh"
#include "QGSP_BERT.hh"
int main(int argc, char** argv)
{
auto* runManager = G4RunManagerFactory::CreateRunManager();
auto* detConstruction = new DetectorConstruction();
runManager->SetUserInitialization(detConstruction);
runManager->SetUserInitialization(new QGSP_BERT);
runManager->Initialize();
// Access the world volume from the detector
G4VPhysicalVolume* worldPV = detConstruction->GetWorldPhysicalVolume();
G4GDMLParser parser;
parser.Write("geometry.gdml", worldPV);
// Continue with UI / batch control if desired
...
}
Your DetectorConstruction can provide a method like GetWorldPhysicalVolume() that returns the pointer to the world volume created in Construct().
Rule: Always pass the world physical volume to parser.Write(). Do not pass a daughter volume. GDML export needs the full volume hierarchy, starting from the world.
You are not restricted to exporting only once. You can call Write() multiple times, for example if you build different geometries depending on configuration parameters and want to save each variant.
Controlling Names and Structure in Exported GDML
When you export geometry, Geant4 maps your G4LogicalVolume, G4VPhysicalVolume, and G4VSolid objects to GDML volume, physvol, and solid entries. The names you have given in C++ become the names in the GDML file. This means your naming strategy in C++ has a direct effect on the clarity and usefulness of the exported file.
You usually assign names implicitly when you construct objects. For example:
auto* solidDetector = new G4Box("DetectorSolid", 5*cm, 5*cm, 1*cm);
auto* logicDetector = new G4LogicalVolume(solidDetector, material, "DetectorLV");
auto* physDetector = new G4PVPlacement(
0, G4ThreeVector(), logicDetector, "DetectorPV", logicWorld, false, 0, true);These names appear in the GDML file:
DetectorSolidas asolidentry.DetectorLVas avolume.DetectorPVas a physical placement.
If you leave names empty or reuse the same names for many different objects, the GDML file becomes harder to read and manipulate. For geometry that you plan to export, it is worth using short but descriptive names and keeping them consistent.
When writing GDML, you can optionally specify a schema location, which may be used by XML tools to validate the file:
parser.SetSchemaLocation("http://cern.ch/geant4/GDML/schema/gdml.xsd");
parser.Write("geometry.gdml", worldPV);If you do not set a schema location, Geant4 writes a default or leaves it empty depending on the version. For many Geant4 based uses, you do not need to worry about the schema, but external tools may find it useful.
Some applications may also want to control the level of detail or auxiliary information exported. The G4GDMLParser can manage auxiliary elements, discussed later, and can also be instructed to strip them if you only want a pure geometric description.
Material and Element Export
When you export a geometry, the parser writes not only solids, logical volumes, and placements, but also elements and materials. GDML materials are built from basic chemical elements with given fractions and densities, very similar to how you define them in C++.
If your geometry uses materials created with G4NistManager, the export still writes full material definitions into the GDML file, not just a name reference. This means that the GDML file is self contained from the point of view of geometry and materials. You can load it into another Geant4 application without needing to repeat the C++ material definitions.
Material related definitions appear in specific GDML sections:
elemententries with atomic number and mass.materialentries that combine elements and define density and state.
The export does not record all properties of Geant4 materials. For example, if you have added optical properties to a material using G4MaterialPropertiesTable, the handling of these properties through GDML may be limited or require auxiliary tags. For basic non optical simulations, the standard exported material definitions are usually sufficient.
If you use very complex material definitions or care about exact material properties in external tools, it is a good idea to open the GDML file and inspect the material section. Even though it is XML, you can still see densities, names, and element fractions as simple text.
Exporting Repeated and Complex Geometry
Many realistic detectors use repeated or parameterized volumes, such as arrays of crystals, segmentation into many slices, or voxelized phantoms. GDML can represent many of these patterns, and G4GDMLParser tries to export them in a natural way.
Replica volumes, parameterized volumes, and placements inside a regular structure may appear in GDML as repeated physvol entries or as structures that mimic replication. However, GDML does not have a direct counterpart for every possible C++ geometry construct, so the exported representation is sometimes more verbose than your C++ code.
From the point of view of export, you do not need to treat these special volumes differently. If they are part of the geometry reachable from the world volume, they will be written. However, for very large parameterized geometries, the GDML file can become extremely large, sometimes many megabytes or more. In those cases, geometric export is still possible, but editing the file by hand becomes impractical.
If you know you will export and share a geometry with many repeated elements, it can help to group volumes logically and maintain clear naming conventions for the repeated parts. This makes the GDML structure easier to interpret and to use in other tools that may want to identify individual segments or detector elements.
Auxiliary Information and Metadata
GDML allows the inclusion of auxiliary information associated with volumes or materials. Geant4 uses this mechanism through G4GDMLAuxStructType and related classes. Auxiliary tags are small pieces of metadata that can be attached to geometry objects and then exported and imported.
Typical uses include:
- Marking certain volumes as active detector regions.
- Attaching readout or digitization parameters.
- Storing visualization hints or grouping information for analysis.
To attach auxiliary information, you use the parser interface and the auxiliary store, for example:
#include "G4GDMLParser.hh"
#include "G4GDMLAuxStructType.hh"
...
G4GDMLAuxStructType aux;
aux.type = "DetectorType";
aux.value = "Scintillator";
parser.AddAuxiliary(aux, logicDetector);
When you call parser.Write(), this auxiliary entry is written into the GDML file and associated with the corresponding volume. A different Geant4 application can later parse the same file, read the auxiliary information using parser.GetAuxMap(), and make decisions based on this metadata.
Auxiliary information is optional and does not change the actual geometry. It is a useful way to keep detector related labels in the same file as the geometry instead of scattering them through separate configuration files.
Important: Auxiliary information exported in GDML is not used automatically by Geant4. Your application must explicitly read and interpret the auxiliary tags after geometry import.
Validating the Exported GDML
After writing a GDML file, you should verify that it correctly represents your original geometry. There are several simple checks you can perform.
First, open the GDML file in a text editor. Verify that the file is not truncated, that it begins with a valid XML declaration, and that the number of defined volumes and materials seems reasonable. For small or medium geometries, you can quickly see if the overall structure matches your expectations.
Second, try to load the GDML file in a clean Geant4 test application. You can write a dedicated program that uses G4GDMLParser::Read() to build the geometry from the file, then use visualization to inspect the result:
#include "G4RunManagerFactory.hh"
#include "G4GDMLParser.hh"
#include "G4VUserDetectorConstruction.hh"
class GDMLDetectorConstruction : public G4VUserDetectorConstruction {
public:
GDMLDetectorConstruction(const G4String& gdmlFile)
: fGDMLFile(gdmlFile) {}
G4VPhysicalVolume* Construct() override {
G4GDMLParser parser;
parser.Read(fGDMLFile);
return parser.GetWorldVolume();
}
private:
G4String fGDMLFile;
};
int main() {
auto* runManager = G4RunManagerFactory::CreateRunManager();
runManager->SetUserInitialization(new GDMLDetectorConstruction("geometry.gdml"));
...
}Once loaded, you can use the usual visualization commands to display volumes and check for missing parts or obvious problems.
Third, run the geometry overlap checker on the imported geometry to ensure that the exported placements did not create overlaps or other inconsistencies. Overlap issues are more often caused by the original C++ geometry rather than the export itself, but it is still useful to confirm that the GDML based geometry behaves identically.
For very complex or large geometries, the GDML file can be validated against the GDML XML schema using external XML validation tools. This can help to detect structural format errors if the file was edited by hand or generated by nonstandard scripts.
Practical Tips for Using GDML Export
For everyday simulation work, it is helpful to follow a few practical rules when working with GDML export.
First, decide early whether a particular detector or geometry is intended to be shared or reused. If so, invest in clear volume and material naming instead of leaving names empty or auto generated. These names make the exported GDML much easier to understand.
Second, keep the geometry construction and export logic separate from physics and analysis code. For example, provide a macro command or a simple option such as a command line flag to trigger geometry export. This lets you rebuild and export geometry on demand without modifying the core simulation code every time.
Third, be aware of file size. Simple detectors produce small GDML files that are easy to share by email or version control. Large segmented or voxelized detectors can produce GDML files that are too big for casual sharing. In such cases, consider whether GDML is the right export format or whether a more compact parametrization in C++ is preferable for long term storage.
Fourth, remember that GDML only describes geometry and materials. When you share a GDML file, also document which physics list, primary particles, and user actions were used in the original simulation, so that others can reproduce your results more accurately.
Finally, treat exported GDML files as part of your simulation configuration. You can track them in version control alongside your C++ source, tag them with simulation versions, and include them in your documentation so that each set of analysis results can be associated with a specific stored geometry snapshot.
Views: 9
KAHIBARO