-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPVExtractMergeBlocksVolumeWell.py
More file actions
347 lines (294 loc) · 13.7 KB
/
PVExtractMergeBlocksVolumeWell.py
File metadata and controls
347 lines (294 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright 2023-2024 TotalEnergies.
# SPDX-FileContributor: Martin Lemay
# ruff: noqa: E402 # disable Module level import not at top of file
import os
import sys
import numpy as np
import numpy.typing as npt
from paraview.util.vtkAlgorithm import ( # type: ignore[import-not-found]
VTKPythonAlgorithmBase, smdomain, smhint, smproperty, smproxy,
)
from typing_extensions import Self
from vtkmodules.vtkCommonCore import vtkInformation, vtkInformationVector
from vtkmodules.vtkCommonDataModel import vtkMultiBlockDataSet
dir_path = os.path.dirname( os.path.realpath( __file__ ) )
parent_dir_path = os.path.dirname( dir_path )
if parent_dir_path not in sys.path:
sys.path.append( parent_dir_path )
import PVplugins # noqa: F401
from geos.utils.GeosOutputsConstants import (
GeosMeshOutputsEnum,
getAttributeToTransferFromInitialTime,
)
from geos.utils.Logger import ERROR, INFO, Logger, getLogger
from geos.processing.post_processing.GeosBlockExtractor import GeosBlockExtractor
from geos_posp.filters.GeosBlockMerge import GeosBlockMerge
from geos.mesh.utils.arrayModifiers import (
copyAttribute,
createCellCenterAttribute,
)
from geos_posp.visu.PVUtils.paraviewTreatments import getTimeStepIndex
__doc__ = """
PVExtractMergeBlocksVolumeWell is a Paraview plugin that allows to merge
ranks of a Geos output objects containing a volumic mesh and wells.
Input and output types are vtkMultiBlockDataSet.
This filter results in 2 output pipelines:
* first pipeline contains the volume mesh. If multiple regions were defined in
the volume mesh, they are preserved as distinct blocks.
* second pipeline contains wells. If multiple wells were used, they are preserved
as distinct blocks.
To use it:
* Load the module in Paraview: Tools>Manage Plugins...>Load new>PVExtractMergeBlocksVolumeWell.
* Select the Geos output .pvd file loaded in Paraview.
* Search and Apply PVExtractMergeBlocksVolumeWell Filter.
"""
@smproxy.filter(
name="PVExtractMergeBlocksVolumeWell",
label="Geos Extract And Merge Blocks - Volume/Well",
)
@smhint.xml( """
<ShowInMenu category="2- Geos Output Mesh Pre-processing"/>
<OutputPort index="0" name="VolumeMesh"/>
<OutputPort index="1" name="Wells"/>
""" )
@smproperty.input( name="Input", port_index=0 )
@smdomain.datatype( dataTypes=[ "vtkMultiBlockDataSet" ], composite_data_supported=True )
class PVExtractMergeBlocksVolumeWell( VTKPythonAlgorithmBase ):
def __init__( self: Self ) -> None:
"""Paraview plugin to extract and merge ranks from Geos output Mesh.
To apply in the case of output ".pvd" file contains Volume and Well
elements.
"""
super().__init__(
nInputPorts=1,
nOutputPorts=2,
inputType="vtkMultiBlockDataSet",
outputType="vtkMultiBlockDataSet",
)
#: all time steps from input
self.m_timeSteps: npt.NDArray[ np.float64 ] = np.array( [] )
#: displayed time step in the IHM
self.m_currentTime: float = 0.0
#: time step index of displayed time step
self.m_currentTimeStepIndex: int = 0
#: request data processing step - incremented each time RequestUpdateExtent is called
self.m_requestDataStep: int = -1
# saved object at initial time step
self.m_outputT0: vtkMultiBlockDataSet = vtkMultiBlockDataSet()
# set logger
self.m_logger: Logger = getLogger( "Extract and merge block Filter" )
def SetLogger( self: Self, logger: Logger ) -> None:
"""Set filter logger.
Args:
logger (Logger): logger
"""
self.m_logger = logger
def FillInputPortInformation( self: Self, port: int, info: vtkInformation ) -> int:
"""Inherited from VTKPythonAlgorithmBase::RequestInformation.
Args:
port (int): input port
info (vtkInformationVector): info
Returns:
int: 1 if calculation successfully ended, 0 otherwise.
"""
if port == 0:
info.Set( self.INPUT_REQUIRED_DATA_TYPE(), "vtkMultiBlockDataSet" )
return 1
def RequestInformation(
self: Self,
request: vtkInformation, # noqa: F841
inInfoVec: list[ vtkInformationVector ], # noqa: F841
outInfoVec: vtkInformationVector,
) -> int:
"""Inherited from VTKPythonAlgorithmBase::RequestInformation.
Args:
request (vtkInformation): request
inInfoVec (list[vtkInformationVector]): input objects
outInfoVec (vtkInformationVector): output objects
Returns:
int: 1 if calculation successfully ended, 0 otherwise.
"""
executive = self.GetExecutive() # noqa: F841
outInfo = outInfoVec.GetInformationObject( 0 ) # noqa: F841
return 1
def RequestDataObject(
self: Self,
request: vtkInformation,
inInfoVec: list[ vtkInformationVector ],
outInfoVec: vtkInformationVector,
) -> int:
"""Inherited from VTKPythonAlgorithmBase::RequestDataObject.
Args:
request (vtkInformation): request
inInfoVec (list[vtkInformationVector]): input objects
outInfoVec (vtkInformationVector): output objects
Returns:
int: 1 if calculation successfully ended, 0 otherwise.
"""
inData = self.GetInputData( inInfoVec, 0, 0 )
outDataCells = self.GetOutputData( outInfoVec, 0 )
outDataWells = self.GetOutputData( outInfoVec, 1 )
assert inData is not None
if outDataCells is None or ( not outDataCells.IsA( "vtkMultiBlockDataSet" ) ):
outDataCells = vtkMultiBlockDataSet()
outInfoVec.GetInformationObject( 0 ).Set(
outDataCells.DATA_OBJECT(),
outDataCells # type: ignore
)
if outDataWells is None or ( not outDataWells.IsA( "vtkMultiBlockDataSet" ) ):
outDataWells = vtkMultiBlockDataSet()
outInfoVec.GetInformationObject( 1 ).Set(
outDataWells.DATA_OBJECT(),
outDataWells # type: ignore
)
return super().RequestDataObject( request, inInfoVec, outInfoVec ) # type: ignore[no-any-return]
def RequestUpdateExtent(
self: Self,
request: vtkInformation, # noqa: F841
inInfoVec: list[ vtkInformationVector ],
outInfoVec: vtkInformationVector,
) -> int:
"""Inherited from VTKPythonAlgorithmBase::RequestUpdateExtent.
Args:
request (vtkInformation): request
inInfoVec (list[vtkInformationVector]): input objects
outInfoVec (vtkInformationVector): output objects
Returns:
int: 1 if calculation successfully ended, 0 otherwise.
"""
executive = self.GetExecutive()
inInfo = inInfoVec[ 0 ]
# get displayed time step info before updating time
if self.m_requestDataStep == -1:
self.m_logger.info( f"Apply filter {__name__}" )
self.m_timeSteps = inInfo.GetInformationObject( 0 ).Get( executive.TIME_STEPS() # type: ignore
)
self.m_currentTime = inInfo.GetInformationObject( 0 ).Get( executive.UPDATE_TIME_STEP() # type: ignore
)
self.m_currentTimeStepIndex = getTimeStepIndex( self.m_currentTime, self.m_timeSteps )
# update requestDataStep
self.m_requestDataStep += 1
# update time according to requestDataStep iterator
inInfo.GetInformationObject( 0 ).Set(
executive.UPDATE_TIME_STEP(),
self.m_timeSteps[ self.m_requestDataStep ] # type: ignore
)
outInfoVec.GetInformationObject( 0 ).Set(
executive.UPDATE_TIME_STEP(),
self.m_timeSteps[ self.m_requestDataStep ] # type: ignore
)
# update all objects according to new time info
self.Modified()
return 1
def RequestData(
self: Self,
request: vtkInformation,
inInfoVec: list[ vtkInformationVector ],
outInfoVec: vtkInformationVector,
) -> int:
"""Inherited from VTKPythonAlgorithmBase::RequestData.
Args:
request (vtkInformation): request
inInfoVec (list[vtkInformationVector]): input objects
outInfoVec (vtkInformationVector): output objects
Returns:
int: 1 if calculation successfully ended, 0 otherwise.
"""
try:
input: vtkMultiBlockDataSet = vtkMultiBlockDataSet.GetData( inInfoVec[ 0 ] )
outputCells: vtkMultiBlockDataSet = self.GetOutputData( outInfoVec, 0 )
outputWells: vtkMultiBlockDataSet = self.GetOutputData( outInfoVec, 1 )
assert input is not None, "Input MultiBlockDataSet is null."
assert outputCells is not None, "Output volum mesh is null."
assert outputWells is not None, "Output well mesh is null."
# time controller
executive = self.GetExecutive()
if self.m_requestDataStep == 0:
# first time step
# do extraction and merge (do not display phase info)
self.m_logger.setLevel( ERROR )
outputWells0: vtkMultiBlockDataSet = vtkMultiBlockDataSet()
self.doExtractAndMerge( input, outputCells, outputWells0 )
self.m_logger.setLevel( INFO )
# save input mesh to copy later
self.m_outputT0.ShallowCopy( outputCells )
request.Set( executive.CONTINUE_EXECUTING(), 1 ) # type: ignore
if self.m_requestDataStep >= self.m_currentTimeStepIndex:
# displayed time step, no need to go further
request.Remove( executive.CONTINUE_EXECUTING() ) # type: ignore
# reinitialize requestDataStep if filter is recalled later
self.m_requestDataStep = -1
# do extraction and merge
self.doExtractAndMerge( input, outputCells, outputWells )
# copy attributes from initial time step
for (
attributeName,
attributeNewName,
) in getAttributeToTransferFromInitialTime().items():
copyAttribute( self.m_outputT0, outputCells, attributeName, attributeNewName )
# create elementCenter attribute if needed
cellCenterAttributeName: str = ( GeosMeshOutputsEnum.ELEMENT_CENTER.attributeName )
createCellCenterAttribute( outputCells, cellCenterAttributeName )
except AssertionError as e:
mess: str = "Block extraction and merge failed due to:"
self.m_logger.error( mess )
self.m_logger.error( str( e ) )
return 0
except Exception as e:
mess1: str = "Block extraction and merge failed due to:"
self.m_logger.critical( mess1 )
self.m_logger.critical( e, exc_info=True )
return 0
return 1
def doExtractAndMerge(
self: Self,
input: vtkMultiBlockDataSet,
outputCells: vtkMultiBlockDataSet,
outputWells: vtkMultiBlockDataSet,
) -> bool:
"""Apply block extraction and merge.
Args:
input (vtkMultiBlockDataSet): input multi block
outputCells (vtkMultiBlockDataSet): output volume mesh
outputWells (vtkMultiBlockDataSet): output well mesh
Returns:
bool: True if extraction and merge successfully eneded, False otherwise
"""
# extract blocks
blockExtractor: GeosBlockExtractor = GeosBlockExtractor( input, extractWells=True )
blockExtractor.applyFilter()
# recover output objects from GeosBlockExtractor filter and merge internal blocks
volumeBlockExtracted: vtkMultiBlockDataSet = blockExtractor.extractedGeosDomain.volume
assert volumeBlockExtracted is not None, "Extracted Volume mesh is null."
outputCells.ShallowCopy( self.mergeBlocksFilter( volumeBlockExtracted, False ) )
wellBlockExtracted: vtkMultiBlockDataSet = blockExtractor.extractedGeosDomain.well
assert wellBlockExtracted is not None, "Extracted Well mesh is null."
outputWells.ShallowCopy( self.mergeBlocksFilter( wellBlockExtracted, False ) )
outputCells.Modified()
outputWells.Modified()
self.m_logger.info( "Volume blocks were successfully splitted from " +
"wells, and ranks were merged together." )
return True
def mergeBlocksFilter( self: Self,
input: vtkMultiBlockDataSet,
convertSurfaces: bool = False ) -> vtkMultiBlockDataSet:
"""Apply vtk merge block filter on input multi block mesh.
Args:
input (vtkMultiBlockDataSet): multiblock mesh to merge
convertSurfaces (bool, optional): True to convert surface from vtkUnstructuredGrid to
vtkPolyData. Defaults to False.
Returns:
vtkMultiBlockDataSet: Multiblock mesh composed of internal merged blocks.
"""
mergeBlockFilter = GeosBlockMerge()
mergeBlockFilter.SetLogger( self.m_logger )
mergeBlockFilter.SetInputDataObject( input )
if convertSurfaces:
mergeBlockFilter.ConvertSurfaceMeshOn()
else:
mergeBlockFilter.ConvertSurfaceMeshOff()
mergeBlockFilter.Update()
mergedBlocks: vtkMultiBlockDataSet = mergeBlockFilter.GetOutputDataObject( 0 )
assert mergedBlocks is not None, "Final merged MultiBlockDataSet is null."
return mergedBlocks