User Guide

This guide describes how to build a geometry with Geom4hep.jl and how to navigate it. The concepts are those of the Geant4 geometry (solids, logical volumes and placements); the Geometry chapter of the Geant4 Application Developer Guide describes them in more detail. The Examples show all of this running, with their output.

Floating point type and units

All the types are parametric on the floating point type T, Float64 or Float32, which is given explicitly when creating objects: Box{Float32}(1, 2, 3). The parameters are converted to T. A geometry must use a single type; read_gdml takes it as an argument.

Float32 is needed on most GPUs (Apple GPUs do not support Float64). With Float32, the surfaces are thicker (tolerance is 1 µm instead of 1 nm), so that rounding errors do not let a ray cross a surface without seeing it.

Lengths are in mm and angles in radians. The module Geom4hep.Units defines units with the Geant4 conventions:

using Geom4hep, Geom4hep.Units
box  = Box{Float64}(1cm, 2cm, 3cm)          # half lengths 10, 20 and 30 mm
tube = Tube{Float64}(0, 5cm, 1m, 0, 90deg)  # a quarter of a cylinder

For the materials, energies are in MeV (eV, keV, MeV, GeV), temperatures in kelvin and pressures in pascal, bar or atmosphere, as in Geant4. Masses are in mg, so that densities are in g/cm³ (7.874g/cm3 == 7.874) and molar masses in mg/mole (55.845g/mole). The module also has the physical constants used for the materials (Avogadro, amu, fine_structure_const, classic_electr_radius, STP_Pressure, NTP_Temperature, ...), with the values of CLHEP.

Points, vectors and transformations

Point3 is a position and Vector3 a displacement or a direction. Both are static vectors (from StaticArrays.jl), so they support indexing, broadcasting, dot, cross, norm, ... The difference of two points is a vector, and a point plus a vector is a point. Directions given to the shape functions must be unit vectors.

p = Point3{Float64}(1, 2, 3)
d = normalize(Vector3{Float64}(1, 1, 0))     # using LinearAlgebra
q = p + 10 * d                               # a Point3

A Transformation3D places a daughter volume in its mother (or the right operand of a boolean shape in the frame of the left one). Applied to a point of the mother frame, it gives the point in the frame of the daughter: t * p is R * (p - t) for a translation t and rotation R. Transformation3D{T}(x, y, z) therefore places the daughter at (x, y, z). Rotations come from Rotations.jl:

t1 = Transformation3D{Float64}(10, 0, 0)                          # translation
t2 = Transformation3D{Float64}(0, 0, 50, RotXYZ{Float64}(0, 0, π/4)) # rotation and translation
t3 = Transformation3D{Float64}(0, 0, 0, π/2, 0, 0)               # RotXYZ angles
p * t1      # inverse transformation: from the daughter frame to the mother frame
t1 * t2     # composition

Note the convention, the same as Geant4 and VecGeom use internally: the rotation R rotates points of the mother frame into the daughter frame, so the daughter appears rotated by the inverse of R.

Shapes

A shape (solid) is defined in its own frame, usually centred at the origin. The parameters are the same as those of the corresponding Geant4 solid (half lengths, radii, and ϕ and θ ranges with a start angle and an extent).

Supported shapes

The Geant4 solids and their status in Geom4hep (✅ supported, ❌ not yet supported):

Geant4 solidGeom4hepGDML elementNotes
G4Box✅ Boxbox
G4Tubs✅ Tubetube
G4CutTubs✅ CutTubecutTube
G4Cons✅ Conecone
G4Trd✅ Trdtrd
G4Trap✅ Traptrap
G4Sphere✅ Spherespherewith ϕ and θ segments
G4Orb✅ Sphereorbas a full Sphere
G4Torus✅ Torustorus
G4Polycone✅ Polyconepolyconez-planes form only
G4Polyhedra✅ Polyhedrapolyhedraz-planes form only
G4UnionSolid, G4SubtractionSolid, G4IntersectionSolid✅ BooleanUnion, BooleanSubtraction, BooleanIntersectionunion, subtraction, intersectionsafeties are conservative (0) in the flat model
G4MultiUnion✅ MultiUnion❌ multiUnionno acceleration structure over the components
G4Para✅ Paraparabuilt as a Trap
G4GenericTrap✅ GenericTraparb8built as a Tessellated shape; twisted faces approximated by slices (exact volume)
G4ExtrudedSolid✅ ExtrudedSolidxtrubuilt as a Tessellated shape (exact)
G4TessellatedSolid✅ Tessellatedtessellatedclosed surface of planar facets, convex or not; no acceleration structure over the facets
G4Tet✅ Tettetbuilt as a Tessellated shape
G4GenericPolycone❌genericPolycone
G4EllipticalTube✅ EllipticalTubeeltube
G4EllipticalCone❌elcone
G4Ellipsoid✅ Ellipsoidellipsoidwith z cuts
G4Paraboloid❌paraboloid
G4Hype❌hype
G4TwistedBox, G4TwistedTrd, G4TwistedTrap, G4TwistedTubs❌twistedbox, ...
G4ScaledSolid❌scaledSolid
G4ReflectedSolid❌reflectedSolid

