pyg4ometry.visualisation

Submodules

Attributes

Classes

Mesh

OverlapType

ViewerBase

Base class for all viewers and exporters. Handles unique meshes and their instances

VisualisationOptions

Basic holder for visualisation parameters, i.e. colour and opacity.

VtkViewer

Visualiser.

VtkViewerColoured

Visualiser that extends VtkViewer. Uses "flat" interpolation and introduces control over colours.

VtkViewerColouredMaterial

Extension of VtkViewerColoured that uses a default material dictionary for

MouseInteractorNamePhysicalVolume

_VisOptions

Basic holder for visualisation parameters, i.e. colour and opacity.

VtkViewerNew

VtkViewerColouredNew

Visualiser that extends VtkViewer. Uses "flat" interpolation and introduces control over colours.

VtkViewerColouredMaterialNew

Extension of VtkViewerColoured that uses a default material dictionary for

MouseInteractorNamePhysicalVolume

BlenderViewer

RenderWriter

VtkExporter

Functions

_getBoundingBox(aMesh[, rotationMatrix, translation, ...])

Axes aligned bounding box. Can also provide a rotation and

_getBoundingBoxMesh(boundingBox)

randomColour()

Return random RGB tuple

hexRGBToRGBTriplet(value)

loadPredefined()

Construct a ColorMap initialised with default colours for various materials.

getPredefinedMaterialVisOptions()

makeVisualisationOptionsDictFromPredefined(ColourMap)

_getPredefinedMaterialVisOptions()

axesFromExtents(extent)

viewLogicalVolumeDifference(referenceLV, otherLV[, ...])

_getPredefinedMaterialVisOptions()

mkVtkIdList(it)

pycsgMeshToVtkPolyData(mesh)

vtkPolyDataToNumpy(data)

pycsgMeshToObj(mesh, fileName)

pyg42VtkTransformation(mtra, tra)

vtkTransformation2PyG4(vt)

pycsgMeshToStl(mesh, fileName)

Package Contents

class pyg4ometry.visualisation.Mesh(solid)
parameters = []
values
solid
localmesh
localboundingmesh
overlapmeshes = []
remesh()
addOverlapMesh(mesh)
getLocalMesh()
getBoundingBox(rotationMatrix=None, translation=None)

Axes aligned bounding box. Can also provide a rotation and a translation (applied in that order) to the vertices.

getBoundingBoxMesh()
class pyg4ometry.visualisation.OverlapType
protrusion = 1
overlap = 2
coplanar = 3
pyg4ometry.visualisation._getBoundingBox(aMesh, rotationMatrix=None, translation=None, nameForError='')

Axes aligned bounding box. Can also provide a rotation and a translation (applied in that order) to the vertices.

pyg4ometry.visualisation._getBoundingBoxMesh(boundingBox)
class pyg4ometry.visualisation.ViewerBase

Base class for all viewers and exporters. Handles unique meshes and their instances

bSubtractDaughters = False
defaultVisOptions = None
defaultOverlapVisOptions = None
defaultCoplanarVisOptions = None
defaultProtusionVisOptions = None
materialVisOptions
materialPbrOptions
clear()
setSubtractDaughters(subtractDaughters=True)
addLogicalVolume(lv, mtra=_np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), tra=_np.array([0, 0, 0]), visOptions=_VisOptions(representation='wireframe'), depth=0, name=None)

Add a logical volume to viewer (recursively)

Parameters:
  • mtra (matrix(3,3)) – Transformation matrix for logical volume

  • tra (array(3)) – Displacement for logical volume

  • visOptions (VisualisationOptions) – VisualisationOptions for the lv mesh

addFlukaRegions(fluka_registry, max_region=1000000, debugIO=False)
addMesh(name, mesh)

Add a single mesh

Parameters:
  • name (str) – Name of mesh (e.g logical volume name)

  • mesh (CSG) – Mesh to be added

addInstance(name, transformation, translation, instanceName='')

Add a new instance for mesh with name

Parameters:
  • name (str) – name of mesh to add instance

  • transformation (array(3,3)) – Transformation matrix for instance

  • translation (array(3)) – Translation for instance

  • instanceName (str) – Name of the instance e.g PV

