Skip to content

Commit da8fccb

Browse files
feat: Update logger managment in PythonViewConfigurator plugin (#241)
1 parent b59ff7f commit da8fccb

File tree

4 files changed

+68
-42
lines changed

4 files changed

+68
-42
lines changed

geos-pv/src/geos/pv/plugins/qc/PVPythonViewConfigurator.py

Lines changed: 52 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# SPDX-FileContributor: Alexandre Benedicto, Martin Lemay
44
# ruff: noqa: E402 # disable Module level import not at top of file
55
import sys
6+
import logging
67
from pathlib import Path
78
from typing import Any, Union, cast
89

@@ -17,6 +18,7 @@
1718
update_paths()
1819

1920
from geos.mesh.utils.multiblockModifiers import mergeBlocks
21+
from geos.utils.Logger import ( CountVerbosityHandler, getLoggerHandlerType )
2022
import geos.pv.utils.paraviewTreatments as pvt
2123
from geos.pv.utils.checkboxFunction import createModifiedCallback # type: ignore[attr-defined]
2224
from geos.pv.utils.DisplayOrganizationParaview import DisplayOrganizationParaview
@@ -28,6 +30,11 @@
2830
GetActiveSource, GetActiveView, Render, Show, servermanager )
2931
from paraview.util.vtkAlgorithm import VTKPythonAlgorithmBase, smdomain, smproperty # type: ignore[import-not-found]
3032
# source: https://github.com/Kitware/ParaView/blob/master/Wrapping/Python/paraview/util/vtkAlgorithm.py
33+
from paraview.detail.loghandler import ( # type: ignore[import-not-found]
34+
VTKHandler,
35+
) # source: https://github.com/Kitware/ParaView/blob/master/Wrapping/Python/paraview/detail/loghandler.py
36+
37+
3138

3239
from vtkmodules.vtkCommonCore import vtkDataArraySelection, vtkInformation
3340
from vtkmodules.vtkCommonDataModel import vtkDataObject, vtkMultiBlockDataSet
@@ -50,6 +57,9 @@
5057
5158
"""
5259

60+
loggerTitle: str = "Python View Configurator"
61+
HANDLER: VTKHandler = VTKHandler()
62+
5363

5464
@SISOFilter( category=FilterCategory.QC,
5565
decoratedLabel="Python View Configurator",
@@ -61,7 +71,6 @@ def __init__( self: Self ) -> None:
6171
6272
Input is a vtkDataObject.
6373
"""
64-
# super().__init__( nInputPorts=1, nOutputPorts=1 )
6574
# Python view layout and object.
6675
self.m_layoutName: str = ""
6776
self.m_pythonView: Any
@@ -139,6 +148,23 @@ def __init__( self: Self ) -> None:
139148
"curvesAspect": {},
140149
}
141150

