Skip to content

Commit

Permalink
rework logging/print in visualisation
Browse files Browse the repository at this point in the history
  • Loading branch information
ManuelHu committed Jan 29, 2025
1 parent 0d5ffda commit ca14618
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 48 deletions.
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,12 @@ lint.flake8-unused-arguments.ignore-variadic-names = true
lint.isort.required-imports = ["from __future__ import annotations"]

[tool.ruff.lint.per-file-ignores]
# ignores because of tests.
"tests/**" = ["T20"]
"src/pyg4ometry/misc/TestUtils.py" = ["T201"]
"src/pyg4ometry/compare/_Compare.py" = ["T201"]
# further ignores, TODO: should be removed.
"src/pyg4ometry/visualisation/{UsdViewer,ViewerHierarchyBase}.py" = ["T201"]

[tool.cibuildwheel]
build = ["*macosx*", "*manylinux_x86_64", "*windows*"]
Expand Down
10 changes: 5 additions & 5 deletions src/pyg4ometry/visualisation/BlenderViewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@

try:
import bpy as _bpy

print("Blender pyg4ometry imported")
except ImportError:
pass
_bpy = None


class BlenderViewer(_ViewerBase):
def __init__(self):
if _bpy is None:
msg = "blender python library not imported"
raise RuntimeError(msg)

super().__init__()
self.instanceBlenderOptions = {}

Expand All @@ -25,8 +27,6 @@ def createBlenderObjects(self, option="unique"):
def createBlenderObjectsUnique(self):

for motherKey in self.instancePlacements:
print(motherKey)
# print(self.instancePlacements[motherKey])

placements = self.instancePlacements[motherKey]

Expand Down
8 changes: 5 additions & 3 deletions src/pyg4ometry/visualisation/Mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import logging as _log
import numpy as _np

_log = _log.getLogger(__name__)