The constructors:

T = Float64
Box{T}(x, y, z)                                   # half lengths
Tube{T}(rmin, rmax, z, ϕ₀, Δϕ)                    # z is the half length
Cone{T}(rmin1, rmax1, rmin2, rmax2, z, ϕ₀, Δϕ)    # radii at -z and +z
CutTube{T}(rmin, rmax, z, ϕ₀, Δϕ, bottom_normal, top_normal)
Trd{T}(x1, x2, y1, y2, z)                         # half lengths at -z and +z
Trap{T}(z, θ, ϕ, y1, x1, x2, α1, y2, x3, x4, α2)  # as G4Trap
Sphere{T}(rmin, rmax, ϕ₀, Δϕ, θ₀, Δθ)
EllipticalTube{T}(dx, dy, dz)                     # semi-axes and half length
Ellipsoid{T}(ax, by, cz, zbottom, ztop)           # semi-axes and z cuts (0 and 0: no cut)
Torus{T}(rmin, rmax, rtor, ϕ₀, Δϕ)
Polycone{T}(rmin, rmax, z, ϕ₀, Δϕ)                # vectors of radii at the z planes
Polyhedra{T}(nsides, rmin, rmax, z, ϕ₀, Δϕ)       # radii to the sides (apothems)
Para{T}(x, y, z, α, θ, ϕ)                         # as G4Para (a Trap)
Tessellated{T}(vertices, faces)                   # closed surface of triangles or quadrilaterals
ExtrudedSolid{T}(polygon, sections)               # polygon [(x, y), ...], sections [(z, (x0, y0), scale), ...]
ExtrudedSolid{T}(polygon, z, off1, scale1, off2, scale2)
GenericTrap{T}(z, vertices)                       # 8 (x, y) vertices, 4 at -z and 4 at +z
Tet{T}(a, b, c, d)                                # the 4 vertices

Para, ExtrudedSolid, GenericTrap and Tet have the names of the Geant4 solids, but their constructors return a Trap or a Tessellated shape.

Shape functions

Every shape implements the functions that a particle transport needs. The points and directions are in the frame of the shape:

FunctionResult
inside(shape, p)kInside, kSurface or kOutside
distance_to_in(shape, p, d)distance along d from an outside point to the shape (Inf if it misses it)
distance_to_out(shape, p, d)distance along d from an inside point to the surface
safety_to_in(shape, p)lower bound of the distance from an outside point to the shape
safety_to_out(shape, p)lower bound of the distance from an inside point to the surface
normal(shape, p)outward unit normal at a point of the surface
extent(shape)(lower, upper) corners of a bounding box
capacity(shape), surface(shape)volume and surface area

The surfaces have a thickness: a point closer than tolerance(T)/2 to a surface is on it. A point on the surface moving into the shape gets distance_to_in == 0, and moving out of it distance_to_out == 0, so that a navigator that stops on a surface does not get stuck there. The safeties are cheaper than the exact distances: they are used to take steps in all directions (e.g. for multiple scattering) without computing intersections.

Boolean shapes

BooleanUnion, BooleanSubtraction and BooleanIntersection combine two shapes; the right one is placed in the frame of the left one. They can be nested:

box  = Box{T}(10, 10, 10)
hole = Tube{T}(0, 5, 20, 0, 2π)
s1 = BooleanSubtraction(box, hole)                                        # a box with a hole along z
s2 = BooleanUnion(s1, Sphere{T}(0, 5), Transformation3D{T}(0, 0, 10))     # and a dome on top

A MultiUnion is the union of any number of placed shapes:

mu = MultiUnion{T}()
for i in 1:10
    add_component!(mu, Box{T}(1, 1, 1), Transformation3D{T}(3i, 0, 0))