151+
self.logger = logging.getLogger( loggerTitle )
152+
self.logger.setLevel( logging.INFO )
153+
self.logger.addHandler( HANDLER )
154+
self.logger.propagate = False
155+
156+
counter: CountVerbosityHandler = CountVerbosityHandler()
157+
self.counter: CountVerbosityHandler
158+
self.nbWarnings: int = 0
159+
try:
160+
self.counter = getLoggerHandlerType( type( counter ), self.logger )
161+
self.counter.resetWarningCount()
162+
except ValueError:
163+
self.counter = counter
164+
self.counter.setLevel( logging.INFO )
165+
166+
self.logger.addHandler( self.counter )
167+
142168
def getUserChoices( self: Self ) -> dict[ str, Any ]:
143169
"""Access the m_userChoices attribute.
144170
@@ -808,12 +834,29 @@ def ApplyFilter( self, inputMesh: vtkDataObject, outputMesh: vtkDataObject ) ->
808834
outputMesh : A dummy mesh transformed.
809835
810836
"""
811-
assert self.m_pythonView is not None, "No Python View was found."
812-
viewSize = GetActiveView().ViewSize
813-
self.m_userChoices[ "ratio" ] = viewSize[ 0 ] / viewSize[ 1 ]
814-
self.defineInputNames()
815-
self.defineUserChoicesCurves()
816-
self.defineCurvesAspect()
817-
self.m_pythonView.Script = self.buildPythonViewScript()
818-
Render()
837+
self.logger.info( f"Apply the plugin { self.logger.name }." )
838+
try:
839+
if self.m_pythonView is None:
840+
raise ValueError( "No Python View was found." )
841+
842+
viewSize = GetActiveView().ViewSize
843+
self.m_userChoices[ "ratio" ] = viewSize[ 0 ] / viewSize[ 1 ]
844+
self.defineInputNames()
845+
self.defineUserChoicesCurves()
846+
self.defineCurvesAspect()
847+
self.m_pythonView.Script = self.buildPythonViewScript()
848+
Render()
849+
850+
result: str = f"The plugin { self.logger.name } succeeded"
851+
if self.counter.warningCount > 0:
852+
self.logger.warning( f"{ result } but { self.counter.warningCount } warnings have been logged." )
853+
else:
854+
self.logger.info( f"{ result }." )
855+
except Exception as e:
856+
self.logger.error( f"The plugin failed due to:\n{ e }" )
857+
return
858+
859+
self.nbWarnings = self.counter.warningCount
860+
self.counter.resetWarningCount()
861+
819862
return

geos-pv/src/geos/pv/pythonViewUtils/Figure2DGenerator.py

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# SPDX-License-Identifier: Apache-2.0
22
# SPDX-FileCopyrightText: Copyright 2023-2024 TotalEnergies.
33
# SPDX-FileContributor: Alexandre Benedicto
4-
from logging import Logger
54
from typing import Any
65

76
import pandas as pd # type: ignore[import-untyped]
@@ -16,7 +15,7 @@
1615

1716
class Figure2DGenerator:
1817

19-
def __init__( self: Self, dataframe: pd.DataFrame, userChoices: dict[ str, list[ str ] ], logger: Logger ) -> None:
18+
def __init__( self: Self, dataframe: pd.DataFrame, userChoices: dict[ str, list[ str ] ] ) -> None:
2019
"""Utility to create cross plots using Python View.
2120
2221
We want to plot f(X) = Y where in this class,
@@ -25,29 +24,20 @@ def __init__( self: Self, dataframe: pd.DataFrame, userChoices: dict[ str, list[
2524
Args:
2625
dataframe (pd.DataFrame): Data to plot.
2726
userChoices (dict[str, list[str]]): User choices.
28-
logger (Logger): Logger to use.
2927
"""
3028
self.m_dataframe: pd.DataFrame = dataframe
3129
self.m_userChoices: dict[ str, Any ] = userChoices
3230
self.m_fig: figure.Figure
3331
self.m_axes: list[ axes._axes.Axes ] = []
3432
self.m_lines: list[ lines.Line2D ] = []
3533
self.m_labels: list[ str ] = []
36-
self.m_logger: Logger = logger
37-
38-
try:
39-
# Apply minus 1 multiplication on certain columns.
40-
self.initMinus1Multiplication()
41-
# Defines m_fig, m_axes, m_lines and m_labels.
42-
self.plotInitialFigure()
43-
# Then to edit and customize the figure.
44-
self.enhanceFigure()
45-
self.m_logger.info( "Data were successfully plotted." )
46-
47-
except Exception as e:
48-
mess: str = "Plot creation failed due to:"
49-
self.m_logger.critical( mess )
50-
self.m_logger.critical( e, exc_info=True )
34+
35+
# Apply minus 1 multiplication on certain columns.
36+
self.initMinus1Multiplication()
37+
# Defines m_fig, m_axes, m_lines and m_labels.
38+
self.plotInitialFigure()
39+
# Then to edit and customize the figure.
40+
self.enhanceFigure()
5141