addVisOptions(name, visOption)

Add vis options to mesh with name

Parameters:
addPbrOptions(name, pbrOption)

Add pbr options to mesh with name

Parameters:
  • name (str) – name of mesh

  • pbrOptions (PbrOptions)

addMaterialVisOption(materialName, visOption)

Append a visualisation option instance to the dictionary of materials.

Parameters:
addMaterialPbrOption(materialName, visOption)

Append a visualisation option instance to the dictionary of materials.

Parameters:
setDefaultVisOptions(visOption)
getDefaultVisOptions()
getMaterialVisOptions(material)
setOverlapVisOption(visOption)
setCoplanarVisOption(visOption)
setProtusionVisOption(visOption)
getOverlapVisOptions(overlaptype)
removeInvisible()

Remove wireframe or transparent instances from self

scaleScene(scaleFactor)
exportGLTFScene(gltfFileName='test.gltf', singleInstance=False)

Export entire scene as gltf file, filename extension dictates binary (glb) or readable json (gltf) singleInstance is a Boolean flag to supress all but one instance

exportGLTFAssets(gltfFileName='test.gltf')

Export all the assets (meshes) without all the instances. The position of the asset is the position of the first instance

exportThreeJSScene(fileNameBase='test', lightBoxHDR='concrete_tunnel_02_4k.hdr')

html based on https://threejs.org/examples/#webgl_loader_gltf HRDI https://polyhaven.com/a/concrete_tunnel_02

npm install node wget https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/4k/concrete_tunnel_02_4k.exr conver EXR to HDR e.g. https://convertio.co/exr-hdr/ python -m http.server 8000 open test.html

dumpMeshQuality()
__repr__()
pyg4ometry.visualisation._predefinedMaterialVisOptions = None
pyg4ometry.visualisation.randomColour()

Return random RGB tuple

pyg4ometry.visualisation.hexRGBToRGBTriplet(value)
class pyg4ometry.visualisation.VisualisationOptions(representation='surface', colour=[0.5, 0.5, 0.5], alpha=0.5, visible=True, lineWidth=1, randomColour=False, depth=0)

Basic holder for visualisation parameters, i.e. colour and opacity. Construct an instance then modify members.

representation
colour
alpha
visible
lineWidth
randomColour
depth
__repr__()
getColour()

Return the colour and generate a random colour if flagged.

_generateRandomColour()
pyg4ometry.visualisation.loadPredefined()

Construct a ColorMap initialised with default colours for various materials.

Lods from package resource files.

pyg4ometry.visualisation.getPredefinedMaterialVisOptions()
pyg4ometry.visualisation.makeVisualisationOptionsDictFromPredefined(ColourMap)
pyg4ometry.visualisation._getPredefinedMaterialVisOptions()
class pyg4ometry.visualisation.VtkViewer(size=(1024, 1024), interpolation='none', **kwargs)

Visualiser.

Parameters:
  • size – (int,int) - (nPixelsHorizontal, nPixelsVeritcal), default (1024,1024)

  • interpolation – (str) - one of “none”, “flat”, “gouraud”, “phong”

Examples:

>>> v = VtkViewer()
>>> v.addLogicalVolume(someLV)
>>> v.view()
ren
renWin
iren
style
localmeshes
localmeshesOverlap
filters
filtersOverlap
mappers = []
physicalMapperMap
mappersOverlap = []
physicalMapperMapOverlap
actors = []
physicalActorMap
actorsOverlap = []
physicalActorMapOverlap
_xCutterOrigin = [0, 0, 0]
_yCutterOrigin = [0, 0, 0]
_zCutterOrigin = [0, 0, 0]
_xCutterNormal = [1, 0, 0]
_yCutterNormal = [0, 1, 0]
_zCutterNormal = [0, 0, 1]
xcutters = []
ycutters = []
zcutters = []
usercutters = []
axes = []
materialVisOptions = None
interps = ('none', 'flat', 'gouraud', 'phong')
interpolation
addAxes(length=20.0, origin=(0, 0, 0))

Add x,y,z axis to the scene.