end

Materials

Materials follow the Geant4 model: an Isotope (G4Isotope) has an atomic number, a number of nucleons and a molar mass; an Element (G4Element) is a mixture of isotopes; a Material (G4Material) is made of elements, with a density, a state, a temperature and a pressure. The NIST data of Geant4 give the elements with their natural isotopic composition (nist_element), and the materials G4_<symbol> of all the elements and a selection of compounds and HEP materials (nist_material, nist_material_names):

using Geom4hep.Units
water = nist_material(T, "G4_WATER")
lead  = nist_material(T, "G4_Pb")
Fe    = nist_element(T, "Fe")

New materials are made as in Geant4: of a single element, of elements given by their number of atoms in a molecule (a compound), or of elements and materials given by mass fractions (a mixture):

H, O, N, Ar = (nist_element(T, s) for s in ("H", "O", "N", "Ar"))
silicon = Material{T}("Silicon", 14, 28.0855g/mole, 2.33g/cm3)
water   = Material{T}("Water", 1.0g/cm3; atoms=[H => 2, O => 1], state=:liquid, I=78eV)
air     = Material{T}("Air", 1.205mg/cm3; fractions=[N => 0.7553, O => 0.2318, Ar => 0.0129], state=:gas)
mixture = Material{T}("WaterLead", 6.0g/cm3; fractions=[water => 0.5, lead => 0.5])
iron    = Element{T}("Iron", "Fe", 26, 55.845g/mole)             # with the natural isotopes