5242
def initMinus1Multiplication( self: Self ) -> None:
5343
"""Multiply by -1 certain columns of the input dataframe."""

geos-pv/src/geos/pv/pythonViewUtils/functionsFigure2DGenerator.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,8 @@ def setupAllAxes(
292292
first_ax.ticklabel_format( style="sci", axis="x", scilimits=( 0, 0 ), useMathText=True )
293293
for i in range( 1, len( associatedProperties.keys() ) ):
294294
second_ax = first_ax.twinx()
295-
assert isinstance( second_ax, axes.Axes )
295+
if not isinstance( second_ax, axes.Axes ):
296+
raise TypeError( "The second ax has not the right type.")
296297
all_ax.append( second_ax )
297298
all_ax[ i ].spines[ "right" ].set_position( ( "axes", 1 + 0.07 * ( i - 1 ) ) )
298299
all_ax[ i ].tick_params( axis="y", which="both", left=False, right=True )
@@ -304,7 +305,8 @@ def setupAllAxes(
304305
first_ax.ticklabel_format( style="sci", axis="y", scilimits=( 0, 0 ), useMathText=True )
305306
for i in range( 1, len( associatedProperties.keys() ) ):
306307
second_ax = first_ax.twiny()
307-
assert isinstance( second_ax, axes.Axes )
308+
if not isinstance( second_ax, axes.Axes ):
309+
raise TypeError( "The second ax has not the right type.")
308310
all_ax.append( second_ax )
309311
all_ax[ i ].spines[ "bottom" ].set_position( ( "axes", -0.08 * i ) )
310312
all_ax[ i ].xaxis.set_label_position( "bottom" )
@@ -383,7 +385,8 @@ def getExtremaAllAxes( axes: list[ axes.Axes ], ) -> tuple[ tuple[ float, float
383385
Returns:
384386
tuple[tuple[float, float], tuple[float, float]]: ((xMin, xMax), (yMin, yMax))
385387
"""
386-
assert len( axes ) > 0
388+
if len( axes ) <= 0:
389+
raise ValueError( "The list of axes can not be empty.")
387390
xMin, xMax, yMin, yMax = getAxeLimits( axes[ 0 ] )
388391
if len( axes ) > 1:
389392
for i in range( 1, len( axes ) ):

geos-pv/src/geos/pv/pythonViewUtils/mainPythonView.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,6 @@
33
# SPDX-FileContributor: Alexandre Benedicto
44
# type: ignore
55
# ruff: noqa
6-
from logging import Logger, getLogger, INFO
7-
from paraview.detail.loghandler import ( # type: ignore[import-not-found]
8-
VTKHandler,
9-
) # source: https://github.com/Kitware/ParaView/blob/master/Wrapping/Python/paraview/detail/loghandler.py
10-
11-
logger: Logger = getLogger( "Python View Configurator" )
12-
logger.setLevel( INFO )
13-
vtkHandler: VTKHandler = VTKHandler()
14-
logger.addHandler( vtkHandler )
15-
166
try:
177
import matplotlib.pyplot as plt
188
from paraview import python_view
@@ -30,7 +20,7 @@
3020
variableName # noqa: F821
3121
)
3222
dataframe = pvt.mergeDataframes( dataframes, variableName ) # noqa: F821
33-
obj_figure = Figure2DGenerator( dataframe, userChoices, logger ) # noqa: F821
23+
obj_figure = Figure2DGenerator( dataframe, userChoices ) # noqa: F821
3424
fig = obj_figure.getFigure()
3525

3626
def setup_data( view ) -> None: # noqa
@@ -42,4 +32,4 @@ def render( view, width: int, height: int ): # noqa
4232
return imageToReturn
4333

4434
except Exception as e:
45-
logger.critical( e, exc_info=True )
35+
raise ChildProcessError( f"Error during the plot:\n{ e }" ) from e

0 commit comments

Comments
 (0)