Parameters:
  • length – float - length of each axis in mm

  • origin – (float,float,float) - (x,y,z) of origin in mm

addAxesWidget()
setOpacity(v, iActor=-1)
setWireframe(iActor=-1)
setSurface(iActor=-1)
setOpacityOverlap(v, iActor=-1)
setWireframeOverlap(iActor=-1)
setSurfaceOverlap(iActor=-1)
setRandomColours(seed=0)
setCutterOrigin(dimension, origin)
Parameters:
  • dimension – str - ‘x’, ‘y’, or ‘z’

  • origin – list([x,y,z])

setCutterNormal(dimension, normal)
Parameters:
  • dimension – str - ‘x’, ‘y’, or ‘z’

  • normal – list([x,y,z]) - should be unit vector

addMaterialVisOption(materialName, visOptionInstance)

Append a visualisation option instance to the dictionary of materials.

Parameters:
setMaterialVisOptions(materialDict)

Replace the (by default None) dictionary for materials to colours :param materialDict: {“materialName”: VisualisationOptions}

See also VisualisationOptions.

setCameraFocusPosition(focalPoint=[0, 0, 0], position=[100, 100, 100])
start()
exportOBJScene(fileName='scene')
exportVRMLScene(fileName='scene')
exportGLTFScene(fileName='scene.gltf')
exportScreenShot(fileName='screenshot.png', rgba=True)

Write the render window view to an image file.

Image types supported are: BMP, JPEG, PNM, PNG, PostScript, TIFF. The default parameters are used for all writers, change as needed.

Parameters:
  • fileName – The file name, if no extension then PNG is assumed.

  • renWin – The render window.

  • rgba – Used to set the buffer type.

Returns:

addLogicalVolume(logical, mtra=_np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), tra=_np.array([0, 0, 0]), recursive=True, addWorld=True)
addLogicalVolumeBounding(logical)
addSolid(solid, rotation=[0, 0, 0], position=[0, 0, 0], representation='surface', colour=[0.5, 0.5, 0.5], opacity=0.2)

Add a solid to the view with an optional rotation and translation.

Parameters:
  • solid (any solid in pyg4ometry.geant4.solid) – solid to add to the view

  • rotation (list(float, float, float) - 3 values) – list of TB rotation angles in radians

  • position (list(float, float, float) - 3 values) – translation in global from from centre in mm

  • representation (str) – the way to visualise it, e.g. ‘surface’ or ‘wireframe’

  • colour (list(float, float, float) - 3 values ranging from 0 - 1) – normalised rgb colour to use for the solid mesh

  • opacity (float, from 0 to 1) – the opacity of the solid if surface style

addBooleanSolidRecursive(solid, mtra=_np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), tra=_np.array([0, 0, 0]), first=True)
Parameters:

solid (pyg4ometry.geant4.solid.SolidBase) – pyg4ometry.geant4.solid instance.

Other parameters are for internal recursion and don’t need to be provided.

Render only a Boolean solid. If one of the constituent solids is also a Boolean, visualise those too. The resultant Boolean is shown in solid form and each constituent in a wireframe. In the case of a null mesh, only the constituents can be shown.

addMeshSimple(csgMesh, visOptions=_VisOptions(), clip=False, name='mesh')
addLogicalVolumeRecursive(logical, mtra=_np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), tra=_np.array([0, 0, 0]))
addMesh(pv_name, solid_name, mesh, mtra, tra, localmeshes, filters, mappers, mapperMap, actors, actorMap, visOptions=None, overlap=False, cutters=True, clippers=False)
view(interactive=True, resetCamera=True)
_getCutterData(axis='x', scaling=1.0)
exportCutterSection(filename, normal='x', scaling=1.0)

Export the section lines in plane perpendicular to normal. Exported as json text.

Parameters:
  • filename – (str) - name of file to export to

  • normal – (str) - one of “x”, “y” or “z”

  • scaling – (float) - multiplier for all cutter line coordinates on export

Examples:

>>> v.exportCutterSection("xz-section.dat", normal="y", scaling=1000)
viewSection(dir='x')
addCutterPlane(position, normal, colour=None)

