11# SPDX-License-Identifier: Apache-2.0
22# SPDX-FileCopyrightText: Copyright 2023-2024 TotalEnergies.
33# SPDX-FileContributor: Antoine Mazuyer, Martin Lemay
4+ import logging
5+
46from typing_extensions import Self
5- from vtkmodules .util .vtkAlgorithm import VTKPythonAlgorithmBase
6- from vtkmodules .vtkCommonCore import (
7- vtkInformation ,
8- vtkInformationVector ,
9- vtkIntArray ,
10- )
11- from vtkmodules .vtkCommonDataModel import ( vtkUnstructuredGrid , vtkCell , vtkTable , vtkCellTypes , VTK_VERTEX )
7+ from vtkmodules .vtkCommonCore import vtkIntArray
8+ from vtkmodules .vtkCommonDataModel import vtkUnstructuredGrid , vtkCell , vtkTable , vtkCellTypes , VTK_VERTEX
129
1310from geos .mesh .model .CellTypeCounts import CellTypeCounts
1411from geos .mesh .stats .meshQualityMetricHelpers import getAllCellTypes
12+ from geos .utils .Logger import ( Logger , getLogger )
1513
1614__doc__ = """
1715CellTypeCounterEnhanced module is a vtk filter that computes cell type counts.
2523 from geos.processing.pre_processing.CellTypeCounterEnhanced import CellTypeCounterEnhanced
2624
2725 # Filter inputs
28- input: vtkUnstructuredGrid
26+ inputMesh: vtkUnstructuredGrid
27+ speHandler: bool # defaults to False
2928
3029 # Instantiate the filter
31- cellTypeCounterEnhancedFilter: CellTypeCounterEnhanced = CellTypeCounterEnhanced()
30+ cellTypeCounterEnhancedFilter: CellTypeCounterEnhanced = CellTypeCounterEnhanced( inputMesh, speHandler )
3231
33- # Set input data object
34- cellTypeCounterEnhancedFilter.SetInputDataObject(input)
32+ # Set the handler of yours (only if speHandler is True).
33+ yourHandler: logging.Handler
34+ cellTypeCounterEnhancedFilter.setLoggerHandler( yourHandler )
3535
3636 # Do calculations
37- cellTypeCounterEnhancedFilter.Update ()
37+ cellTypeCounterEnhancedFilter.applyFilter ()
3838
39- # Get counts
39+ # Get result
4040 counts: CellTypeCounts = cellTypeCounterEnhancedFilter.GetCellTypeCountsObject()
41+ outputTable: vtkTable = cellTypeCounterEnhancedFilter.getOutput()
4142"""
4243
44+ loggerTitle : str = "Cell Type Counter Enhanced"
4345
44- class CellTypeCounterEnhanced ( VTKPythonAlgorithmBase ):
4546
46- def __init__ ( self ) -> None :
47- """CellTypeCounterEnhanced filter computes mesh stats."""
48- super ().__init__ ( nInputPorts = 1 , nOutputPorts = 1 , inputType = "vtkUnstructuredGrid" , outputType = "vtkTable" )
49- self ._counts : CellTypeCounts = CellTypeCounts ()
47+ class CellTypeCounterEnhanced ():
5048
51- def FillInputPortInformation ( self : Self , port : int , info : vtkInformation ) -> int :
52- """Inherited from VTKPythonAlgorithmBase::RequestInformation.
49+ def __init__ (
50+ self : Self ,
51+ inputMesh : vtkUnstructuredGrid ,
52+ speHandler : bool = False ,
53+ ) -> None :
54+ """CellTypeCounterEnhanced filter computes mesh stats.
5355
5456 Args:
55- port (int): Input port
56- info (vtkInformationVector): Info
57-
58- Returns:
59- int: 1 if calculation successfully ended, 0 otherwise.
57+ inputMesh (vtkUnstructuredGrid): The input mesh.
58+ speHandler (bool, optional): True to use a specific handler, False to use the internal handler.
59+ Defaults to False.
6060 """
61- if port == 0 :
62- info . Set ( self .INPUT_REQUIRED_DATA_TYPE (), "vtkUnstructuredGrid" )
63- return 1
61+ self . inputMesh : vtkUnstructuredGrid = inputMesh
62+ self .outTable : vtkTable = vtkTable ( )
63+ self . _counts : CellTypeCounts = CellTypeCounts ()
6464
65- def RequestData (
66- self : Self ,
67- request : vtkInformation , # noqa: F841
68- inInfoVec : list [ vtkInformationVector ], # noqa: F841
69- outInfoVec : vtkInformationVector ,
70- ) -> int :
71- """Inherited from VTKPythonAlgorithmBase::RequestData.
65+ # Logger.
66+ self .logger : Logger
67+ if not speHandler :
68+ self .logger = getLogger ( loggerTitle , True )
69+ else :
70+ self .logger = logging .getLogger ( loggerTitle )
71+ self .logger .setLevel ( logging .INFO )
72+ self .logger .propagate = False
73+
74+ def setLoggerHandler ( self : Self , handler : logging .Handler ) -> None :
75+ """Set a specific handler for the filter logger.
76+
77+ In this filter 4 log levels are use, .info, .error, .warning and .critical,
78+ be sure to have at least the same 4 levels.
7279
7380 Args:
74- request (vtkInformation): Request
75- inInfoVec (list[vtkInformationVector]): Input objects
76- outInfoVec (vtkInformationVector): Output objects
81+ handler (logging.Handler): The handler to add.
82+ """
83+ if len ( self .logger .handlers ) == 0 :
84+ self .logger .addHandler ( handler )
85+ else :
86+ self .logger .warning ( "The logger already has an handler, to use yours set the argument 'speHandler'"
87+ " to True during the filter initialization." )
88+
89+ def applyFilter ( self : Self ) -> bool :
90+ """Apply CellTypeCounterEnhanced filter.
7791
7892 Returns:
79- int: 1 if calculation successfully ended, 0 otherwise.
93+ bool: True if the filter succeeded, False otherwise.
8094 """
81- inData : vtkUnstructuredGrid = self .GetInputData ( inInfoVec , 0 , 0 )
82- outTable : vtkTable = vtkTable .GetData ( outInfoVec , 0 )
83- assert inData is not None , "Input mesh is undefined."
84- assert outTable is not None , "Output table is undefined."
85-
86- # compute cell type counts
87- self ._counts .reset ()
88- self ._counts .setTypeCount ( VTK_VERTEX , inData .GetNumberOfPoints () )
89- for i in range ( inData .GetNumberOfCells () ):
90- cell : vtkCell = inData .GetCell ( i )
91- self ._counts .addType ( cell .GetCellType () )
92-
93- # create output table
94- # first reset output table
95- outTable .RemoveAllRows ()
96- outTable .RemoveAllColumns ()
97- outTable .SetNumberOfRows ( 1 )
98-
99- # create columns per types
100- for cellType in getAllCellTypes ():
101- array : vtkIntArray = vtkIntArray ()
102- array .SetName ( vtkCellTypes .GetClassNameFromTypeId ( cellType ) )
103- array .SetNumberOfComponents ( 1 )
104- array .SetNumberOfValues ( 1 )
105- array .SetValue ( 0 , self ._counts .getTypeCount ( cellType ) )
106- outTable .AddColumn ( array )
107- return 1
95+ self .logger .info ( f"Apply filter { self .logger .name } ." )
96+ try :
97+ # compute cell type counts
98+ self ._counts .reset ()
99+ self ._counts .setTypeCount ( VTK_VERTEX , self .inputMesh .GetNumberOfPoints () )
100+ for i in range ( self .inputMesh .GetNumberOfCells () ):
101+ cell : vtkCell = self .inputMesh .GetCell ( i )
102+ self ._counts .addType ( cell .GetCellType () )
103+
104+ # create output table
105+ # first reset output table
106+ self .outTable .RemoveAllRows ()
107+ self .outTable .RemoveAllColumns ()
108+ self .outTable .SetNumberOfRows ( 1 )
109+
110+ # create columns per types
111+ for cellType in getAllCellTypes ():
112+ array : vtkIntArray = vtkIntArray ()
113+ array .SetName ( vtkCellTypes .GetClassNameFromTypeId ( cellType ) )
114+ array .SetNumberOfComponents ( 1 )
115+ array .SetNumberOfValues ( 1 )
116+ array .SetValue ( 0 , self ._counts .getTypeCount ( cellType ) )
117+ self .outTable .AddColumn ( array )
118+ self .logger .info ( f"The filter { self .logger .name } succeeded." )
119+ except TypeError as e :
120+ self .logger .error ( f"The filter { self .logger .name } failed.\n { e } " )
121+ return False
122+ except Exception as e :
123+ mess : str = f"The filter { self .logger .name } failed.\n { e } "
124+ self .logger .critical ( mess , exc_info = True )
125+ return False
126+
127+ return True
108128
109129 def GetCellTypeCountsObject ( self : Self ) -> CellTypeCounts :
110130 """Get CellTypeCounts object.
@@ -113,3 +133,7 @@ def GetCellTypeCountsObject( self: Self ) -> CellTypeCounts:
113133 CellTypeCounts: CellTypeCounts object.
114134 """
115135 return self ._counts
136+
137+ def getOutput ( self : Self ) -> vtkTable :
138+ """Get the computed vtkTable."""
139+ return self .outTable
0 commit comments