The derived quantities are computed as in Geant4: radiation_length (Tsai's formula), nuclear_interaction_length, electron_density, mean_excitation_energy (from the NIST data, from GDML, or from the elements), mass_fractions and atoms_per_volume:

radiation_length(lead) / cm                # 0.5613
nuclear_interaction_length(water) / cm     # 75.37
mean_excitation_energy(water) / eV         # 78.0

A material can also be given by its density only, Material{T}("iron"; density=7.874), which is enough for the navigation and the mass thickness of xray; its radiation and interaction lengths are then unknown (NaN).

Volumes and placements

A Volume (Geant4's logical volume) is a shape filled with a material. Daughter volumes are placed in it with place_daughter! (Geant4's physical volume placement), which records a PlacedVolume with the transformation. The same volume can be placed many times, in the same or in different mothers. The daughters must be inside the mother and must not overlap each other; this is not checked.

world  = Volume{T}("world", Box{T}(1000, 1000, 1000), Material{T}("air"; density=0.0012))
layer = Volume{T}("module", Box{T}(100, 100, 10), Material{T}("iron"; density=7.87))
for i in -2:2
    place_daughter!(world, Transformation3D{T}(0, 0, 100i), layer)
end
world[3]          # the volume of the 3rd daughter

An Assembly groups volumes without a mother shape: placing an assembly places each of its volumes. world_volume returns a world volume that contains a given volume.

GDML

read_gdml(file, T) reads a GDML file, the geometry exchange format of Geant4 and ROOT, and returns its world volume:

world = read_gdml("cms2018.gdml", Float32)

The materials, the shapes in the table of supported shapes, the booleans, the volumes, the physical volumes and the assemblies are read, with the units of the file converted to mm and radians. Solids that are not supported are replaced by NoShape with a warning, and the booleans with such an operand are reduced to their valid operand (the first of a subtraction, or either one of a union), or are empty.

The numeric attributes can be expressions, as in Geant4: numbers, the <constant>, <variable>, <quantity> and <expression> of the <define> section, the units (2*cm), pi, the arithmetic operators and the usual math functions (e.g. deltaphi="2*(HALFPI+0.2*pi)"). The attributes that are missing are 0, as in Geant4 (e.g. a <position> with only x). The <loop> and <matrix> elements are not supported.

The materials are read as by Geant4: isotopes, elements (by Z and molar mass, or by isotopes), materials of a single element, compounds (<composite>), mixtures of elements and materials (<fraction>), with their density, state, temperature, pressure and mean excitation energy (<MEE>), in the units of the file. Elements and materials that are referenced but not defined in the file are taken from the NIST data (e.g. G4_AIR or Fe).

Geometry model and navigation

Closing the geometry

The hierarchy of volumes is convenient to build a geometry, but not to navigate it: its objects have different types, are referenced by pointers and cannot be moved to a GPU. close_geometry converts it to a GeometryModel:

  • all the data is in arrays of plain (isbits) structures, referenced by indices: the model can be moved to a GPU with Adapt.adapt;
  • the shapes are stored by type, and a shape function is called with shape_call through a generated if chain over the types instead of dynamic dispatch;
  • boolean shapes, of any nesting, become flat CSG programs over primitive shapes, and long chains of unions become multi-unions;
  • the daughters of volumes with many daughters are organized in a bounding volume hierarchy (BVH).
model = close_geometry(world)
model, index = close_geometry(world; with_index=true)   # index.volumes[i] is the Volume of volume i

A NavState is the position of a point in the hierarchy: the path of placements from the world to the current volume, and the transformation from the global frame to the frame of the current volume. It is immutable, so it can be kept in registers on a GPU.

function track_length(model, point, dir)
    state = locate(model, point)
    length = zero(eltype(point))
    while in_world(state)
        step, state = compute_step(model, state, point, dir, typemax(eltype(point)))
        point += step * dir
        length += step
    end
    return length
end

After crossing a boundary, the new state is computed for the point pushed by push_tolerance beyond it. Like Geant4, the navigator remembers the daughter that a step has just left ("blocked" volume), to avoid re-entering it immediately because of rounding errors.

GPUs

The navigator functions are plain Julia functions on isbits data, so they can be called from GPU kernels. KernelAbstractions.jl gives kernels that run on any GPU. xray is an example: it computes an X-ray image of a geometry (the mass thickness along parallel rays, or the material budget in radiation or interaction lengths with quantity=:radlen or :nuclen) on the CPU (with Julia threads) or on a GPU:

world = read_gdml("cms2018.gdml", Float32)
model = close_geometry(world)
u, v, image, nsteps = xray(model, 3, 1000)                                  # CPU
using Metal
u, v, image, nsteps = xray(model, 3, 1000; backend=MetalBackend())          # Apple GPU

Some GPU compilers (Apple's in particular) inline all the function calls of a kernel: the size of a kernel grows with the number of shape types of the model and with the number of call sites of the shape functions. This is why the model dispatches without recursion and the CSG programs are flat.

Visualization

The drawing functions need a Makie backend (GLMakie for interactive windows, CairoMakie for images). draw creates a figure with a shape or a volume hierarchy, and draw! adds it to an existing LScene:

using GLMakie: GLMakie, Figure, LScene
draw(Torus{Float64}(1, 2, 10, 0, 3π/2))
fig = Figure(); scene = LScene(fig[1, 1])
draw!(scene, world; wireframe=true, maxlevel=3)

The volumes are colored by the dominant element of their material (the element with the largest mass fraction: iron in red, copper in blue, silicon in yellow, ...), and the volumes of gases and vacuum (below 0.25 g/cm³) are not drawn; colorby=:level draws all the volumes with grey levels by depth instead. The world volume itself is not drawn. Before drawing, the meshes of all the volumes are merged into a single mesh with the colors at the vertices (each volume is meshed once, whatever its number of placements): Makie draws large geometries, such as CMS, with a single plot, and CairoMakie, which has no depth buffer, sorts all their triangles by depth. Other keyword arguments go to Makie, e.g. color=(:steelblue, 0.4) for a single transparent color.

clip=:xy (or :x, :y, :z, :xz, :yz, :xyz) cuts away the region with positive coordinates along these axes, to see the inside of a geometry: the volumes that cross the region are drawn as their subtraction with a large box, computed with csg_mesh.

Makie exports some names that are also Geom4hep shapes (Box, Sphere, ...): import only the Makie names you need, as above, or qualify the shapes (Geom4hep.Box).

mesh(shape) returns a GeometryBasics.Mesh of the surface of a shape, for other visualization or export tools. shape_to_mesh(shape) returns a mesh of triangles oriented outwards with normals at the vertices, smooth on the curved surfaces and sharp at the edges, which is the one that draw uses.

Benchmarks

benchmark_shape times the shape functions of a shape with the methodology of the VecGeom shape benchmarks: the shape in a world box, points sampled in the box (half of them inside the shape) and rays of which 80% hit the shape. vecgeom_suite has the setups of the VecGeom benchmark programs for the shapes of Geom4hep. The script examples/Benchmarks.jl runs the suite and, given a VecGeom build, runs the VecGeom programs with the same setups and compares the times:

julia --project=examples examples/Benchmarks.jl --vecgeom <vecgeom-build>/test/benchmark Polycone