Add a cutting plane at position=[x,y,z] with normal [nx,ny,nz].

Parameters:
  • position – [float, float, float] - (x,y,z) position in scene (mm)

  • normal – [float, float, float] - (nx,ny,z) normal unit vector

  • colour – None or [float, float, float] - [r,g,b] in range [0:1]

Cutters are stored in self.usercutters.

addActor(actor)
getOverlapVisOptions(overlaptype)
getMaterialVisOptions(pv)
_getDefaultVis(pv)
printViewParameters()
class pyg4ometry.visualisation.VtkViewerColoured(*args, defaultColour=None, materialVisOptions=None, **kwargs)

Bases: VtkViewer

Visualiser that extends VtkViewer. Uses “flat” interpolation and introduces control over colours.

Keyword Arguments:

  • materialVisOptions: {“materialName”: VisualisationOptions or list or tuple, …}

  • interpolation (str): see VtkViewer

  • defaultColour (str): “random” or [r,g,b]

Examples:

>>> vMaterialMap = VtkViewerColoured(materialVisOptions={"G4_WATER":[0,0,1]})
>>> vRandom = VtkViewerColoured(defaultColour="random")
>>> vColoured = VtkViewerColoured(defaultColour=[0.1,0.1,0.1])
>>> vColourAlpha = VtkViewerColoured(defaultColour=[0.1,0.1,0.1,0.5])

of use visualisation options instances

>>> vo = pyg4ometry.visualisation.VisualisationOptions()
>>> vo.colour = [0.1,1.0,0.5]
>>> vo.alpha = 0.3
>>> options = {'G4_WATER':vo}
>>> vis = VtkViewerColoured(materialVisOptions=options)

If the value in the materialVisOptions is a list or a tuple, it will be upgraded to a VisualisationOptions instance.

materialVisOptions
_defaultVis
randomColour
_getDefaultVis(pv)
pyg4ometry.visualisation.PubViewer
class pyg4ometry.visualisation.VtkViewerColouredMaterial(*args, **kwargs)

Bases: PubViewer

Extension of VtkViewerColoured that uses a default material dictionary for several common materials. Material colours are in defined Colour.py for many Geant4, FLUKA and BDSIM materials.

class pyg4ometry.visualisation.MouseInteractorNamePhysicalVolume(renderer, vtkviewer)

Bases: vtk.vtkInteractorStyleTrackballCamera

renderer
vtkviewer
rightButtonPressEvent(obj, event)
pyg4ometry.visualisation.axesFromExtents(extent)
pyg4ometry.visualisation.viewLogicalVolumeDifference(referenceLV, otherLV, otherTranslation=[0, 0, 0], otherRotation=[0, 0, 0], viewDifference=True)
Parameters:
  • referenceLV (pyg4ometry.geant4.LogicalVolume.) – LogicalVolume instance to view viewed in red.

  • referenceLV – LogicalVolume instance to view viewed in blue.

  • otherTranslation ([float, float, float]) – Translation (in native units, mm) of otherLV w.r.t. referenceLV

  • otherRotation ([float, float, float]) – Rotation (in native units, rad) of other LV w.r.t. referenceLV.

View the shapes of 2 logical volumes without their contents. The reference one will be red and the ‘other’ one will be blue.

The other one may optionally be translated and rotated (Tait-Bryant x,y,z) relative to the reference.

class pyg4ometry.visualisation._VisOptions(representation='surface', colour=[0.5, 0.5, 0.5], alpha=0.5, visible=True, lineWidth=1, randomColour=False, depth=0)

Basic holder for visualisation parameters, i.e. colour and opacity. Construct an instance then modify members.

representation
colour
alpha
visible
lineWidth
randomColour
depth
__repr__()
getColour()

Return the colour and generate a random colour if flagged.

_generateRandomColour()
pyg4ometry.visualisation._getPredefinedMaterialVisOptions()
class pyg4ometry.visualisation.VtkViewerNew

Bases: pyg4ometry.visualisation.ViewerBase

cutterOrigins
cutterNormals
bClipper = False
bClipperCutter = False
clipperOrigin = None
clipperNormal = None
clipperPlaneWidget = None
initVtk()
clear()
addAxes(length=20.0, origin=(0, 0, 0))

