Skip to content

Commit

Permalink
enable ruff T201 check and fix misc print/logging
Browse files Browse the repository at this point in the history
  • Loading branch information
ManuelHu committed Jan 29, 2025
1 parent ca14618 commit 735561d
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 65 deletions.
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,12 @@ lint.select = [
"EXE", # flake8-executable
"NPY", # NumPy specific rules
# "PD", # pandas-vet
"T201",
]

lint.extend-ignore = [
"PLR", # Design related pylint codes
"E501", # Line too long
"PT004", # Use underscore for non-returning fixture (use usefixture instead)
"RUF012", # Mutable class attributes should be annotated with typing.ClassVar
"RUF100", # unused noqa TODO: remove after print() migration
]
Expand All @@ -147,6 +147,10 @@ lint.isort.required-imports = ["from __future__ import annotations"]
"src/pyg4ometry/misc/TestUtils.py" = ["T201"]
"src/pyg4ometry/compare/_Compare.py" = ["T201"]
# further ignores, TODO: should be removed.
"src/pyg4ometry/gui/**" = ["T201"]
"src/pyg4ometry/{fluka,convert}/**" = ["T201"]
"src/pyg4ometry/{io,analysis,features}/**" = ["T201"]
"src/pyg4ometry/{freecad,pycgal,pyoce}/**" = ["T201"]
"src/pyg4ometry/visualisation/{UsdViewer,ViewerHierarchyBase}.py" = ["T201"]

[tool.cibuildwheel]
Expand Down
12 changes: 6 additions & 6 deletions src/pyg4ometry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
__version__ = "unknown version"
version_tuple = (0, 0, "unknown version")

import logging

_log = logging.getLogger(__name__)

from . import config
from . import compare
from . import convert
Expand All @@ -19,7 +23,7 @@
try:
from . import pyoce
except ImportError:
print("Failed to import open cascade")
_log.error("Failed to import opencascade")
from . import stl
from . import transformation
from . import visualisation
Expand All @@ -29,8 +33,4 @@
from . import misc
from . import analysis
from . import montecarlo

try:
from . import usd
except ImportError:
print("Failed to import open usd")
from . import usd
14 changes: 7 additions & 7 deletions src/pyg4ometry/analysis/flukaData.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ def debugDumpFile(fd, limit=10000000):
while data:
data = fortran_read(fd)
if data and iData < limit:
print(iData, len(data))
print(iData, len(data)) # noqa: T201
iData += 1

print("total records", iData)
print("total records", iData) # noqa: T201


class _FlukaDataFile:
Expand Down Expand Up @@ -84,11 +84,11 @@ def read_data(self, fd):
pass

def print_header(self):
print("title : ", self.title)
print("time : ", self.time)
print("weight : ", self.weight)
print("ncase : ", self.ncase)
print("nbatch : ", self.nbatch)
print("title : ", self.title) # noqa: T201
print("time : ", self.time) # noqa: T201
print("weight : ", self.weight) # noqa: T201
print("ncase : ", self.ncase) # noqa: T201
print("nbatch : ", self.nbatch) # noqa: T201


class FlukaBinData:
Expand Down
72 changes: 36 additions & 36 deletions src/pyg4ometry/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def _parseStrPythonAsDict(strPython):


def _printCitation():
print("https://zenodo.org/doi/10.5281/zenodo.10449301")
print("https://zenodo.org/doi/10.5281/zenodo.10449301") # noqa: T201