class OverlapType:
protrusion = 1
Expand Down Expand Up @@ -71,7 +73,7 @@ def _getBoundingBox(aMesh, rotationMatrix=None, translation=None, nameForError="
"""
vertices, _, _ = aMesh.toVerticesAndPolygons()
if not vertices:
print("Warning> getBoundingBox null mesh error : ", nameForError)
_log.warning("getBoundingBox null mesh error : %s", nameForError)
if _config.meshingNullException:
raise exceptions.NullMeshError(nameForError)
else:
Expand All @@ -88,7 +90,7 @@ def _getBoundingBox(aMesh, rotationMatrix=None, translation=None, nameForError="
vMin = [min(vertices[..., 0]), min(vertices[..., 1]), min(vertices[..., 2])]
vMax = [max(vertices[..., 0]), max(vertices[..., 1]), max(vertices[..., 2])]

_log.info("visualisation.Mesh.getBoundingBox> %s %s", vMin, vMax)
_log.debug("visualisation.Mesh.getBoundingBox> %s %s", vMin, vMax)

return [vMin, vMax]

Expand All @@ -107,7 +109,7 @@ def _getBoundingBoxMesh(boundingBox):
pY = dy / 2.0
pZ = dz / 2.0

_log.info("box.pycsgmesh> getBoundingBoxMesh")
_log.debug("box.pycsgmesh> getBoundingBoxMesh")

mesh = _CSG.cube(center=[x0, y0, z0], radius=[pX, pY, pZ])
return mesh
18 changes: 10 additions & 8 deletions src/pyg4ometry/visualisation/ViewerBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
import copy as _copy
import numpy as _np
import random as _random
import logging as _log
from .. import pycgal as _pycgal
from .. import transformation as _transformation
from .VisualisationOptions import (
VisualisationOptions as _VisOptions,
)
from .Mesh import OverlapType as _OverlapType

_log = _log.getLogger(__name__)


def _daughterSubtractedMesh(lv):
mm = lv.mesh.localmesh.clone() # mother mesh
Expand Down Expand Up @@ -165,7 +168,7 @@ def addLogicalVolume(
pass

else:
print("Unknown logical volume type or null mesh")
_log.warning("Unknown logical volume type or null mesh")

for pv in lv.daughterVolumes:
vo = self.getVisOptions(pv)
Expand Down Expand Up @@ -226,11 +229,10 @@ def addLogicalVolume(
self.addInstance(pv_name, new_mtra, new_tra, pv_name)
self.addVisOptions(pv_name, vo2)

def addFlukaRegions(self, fluka_registry, max_region=1000000, debugIO=False):
def addFlukaRegions(self, fluka_registry, max_region=1000000):
icount = 0
for k in fluka_registry.regionDict:
if debugIO:
print("ViewerBase.addFlukaRegions>", k)
_log.debug("ViewerBase.addFlukaRegions> %s", k)
m = fluka_registry.regionDict[k].mesh()

if m is not None:
Expand Down Expand Up @@ -432,7 +434,7 @@ def exportGLTFScene(self, gltfFileName="test.gltf", singleInstance=False):
VEC3,
)
except ImportError:
print("pygltflib needs to be installed for export : 'pip install pygltflib'")
_log.error("pygltflib needs to be installed for export : 'pip install pygltflib'")
return

materials = []
Expand Down Expand Up @@ -603,7 +605,7 @@ def exportGLTFScene(self, gltfFileName="test.gltf", singleInstance=False):
f.write(glb)
f.close()
else:
print("ViewerBase::exportGLTFScene> unknown gltf extension")
_log.error("ViewerBase::exportGLTFScene> unknown gltf extension")

def exportGLTFAssets(self, gltfFileName="test.gltf"):
"""Export all the assets (meshes) without all the instances. The position of the asset is
Expand Down Expand Up @@ -658,7 +660,7 @@ def dumpMeshQuality(self):
mesh = self.localmeshes[localmeshkey]

if _pycgal.CGAL.is_triangle_mesh(mesh.sm):
print(
print( # noqa: T201
localmeshkey,
mesh,
mesh.polygonCount(),
Expand All @@ -667,7 +669,7 @@ def dumpMeshQuality(self):
mesh.volume(),
)
else:
print(localmeshkey)
print(localmeshkey) # noqa: T201

def __repr__(self):
return "ViewerBase"
12 changes: 7 additions & 5 deletions src/pyg4ometry/visualisation/VtkExporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@
)
import logging as _logging

_log = _logging.getLogger(__name__)

_WITH_PARAVIEW = True
try:
import paraview.simple as paras
except (ImportError, ImportWarning):
_WITH_PARAVIEW = False
msg = "paraview is required for this module to have full functionalities.\n"
msg += "Not all methods will be available."
_logging.log(20, msg)
_log.warning(msg)


class VtkExporter:
Expand Down Expand Up @@ -81,7 +83,7 @@ def export_to_Paraview(
)
paras.Show(xml, MapScalars=0)
index += 1
print((index / len(self.elements)) * 100, " %")
_log.info("%.2f %%", (index / len(self.elements)) * 100)

paras.Render()

Expand Down Expand Up @@ -195,7 +197,7 @@ def add_logical_world_volume(
writer = _vtk.vtkXMLMultiBlockDataWriter()
writer.SetDataModeToAscii()
writer.SetInputData(self.mbdico[element])
print(f"Trying to write file {element}.vtm")
_log.info(f"Trying to write file {element}.vtm")
writer.SetFileName(f"{self.path}/{element}.vtm")
writer.Write()

Expand Down Expand Up @@ -332,8 +334,8 @@ def getMaterialVisOptions(self, name):
if namestrip in self.materialVisualisationOptions.keys():
return self.materialVisualisationOptions[namestrip]
else:
print(
f"Warning, missing {namestrip} in materialVisualisationOptions, replace by default color"
_log.warning(
f"missing {namestrip} in materialVisualisationOptions, replace by default color"
)
return self.materialVisualisationOptions["G4_C"]

Expand Down
22 changes: 12 additions & 10 deletions src/pyg4ometry/visualisation/VtkViewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import logging as _log
import random as _random

_log = _log.getLogger(__name__)


class VtkViewer:
"""
Expand Down Expand Up @@ -480,7 +482,7 @@ def addBooleanSolidRecursive(
)
first = False
except _exceptions.NullMeshError:
print(solid.name, "> null mesh... continuing")
_log.debug(f"{solid.name} > null mesh... continuing")

obj1 = solid.object1()
obj2 = solid.object2()
Expand Down Expand Up @@ -562,7 +564,7 @@ def addLogicalVolumeRecursive(
pv_name = pv.name

if pv.logicalVolume.type == "logical":
_log.info(
_log.debug(
f"VtkViewer.addLogicalVolume> Daughter {pv.name} {pv.logicalVolume.name} {pv.logicalVolume.solid.name} "
)

Expand Down Expand Up @@ -699,7 +701,7 @@ def addMesh(
clippers=False,
):
# VtkPolyData : check if mesh is in localmeshes dict
_log.info("VtkViewer.addLogicalVolume> vtkPD")
_log.debug("VtkViewer.addLogicalVolume> vtkPD")

if solid_name in localmeshes:
vtkPD = localmeshes[solid_name]
Expand Down Expand Up @@ -754,7 +756,7 @@ def addMesh(
vtkPD = normal_generator.GetOutput()

# Filter : check if filter is in the filters dict
_log.info("VtkViewer.addLogicalVolume> vtkFLT")
_log.debug("VtkViewer.addLogicalVolume> vtkFLT")
filtername = solid_name + "_filter"
if filtername in filters:
vtkFLT = filters[filtername]
Expand All @@ -764,7 +766,7 @@ def addMesh(
filters[filtername] = vtkFLT

# Mapper
_log.info("VtkViewer.addLogicalVolume> vtkMAP")
_log.debug("VtkViewer.addLogicalVolume> vtkMAP")
mappername = pv_name + "_mapper"
vtkMAP = _vtk.vtkPolyDataMapper()
vtkMAP.ScalarVisibilityOff()
Expand Down Expand Up @@ -1109,10 +1111,10 @@ def getVisOptions(self, pv):

def printViewParameters(self):
activeCamera = self.ren.GetActiveCamera()
print("Window size ", self.renWin.GetSize())
print("Focal point ", activeCamera.GetFocalPoint())
print("Camera position ", activeCamera.GetPosition())
print("Focal distance ", activeCamera.GetDistance())
print("Window size ", self.renWin.GetSize()) # noqa: T201
print("Focal point ", activeCamera.GetFocalPoint()) # noqa: T201
print("Camera position ", activeCamera.GetPosition()) # noqa: T201
print("Focal distance ", activeCamera.GetDistance()) # noqa: T201


class VtkViewerColoured(VtkViewer):
Expand Down Expand Up @@ -1216,7 +1218,7 @@ def rightButtonPressEvent(self, obj, event):
pass
else:
name = name[: name.find("_actor")]
print(f"{type(self.vtkviewer).__name__}> selected> {name}")
_log.debug(f"{type(self.vtkviewer).__name__}> selected> {name}")


def axesFromExtents(extent):
Expand Down
34 changes: 17 additions & 17 deletions src/pyg4ometry/visualisation/VtkViewerNew.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ def addAxesWidget(self):

def addCutter(self, name, origin, normal):
if self.bBuiltPipelines:
print("Need to add cutter before pipelines are built")
msg = "Need to add cutter before pipelines are built"
raise RuntimeError(msg)

self.cutterOrigins[name] = origin
self.cutterNormals[name] = normal
Expand Down Expand Up @@ -179,7 +180,8 @@ def exportVtkGLTFScene(self, fileName="scene.gltf"):

def addClipper(self, origin, normal, bClipperCutter=False, bClipperCloseCuts=True):
if self.bBuiltPipelines:
print("Need to add clipper before pipelines are built")
msg = "Need to add clipper before pipelines are built"
raise RuntimeError(msg)

self.bClipper = True
self.clipperOrigin = origin
Expand All @@ -205,16 +207,14 @@ def setClipper(self, origin, normal):

def addClipperWidget(self):
if not self.bBuiltPipelines:
print(
msg = (
"Need to build pipelines before adding clipper widget e.g. v.bulidPipelinesAppend()"
)
return
raise RuntimeError(msg)

if len(self.clippers) == 0:
print(
"Need to add a clipping plane adding clipper widget e.g. v.addClipper([0, 0, 0], [0, 0, 1], True"
)
return
msg = "Need to add a clipping plane adding clipper widget e.g. v.addClipper([0, 0, 0], [0, 0, 1], True"
raise RuntimeError(msg)

plaRep = _vtk.vtkImplicitPlaneRepresentation()
# plaRep.SetPlaceFactor(1.25)
Expand Down Expand Up @@ -483,16 +483,16 @@ def buildPipelinesTransformed(self):

def render(self):
if not self.bBuiltPipelines:
print("Pipelines have not been built")
return
msg = "Pipelines have not been built"
raise RuntimeError(msg)

# Render
self.renWin.Render()

def view(self, interactive=True, resetCamera=False):
if not self.bBuiltPipelines:
print("Pipelines have not been built")
return
msg = "Pipelines have not been built"
raise RuntimeError(msg)

# enable user interface interactor
self.iren.Initialize()
Expand Down Expand Up @@ -649,15 +649,15 @@ def rightButtonPressEvent(self, obj, event):
self.ren.RemoveActor(self.highLightActor)

clickPos = self.GetInteractor().GetEventPosition()
print("clickPos> ", clickPos)
# print("clickPos> ", clickPos)

picker = _vtk.vtkPropPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.ren)
actor = picker.GetActor()

pointPicker = _vtk.vtkPointPicker()
pointPicker.Pick(clickPos[0], clickPos[1], 0, self.ren)
print("pointId>", pointPicker.GetPointId())
# print("pointId>", pointPicker.GetPointId())

cellPicker = _vtk.vtkCellPicker()
cellPicker.SetPickClippingPlanes(False)
Expand All @@ -684,10 +684,10 @@ def rightButtonPressEvent(self, obj, event):
.GetInputAlgorithm()
)

print(self.inalgo.GetClassName(), appPolyData.GetClassName())
# print(self.inalgo.GetClassName(), appPolyData.GetClassName())

point = self.inalgo.GetOutput().GetPoint(cellPicker.GetPointId())
print("pointPos>", point)
# print("pointPos>", point)

# loop over appendPolyData and find closest
dmin = 1e99
Expand Down Expand Up @@ -717,7 +717,7 @@ def rightButtonPressEvent(self, obj, event):

tba = _transformation.matrix2tbxyz(mtra)

print("minimum pd>", di, dmin, lvName, pvName, tba, tra, localExtent, globalExtent)
# print("minimum pd>", di, dmin, lvName, pvName, tba, tra, localExtent, globalExtent)

if self.highLightActor:
self.ren.RemoveActor(self.highLightActor)
Expand Down

0 comments on commit ca14618

Please sign in to comment.