Add x,y,z axis to the scene.

Parameters:
  • length – float - length of each axis in mm

  • origin – (float,float,float) - (x,y,z) of origin in mm

setAxes(iAxes, length, origin)
addAxesWidget()
addCutter(name, origin, normal)
setCutter(name, origin, normal)
addCutterWidget()
exportCutter(name, fileName)
getCutterPolydata(name)
addClipper(origin, normal, bClipperCutter=False, bClipperCloseCuts=True)
setClipper(origin, normal)
addClipperWidget()
updateClipperPlaneCallback(obj, event)
_polydata2Actor(polydata)
buildPipelines()
buildPipelinesSeparate()
buildPipelinesAppend()
buildPipelinesTransformed()
render()
view(interactive=True, resetCamera=False)
__repr__()
addTracks(pd)
addScoringMesh(gd)
class pyg4ometry.visualisation.VtkViewerColouredNew(*args, defaultColour=None, materialVisOptions=None, **kwargs)

Bases: VtkViewerNew

Visualiser that extends VtkViewer. Uses “flat” interpolation and introduces control over colours.

Keyword Arguments:
  • materialVisOptions: {“materialName”: VisualisationOptions or list or tuple, …}

  • interpolation (str): see VtkViewer

  • defaultColour (str): “random” or [r,g,b]

Examples:

>>> vMaterialMap = VtkViewerColoured(materialVisOptions={"G4_WATER":[0,0,1]})
>>> vRandom = VtkViewerColoured(defaultColour="random")
>>> vColoured = VtkViewerColoured(defaultColour=[0.1,0.1,0.1])
>>> vColourAlpha = VtkViewerColoured(defaultColour=[0.1,0.1,0.1,0.5])

of use visualisation options instances

>>> vo = pyg4ometry.visualisation.VisualisationOptions()
>>> vo.colour = [0.1,1.0,0.5]
>>> vo.alpha = 0.3
>>> options = {'G4_WATER':vo}
>>> vis = VtkViewerColoured(materialVisOptions=options)

If the value in the materialVisOptions is a list or a tuple, it will be upgraded to a VisualisationOptions instance.

_defaultVis
randomColour
_getDefaultVis(pv)
class pyg4ometry.visualisation.VtkViewerColouredMaterialNew(*args, **kwargs)

Bases: VtkViewerColouredNew

Extension of VtkViewerColoured that uses a default material dictionary for several common materials. Material colours are in defined Colour.py for many Geant4, FLUKA and BDSIM materials.

class pyg4ometry.visualisation.MouseInteractorNamePhysicalVolume(renderer, vtkviewer)

Bases: vtk.vtkInteractorStyleTrackballCamera

ren
vtkviewer
highLightActor = None
highLightTextActor = None
removeHighLight()
removeHighLightText()
rightButtonPressEvent(obj, event)
class pyg4ometry.visualisation.BlenderViewer

Bases: pyg4ometry.visualisation.ViewerBase

instanceBlenderOptions
createBlenderObjects(option='unique')
createBlenderObjectsUnique()
class pyg4ometry.visualisation.RenderWriter
materials
meshes
instances
addLogicalVolumeRecursive(logical, mtra=_np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), tra=_np.array([0, 0, 0]))
addMesh(logical)
addInstance(logical, transformation, translation)
write(outputDirectory)
pyg4ometry.visualisation.mkVtkIdList(it)
pyg4ometry.visualisation.pycsgMeshToVtkPolyData(mesh)
pyg4ometry.visualisation.vtkPolyDataToNumpy(data)
pyg4ometry.visualisation.pycsgMeshToObj(mesh, fileName)
pyg4ometry.visualisation.pyg42VtkTransformation(mtra, tra)
pyg4ometry.visualisation.vtkTransformation2PyG4(vt)
pyg4ometry.visualisation.pycsgMeshToStl(mesh, fileName)
pyg4ometry.visualisation._WITH_PARAVIEW = False
class pyg4ometry.visualisation.VtkExporter(path='.')
path
localmeshes
elements = []
mbdico
mbindexdico
materialVisualisationOptions
export_to_Paraview(reg, fileName='Paraview_model.pvsm', model=True, df_model=None, df_color=None)