def cli(
Expand Down Expand Up @@ -159,11 +159,11 @@ def cli(
verbose=None,
testing=False,
):
print("pyg4 - command line interface")
print("pyg4 - command line interface") # noqa: T201

# switch on file type
if not inputFileName:
print("pyg4> need input file name")
print("pyg4> need input file name") # noqa: T201

try:
if str(inputFileName).startswith("g4edgetestdata/"):
Expand All @@ -173,7 +173,7 @@ def cli(
d = g4edgetestdata.G4EdgeTestData()
inputFileName = d[inputFileName.replace("g4edgetestdata/", "")]
except ImportError:
print("pyg4> g4edgetestdata package not available - install with pip")
print("pyg4> g4edgetestdata package not available - install with pip") # noqa: T201
f = open(inputFileName)
f.close()
except FileNotFoundError:
Expand All @@ -189,57 +189,57 @@ def cli(
bbExtent = _np.array(wl.extent())
bbDExtent = bbExtent[1] - bbExtent[0]
bbCentre = bbExtent[0] + bbExtent[1]
print("pyg4> extent ", bbExtent)
print("pyg4> extent size ", bbDExtent)
print("pyg4> extent centre ", bbCentre)
print("pyg4> extent ", bbExtent) # noqa: T201
print("pyg4> extent size ", bbDExtent) # noqa: T201
print("pyg4> extent centre ", bbCentre) # noqa: T201

# these are not used on their own but possibly as part of other commands in multiple places
r = rotation if rotation else [0, 0, 0]
t = translation if translation else [0, 0, 0]

if info:
if info == "reg":
print("pyg4> registry defines")
print(list(reg.defineDict.keys()))
print("pyg4> registry materials")
print(list(reg.materialDict.keys()))
print("pyg4> registry solids")
print(list(reg.solidDict.keys()))
print("pyg4> registry logical volumes")
print(list(reg.logicalVolumeDict.keys()))
print("pyg4> registry assembly volumes")
print(list(reg.assemblyVolumeDict.keys()))
print("pyg4> registry physical volumes")
print(list(reg.physicalVolumeDict.keys()))
print("pyg4> registry optical surfaces")
print(list(reg.surfaceDict.keys()))
print("pyg4> registry defines") # noqa: T201
print(list(reg.defineDict.keys())) # noqa: T201
print("pyg4> registry materials") # noqa: T201
print(list(reg.materialDict.keys())) # noqa: T201
print("pyg4> registry solids") # noqa: T201
print(list(reg.solidDict.keys())) # noqa: T201
print("pyg4> registry logical volumes") # noqa: T201
print(list(reg.logicalVolumeDict.keys())) # noqa: T201
print("pyg4> registry assembly volumes") # noqa: T201
print(list(reg.assemblyVolumeDict.keys())) # noqa: T201
print("pyg4> registry physical volumes") # noqa: T201
print(list(reg.physicalVolumeDict.keys())) # noqa: T201
print("pyg4> registry optical surfaces") # noqa: T201
print(list(reg.surfaceDict.keys())) # noqa: T201
elif info == "tree":
_pyg4.geant4.DumpGeometryStructureTree(wl, 0)
elif info == "instances":
print("pyg4> Not yet implemented")
print("pyg4> Not yet implemented") # noqa: T201
else:
errMsg = "Accepted info keys are 'reg', 'tree', 'instances'"
raise ValueError(errMsg)

if checkOverlaps:
print("pyg4> checkoverlaps")
print("pyg4> checkoverlaps") # noqa: T201
wl.checkOverlaps(True)

if analysis:
print("pyg4> analysis")
print("pyg4> analysis") # noqa: T201
a = _pyg4.geant4.AnalyseGeometryComplexity(reg.getWorldVolume())
a.printSummary()

if compareFileName is not None:
creg, cwl = _loadFile(compareFileName)
comparision = _pyg4.compare.geometry(wl, cwl, _pyg4.compare.Tests(), False)
print("pyg4> compare")
print("pyg4> compare") # noqa: T201
comparision.print()

if appendFileName is not None:
reg1, wl1 = _loadFile(appendFileName)
wp1 = _pyg4.geant4.PhysicalVolume(r, t, wl1, "l1_pv", wl, reg)
print("pyg4> append")
print("pyg4> append") # noqa: T201
reg.addVolumeRecursive(wp1)

# extract lv in new registry etc
Expand Down Expand Up @@ -324,7 +324,7 @@ def cli(
v.addCutter("cli-cutter", o, n)
v.buildPipelinesAppend()
v.exportCutter("cli-cutter", planeCutterOutputFileName)
print(
print( # noqa: T201
"pyg4> cutter with " + str(o) + ", " + str(n) + " written to: ",
planeCutterOutputFileName,
)
Expand All @@ -340,7 +340,7 @@ def mainNoExceptions(testArgs=None, testing=False):
try:
main(testArgs, testing)
except Exception as ex:
print(*ex.args)
print(*ex.args) # noqa: T201
exit(1)


Expand Down Expand Up @@ -500,45 +500,45 @@ def main(testArgs=None, testing=False):

verbose = options.__dict__["verbose"]
if verbose:
print("pyg4> options")
print(options)
print("pyg4> options") # noqa: T201
print(options) # noqa: T201

if options.__dict__["citation"]:
_printCitation()
exit(0)

# absolutely need a file name
if options.__dict__["inputFileName"] is None:
print("pyg4> need an input file")
print("pyg4> need an input file") # noqa: T201
exit(1)

# parse plane
planeData = options.__dict__["planeCutter"]
if planeData is not None:
planeData = _parseStrMultipletAsFloat(planeData)
if verbose:
print("pyg4> clipper plane data", planeData)
print("pyg4> clipper plane data", planeData) # noqa: T201

# parse translation
translation = options.__dict__["translation"]
if translation is not None:
translation = _parseStrMultipletAsFloat(translation)
if verbose:
print("pyg4> translation ", translation)
print("pyg4> translation ", translation) # noqa: T201

# parse rotation
rotation = options.__dict__["rotation"]
if rotation is not None:
rotation = _parseStrMultipletAsFloat(rotation)
if verbose:
print("pyg4> rotation ", rotation)
print("pyg4> rotation ", rotation) # noqa: T201

# parse clip box
clipbox = options.__dict__["clip"]
if clipbox is not None:
clipbox = _parseStrMultipletAsFloat(clipbox)
if verbose:
print("pyg4> clip ", clipbox)
print("pyg4> clip ", clipbox) # noqa: T201

# parse solid
# this must be done when we have a registry
Expand All @@ -552,7 +552,7 @@ def main(testArgs=None, testing=False):
if featureData is not None:
featureData = _parseStrMultipletAsFloat(featureData)
if verbose:
print("pyg4> feature data", featureData)
print("pyg4> feature data", featureData) # noqa: T201

# parse gltf scale
gltfScale = options.__dict__["gltfScale"]
Expand Down
16 changes: 8 additions & 8 deletions src/pyg4ometry/compare/_Compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def printAllTestNames(cls):
Print all tests names - the exact strings that can be used to turn them off or on.
"""
for name in cls._testNames:
print('"' + name + '"')
print('"' + name + '"') # noqa: T201

def __repr__(self):
s = ""
Expand Down Expand Up @@ -238,22 +238,22 @@ def print(
>>> cr.print(testResultsToPrint=TestResult.All())
>>> cr.print(allTests=True)
"""
print("Overall result> ", self.result)
print("Overall result> ", self.result) # noqa: T201
if allTests:
testResultsToPrint = TestResult.All()
if testName is None:
for tn, results in self.test.items():
print("Test> ", tn)
print("Test> ", tn) # noqa: T201
for result in results:
# only print if required
if result.testResult in testResultsToPrint:
print(result)
print(" ")
print(result) # noqa: T201
print(" ") # noqa: T201
else:
print("Test> ", testName)
print("Test> ", testName) # noqa: T201
for result in self.test[testName]:
print(result)
print(" ") # for a new line
print(result) # noqa: T201
print(" ") # for a new line # noqa: T201


def gdmlFiles(referenceFile, otherFile, tests=Tests(), includeAllTestResults=False):
Expand Down
10 changes: 6 additions & 4 deletions src/pyg4ometry/freecad/Reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from ..geant4 import Material as _Material
from ..meshutils import MeshShrink as _MeshShrink

_log = _log.getLogger(__name__)


class Reader:
def __init__(self, fileName, registryOn=True, fileNameAux=None):
Expand Down Expand Up @@ -170,7 +172,7 @@ def convertFlat(
globalPlacement.Rotation = globalRotation.multiply(globalPlacement.Rotation)

# info log output
_log.info(
_log.debug(
f"freecad.reader.convertFlat> Part::Feature label={obj.Label} typeid={obj.TypeId} placement={obj.Placement}"
)

Expand Down Expand Up @@ -379,7 +381,7 @@ def printStructure(self):

def recursePrintObjectTree(self, obj):
if obj.TypeId == "App::Part":
_log.info(
_log.debug(
f"freecad.Reader.recursePrintObjectTree> App::Part {obj.TypeId} {obj.Label} {obj.Placement}"
)
for gobj in obj.Group:
Expand All @@ -395,7 +397,7 @@ def recurseObjectTree(self, obj):
import pyg4ometry.gdml.Defines

if obj.TypeId == "App::Part": # mapped to logical volume, group objects mapped to physical
_log.info(
_log.debug(
f"freecad.reader.recurseObjectTree> App::Part label={obj.Label} grouplen={len(obj.Group)} placement={obj.Placement}"
)

Expand Down Expand Up @@ -451,7 +453,7 @@ def recurseObjectTree(self, obj):

return objects
elif obj.TypeId == "Part::Feature": # mapped to logical volumes
_log.info(
_log.debug(
f"freecad.reader.recurseObjectTree> Part::Feature label={obj.Label} placement={obj.Placement}"
)

Expand Down
9 changes: 6 additions & 3 deletions src/pyg4ometry/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
import time
import numpy as np
from copy import deepcopy
import logging

_log = logging.getLogger(__name__)


def _write_pickle(obj, path):
Expand Down Expand Up @@ -78,14 +81,14 @@ def writeAppend(self, path, verbose=False):
existing = _load_pickle(path)

if verbose:
print(f"Appending samples to {path}")
print(self.n_samples_description())
_log.info(f"Appending samples to {path}")
_log.info(f"{self.n_samples_description()}")
new = Samples.from_existing(existing, self)

_write_pickle(new, path)
except FileNotFoundError:
if verbose:
print(f"Writing new samples to {path}")
_log.info(f"Writing new samples to {path}")
self.write(path)

def __getitem__(self, key):
Expand Down

0 comments on commit 735561d

Please sign in to comment.