Method that exports the visible logical volumes of the registry reg into Paraview VTK files (.vtm) and creates a Paraview State file (.pvsm) for the Paraview Model.

df_model and df_color are optional: if they are not given, the Paraview model will take the materials colors

Parameters:
  • reg – Registry

  • fileName – Name of the Paraview State file (.pvsm)

  • model – Boolean informing whether we work with a “model” GDML or a “simple” GDML

True: it will consider that each daughter volume of the GDML world volume will need a .vtm file False: it will create one .vtm file for the whole GDML :param df_model: (optional) pandas.DataFrame linking the NAME of the element and their TYPE :param df_color: (optional) pandas.DataFrame linking the TYPE with its specific R G B color

export_to_VTK(reg, model=True, df_model=None, df_color=None)

Method that exports the visible logical volumes of the registry reg into Paraview VTK files (.vtm).

Parameters:
  • reg – Registry

  • model – Boolean informing whether we work with a “model” GDML or a “simple” GDML

True: it will consider that each daughter volume of the GDML world volume will need a .vtm file False: it will create one .vtm file for the whole GDML :param df_model: (optional) pandas.DataFrame linking the NAME of the element and their TYPE :param df_color: (optional) pandas.DataFrame linking the TYPE with its specific R G B color

fill_color_dico(df_gdml, df_model, df_color)

Method that fills a dictionary linking the logical volumes names and their respective color based on the pandas.DataFrame df_color linking the TYPE of the elements and their respective RGB color values.

Parameters:
  • df_gdml – pandas.DataFrame that represents the GDML Structure

  • df_model – pandas.DataFrame linking the NAME of the element and their TYPE

  • df_color – pandas.DataFrame linking the TYPE with its specific R G B color

Returns: A dictionary with the keys R, G and B whose item is a dictionary with as keys the logical volumes names and as item the respective RGB value

add_logical_world_volume(lv, model, color_dico={'R': {}, 'G': {}, 'B': {}}, rotation=_np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), translation=_np.array([0, 0, 0]))

Method that receives the logical world volume and calls the necessary methods to write the .vtm file(s).

Parameters:
  • lv – Logical world volume

  • model – Boolean informing whether we work with a “model” GDML or a “simple” GDML

True: it will consider that each daughter volume of the GDML world volume will need a .vtm file False: it will create one .vtm file for the whole GDML :param color_dico: A dictionary with the keys R, G and B whose item is a dictionary with as keys the logical volumes names and as item the respective RGB value :param rotation: (optional) numpy.matrix :param translation: (optional) numpy.array

add_logical_volume_recursive(lv, rotation, translation, color_dico, first_level=True)

Method that receives a logical volume and add calls addMesh() on its mesh. The method is recursive and will be called on all the daughter logical volumes of the logical volume.

Parameters:
  • lv – Logical volume

  • rotation – numpy.matrix

  • ranslation – numpy.array

  • color_dico – A dictionary with the keys R, G and B whose item is a dictionary

with as keys the logical volumes names and as item the respective RGB value :param first_level: Boolean indicating if we are at the first level of recursivity

addMesh(solid_name, mesh, rotation, translation, visOptions=None)

Method that converts the mesh into VtkPolyData (.vtp file) and gives it the correct rotation, translation and color.

Parameters:
  • solid_name – Name of the logical volume solid

  • mesh – Mesh of the logical volume

  • rotation – numpy.matrix

  • translation – numpy.array

  • visOptions – VisualisationOptions instance

getMaterialVisOptions(name)

Method that “cleans” the logical volume material string.

Parameters:

name (str) – raw name of the logical volume material

Returns: clean name of the logical volume material

getElementName(logicalVolumeName)

Method that “cleans” the logical volume name string.

Parameters:

logicalVolumeName (str) – raw name of the logical volume

Returns: clean name of the logical volume

countVisibleDaughters(lv, element_name, n=0)

Method that counts the number of “visible” daughter logical volumes of the mother logical volume lv.

Parameters:

Returns: n