File size: 27,585 Bytes
9d54b72 |
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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 |
import argparse
import copy
import os
import sys
import traceback
import vtkmodules.all as vtk
from thrift.TSerialization import TBinaryProtocol
from thrift.TSerialization import deserialize
from thrift.TSerialization import serialize
from python_vtk.vcellvismesh.ttypes import ChomboIndexData
from python_vtk.vcellvismesh.ttypes import FiniteVolumeIndexData
from python_vtk.vcellvismesh.ttypes import MovingBoundaryIndexData
from python_vtk.vcellvismesh.ttypes import PolyhedronFace
from python_vtk.vcellvismesh.ttypes import VisIrregularPolyhedron
from python_vtk.vcellvismesh.ttypes import VisLine
from python_vtk.vcellvismesh.ttypes import VisMesh
from python_vtk.vcellvismesh.ttypes import VisPolygon
from python_vtk.vcellvismesh.ttypes import VisTetrahedron
def writeChomboVolumeVtkGridAndIndexData(visMesh: VisMesh, domainname: str, vtkfile, indexfile) -> None:
originalVisMesh = visMesh
correctedVisMesh = originalVisMesh # same mesh if no irregularPolyhedra
if originalVisMesh.irregularPolyhedra is not None:
correctedVisMesh = copy.deepcopy(visMesh)
if correctedVisMesh.tetrahedra is None:
correctedVisMesh.tetrahedra = []
for irregularPolyhedron in correctedVisMesh.irregularPolyhedra:
tets = createTetrahedra(irregularPolyhedron, correctedVisMesh)
for tet in tets:
correctedVisMesh.tetrahedra.append(tet)
correctedVisMesh.irregularPolyhedra = None
vtkgrid: vtk.vtkUnstructuredGrid = getVolumeVtkGrid(correctedVisMesh)
writevtk(vtkgrid, vtkfile)
chomboIndexData = ChomboIndexData()
chomboIndexData.chomboVolumeIndices = []
chomboIndexData.domainName = domainname
if correctedVisMesh.dimension == 2:
if correctedVisMesh.polygons is not None:
for polygon in correctedVisMesh.polygons:
assert isinstance(polygon, VisPolygon)
chomboIndexData.chomboVolumeIndices.append(polygon.chomboVolumeIndex)
if chomboIndexData.chomboVolumeIndices is None:
print("didn't find any indices ... bad")
elif correctedVisMesh.dimension == 3:
if correctedVisMesh.visVoxels is not None:
for voxel in correctedVisMesh.visVoxels:
chomboIndexData.chomboVolumeIndices.append(voxel.chomboVolumeIndex)
if correctedVisMesh.irregularPolyhedra is not None:
raise Exception("unexpected irregular polyhedra in mesh, should have been replaced with tetrahedra")
if correctedVisMesh.tetrahedra is not None:
for tetrahedron in correctedVisMesh.tetrahedra:
assert isinstance(tetrahedron, VisTetrahedron)
chomboIndexData.chomboVolumeIndices.append(tetrahedron.chomboVolumeIndex)
if len(chomboIndexData.chomboVolumeIndices) == 0:
print("didn't find any indices ... bad")
writeChomboIndexData(indexfile, chomboIndexData)
def writeChomboMembraneVtkGridAndIndexData(visMesh: VisMesh, domainname: str, vtkfile, indexfile) -> None:
vtkgrid = getMembraneVtkGrid(visMesh)
writevtk(vtkgrid, vtkfile)
chomboIndexData = ChomboIndexData()
chomboIndexData.chomboSurfaceIndices = []
if domainname.upper().endswith("MEMBRANE") is False:
raise Exception("expecting domain name ending with membrane")
chomboIndexData.domainName = domainname
if visMesh.dimension == 3:
if visMesh.surfaceTriangles is not None:
for surfaceTriangle in visMesh.surfaceTriangles:
chomboIndexData.chomboSurfaceIndices.append(surfaceTriangle.chomboSurfaceIndex)
elif visMesh.dimension == 2:
if visMesh.visLines is not None:
for visLine in visMesh.visLines:
assert isinstance(visLine, VisLine)
chomboIndexData.chomboSurfaceIndices.append(visLine.chomboSurfaceIndex)
if len(chomboIndexData.chomboSurfaceIndices) == 0:
print("didn't find any indices ... bad")
writeChomboIndexData(indexfile, chomboIndexData)
def writeFiniteVolumeSmoothedVtkGridAndIndexData(visMesh: VisMesh, domainName: str, vtuFile, indexFile) -> None:
vtkgrid = getVolumeVtkGrid(visMesh)
if visMesh.dimension == 3:
vtkgridSmoothed = smoothUnstructuredGridSurface(vtkgrid)
else:
vtkgridSmoothed = vtkgrid
writevtk(vtkgridSmoothed, vtuFile)
finiteVolumeIndexData = FiniteVolumeIndexData()
finiteVolumeIndexData.finiteVolumeIndices = []
finiteVolumeIndexData.domainName = domainName
if visMesh.dimension == 2:
# if volume
if visMesh.polygons is not None:
for polygon in visMesh.polygons:
finiteVolumeIndexData.finiteVolumeIndices.append(polygon.finiteVolumeIndex)
# if membrane
if visMesh.visLines is not None:
for visLine in visMesh.visLines:
finiteVolumeIndexData.finiteVolumeIndices.append(visLine.finiteVolumeIndex)
elif visMesh.dimension == 3:
# if volume
if visMesh.visVoxels is not None:
for voxel in visMesh.visVoxels:
finiteVolumeIndexData.finiteVolumeIndices.append(voxel.finiteVolumeIndex)
if visMesh.irregularPolyhedra is not None:
raise Exception("unexpected irregular polyhedra in mesh, should have been replaced with tetrahedra")
if visMesh.tetrahedra is not None:
for tetrahedron in visMesh.tetrahedra:
finiteVolumeIndexData.finiteVolumeIndices.append(tetrahedron.finiteVolumeIndex)
# if membrane
if visMesh.polygons is not None:
for polygon in visMesh.polygons:
finiteVolumeIndexData.finiteVolumeIndices.append(polygon.finiteVolumeIndex)
if finiteVolumeIndexData.finiteVolumeIndices == None or len(finiteVolumeIndexData.finiteVolumeIndices) == 0:
print("didn't find any indices ... bad")
writeFiniteVolumeIndexData(indexFile, finiteVolumeIndexData)
def writeFiniteVolumeIndexData(finiteVolumeIndexFile, finiteVolumeIndexData):
assert isinstance(finiteVolumeIndexData, FiniteVolumeIndexData)
blob = serialize(finiteVolumeIndexData, protocol_factory=TBinaryProtocol.TBinaryProtocolFactory())
ff = open(finiteVolumeIndexFile,'wb')
ff.write(blob)
ff.close()
print("wrote finitevolume data to file "+str(finiteVolumeIndexFile))
def writeMovingBoundaryVolumeVtkGridAndIndexData(visMesh: VisMesh, domainName: str, vtuFile, indexFile):
vtkgrid = getVolumeVtkGrid(visMesh)
writevtk(vtkgrid, vtuFile)
movingBoundaryIndexData = MovingBoundaryIndexData()
movingBoundaryIndexData.movingBoundaryVolumeIndices = []
movingBoundaryIndexData.domainName = domainName
movingBoundaryIndexData.timeIndex = 0
if visMesh.dimension == 2:
# if volume
if visMesh.polygons is not None:
for polygon in visMesh.polygons:
movingBoundaryIndexData.movingBoundaryVolumeIndices.append(polygon.movingBoundaryVolumeIndex)
# if membrane
if visMesh.visLines is not None:
for visLine in visMesh.visLines:
movingBoundaryIndexData.movingBoundarySurfaceIndices.append(visLine.movingBoundarySurfaceIndex)
# elif visMesh.dimension == 3:
# # if volume
# if visMesh.visVoxels is not None:
# for voxel in visMesh.visVoxels:
# movingBoundaryIndexData.finiteVolumeIndices.append(voxel.finiteVolumeIndex)
# if visMesh.irregularPolyhedra is not None:
# raise Exception("unexpected irregular polyhedra in mesh, should have been replaced with tetrahedra")
# if visMesh.tetrahedra is not None:
# for tetrahedron in visMesh.tetrahedra:
# movingBoundaryIndexData.finiteVolumeIndices.append(tetrahedron.finiteVolumeIndex)
# # if membrane
# if visMesh.polygons is not None:
# for polygon in visMesh.polygons:
# movingBoundaryIndexData.finiteVolumeIndices.append(polygon.finiteVolumeIndex)
if movingBoundaryIndexData.movingBoundaryVolumeIndices == None and movingBoundaryIndexData.movingBoundarySurfaceIndices == None:
print("didn't find any indices ... bad")
if movingBoundaryIndexData.movingBoundaryVolumeIndices != None and len(movingBoundaryIndexData.movingBoundaryVolumeIndices) == 0:
print("didn't find any indices ... bad")
if movingBoundaryIndexData.movingBoundarySurfaceIndices != None and len(movingBoundaryIndexData.movingBoundarySurfaceIndices) == 0:
print("didn't find any indices ... bad")
writeMovingBoundaryIndexData(indexFile, movingBoundaryIndexData)
def writeComsolVolumeVtkGridAndIndexData(visMesh, domainName, vtuFile, indexFile):
assert isinstance(visMesh, VisMesh)
vtkgrid = getVolumeVtkGrid(visMesh)
writevtk(vtkgrid, vtuFile)
# movingBoundaryIndexData = MovingBoundaryIndexData()
# movingBoundaryIndexData.movingBoundaryVolumeIndices = []
# movingBoundaryIndexData.domainName = domainName
# movingBoundaryIndexData.timeIndex = 0
# if visMesh.dimension == 2:
# # if volume
# if visMesh.polygons is not None:
# for polygon in visMesh.polygons:
# movingBoundaryIndexData.movingBoundaryVolumeIndices.append(polygon.movingBoundaryVolumeIndex)
# # if membrane
# if visMesh.visLines is not None:
# for visLine in visMesh.visLines:
# movingBoundaryIndexData.movingBoundarySurfaceIndices.append(visLine.movingBoundarySurfaceIndex)
# elif visMesh.dimension == 3:
# # if volume
# if visMesh.visVoxels is not None:
# for voxel in visMesh.visVoxels:
# movingBoundaryIndexData.finiteVolumeIndices.append(voxel.finiteVolumeIndex)
# if visMesh.irregularPolyhedra is not None:
# raise Exception("unexpected irregular polyhedra in mesh, should have been replaced with tetrahedra")
# if visMesh.tetrahedra is not None:
# for tetrahedron in visMesh.tetrahedra:
# movingBoundaryIndexData.finiteVolumeIndices.append(tetrahedron.finiteVolumeIndex)
# # if membrane
# if visMesh.polygons is not None:
# for polygon in visMesh.polygons:
# movingBoundaryIndexData.finiteVolumeIndices.append(polygon.finiteVolumeIndex)
# if movingBoundaryIndexData.movingBoundaryVolumeIndices == None and movingBoundaryIndexData.movingBoundarySurfaceIndices == None:
# print "didn't find any indices ... bad"
#
# if movingBoundaryIndexData.movingBoundaryVolumeIndices != None and len(movingBoundaryIndexData.movingBoundaryVolumeIndices) == 0:
# print "didn't find any indices ... bad"
#
# if movingBoundaryIndexData.movingBoundarySurfaceIndices != None and len(movingBoundaryIndexData.movingBoundarySurfaceIndices) == 0:
# print "didn't find any indices ... bad"
#
#writeMovingBoundaryIndexData(indexFile, None)
def writeMovingBoundaryIndexData(movingBoundaryIndexFile, movingBoundaryIndexData):
assert isinstance(movingBoundaryIndexData, MovingBoundaryIndexData)
blob = serialize(movingBoundaryIndexData, protocol_factory=TBinaryProtocol.TBinaryProtocolFactory())
ff = open(movingBoundaryIndexFile,'wb')
ff.write(blob)
ff.close()
print("wrote movingboundary data to file "+str(movingBoundaryIndexFile))
def writeChomboIndexData(chomboIndexFile, chomboIndexData):
"""
Returns:
None:
"""
assert isinstance(chomboIndexData, ChomboIndexData)
blob = serialize(chomboIndexData, protocol_factory=TBinaryProtocol.TBinaryProtocolFactory())
ff = open(chomboIndexFile,'wb')
ff.write(blob)
ff.close()
print("wrote chomboIndex data to file "+str(chomboIndexFile))
#
# read a vtkUnstructuredGrid from the XML format
#
def readvtk(vtkfile):
if not os.path.isfile(vtkfile):
raise Exception("unstructured grid " + str(vtkfile) + " not found")
tester = vtk.vtkXMLFileReadTester()
tester.SetFileName(str(vtkfile))
if tester.TestReadFile() != 1:
raise Exception("expecting XML formatted VTK unstructured grid")
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName(vtkfile)
reader.Update()
vtkgrid = reader.GetOutput()
assert isinstance(vtkgrid, vtk.vtkUnstructuredGrid)
print("read from file " + str(vtkfile))
vtkgrid.BuildLinks()
return vtkgrid
#
# write a vtkUnstructuredGrid to the XML format
#
def writevtk(vtkgrid, filename):
writer = vtk.vtkXMLUnstructuredGridWriter()
bASCII = False
if bASCII:
writer.SetDataModeToAscii()
else:
writer.SetCompressorTypeToNone()
writer.SetDataModeToBinary()
try:
writer.SetInputData(vtkgrid)
except AttributeError:
writer.SetInput(vtkgrid)
writer.SetFileName(filename)
writer.Update()
print("wrote to file "+str(filename))
#
# create a single-variable vtu file
#
def writeDataArrayToNewVtkFile(emptyMeshFile, varName, data, newMeshFile):
assert type(emptyMeshFile) is str
assert type(varName) is str
assert type(newMeshFile) is str
try:
#raise ImportError("dummy exception")
import numpy as np
from vtk.util import numpy_support
print("writing varData using numpy")
data = np.array(data)
vtkgrid = readvtk(emptyMeshFile)
assert isinstance(vtkgrid, vtk.vtkUnstructuredGrid)
#
# add cell data array to the empty mesh for this variable
#
dataArray = vtk.vtkDoubleArray()
dataArray = numpy_support.numpy_to_vtk(data)
assert isinstance(dataArray, )
dataArray.SetName(varName)
cellData: vtk.vtkCellData = vtkgrid.GetCellData()
cellData.AddArray(dataArray)
#
# write mesh and data to the file for that domain and time
#
writevtk(vtkgrid, newMeshFile)
except ImportError as nonumpy:
import array
print("writing varData using array package")
print(type(data))
print(str(data))
data = array.array('d', data)
vtkgrid = readvtk(emptyMeshFile)
#
# add cell data array to the empty mesh for this variable
#
dataArray = vtk.vtkDoubleArray()
dataArray.SetVoidArray(data, len(data), 1)
dataArray.SetNumberOfComponents(1)
dataArray.SetName(varName)
cellData: vtk.vtkCellData = vtkgrid.GetCellData()
cellData.AddArray(dataArray)
#
# write mesh and data to the file for that domain and time
#
writevtk(vtkgrid, newMeshFile)
def getMembraneVtkGrid(visMesh: VisMesh) -> vtk.vtkUnstructuredGrid:
vtkpoints = vtk.vtkPoints()
for visPoint in visMesh.surfacePoints:
vtkpoints.InsertNextPoint(visPoint.x,visPoint.y,visPoint.z)
vtkgrid = vtk.vtkUnstructuredGrid()
vtkgrid.Allocate(len(visMesh.surfacePoints), len(visMesh.surfacePoints))
vtkgrid.SetPoints(vtkpoints)
if visMesh.dimension == 2:
vtkline = vtk.vtkLine()
lineType = vtkline.GetCellType()
for line in visMesh.visLines:
pts = vtk.vtkIdList()
pts.InsertNextId(line.p1)
pts.InsertNextId(line.p2)
vtkgrid.InsertNextCell(lineType, pts)
else:
vtktriangle = vtk.vtkTriangle()
triangleType = vtktriangle.GetCellType()
for surfaceTriangle in visMesh.surfaceTriangles:
pts = vtk.vtkIdList()
for pi in surfaceTriangle.pointIndices:
pts.InsertNextId(pi)
# each triangle is a cell
vtkgrid.InsertNextCell(triangleType, pts)
vtkgrid.BuildLinks()
return vtkgrid
def getVolumeVtkGrid(visMesh: VisMesh) -> vtk.vtkUnstructuredGrid:
bClipPolyhedra = True
vtkpoints = vtk.vtkPoints()
for visPoint in visMesh.points:
vtkpoints.InsertNextPoint(visPoint.x, visPoint.y, visPoint.z)
vtkgrid = vtk.vtkUnstructuredGrid()
vtkgrid.Allocate(len(visMesh.points), len(visMesh.points))
vtkgrid.SetPoints(vtkpoints)
quadType = vtk.vtkQuad().GetCellType()
# lineType = vtk.vtkLine().GetCellType()
polygonType = vtk.vtkPolygon().GetCellType()
polyhedronType = vtk.vtkPolyhedron().GetCellType()
triangleType = vtk.vtkTriangle().GetCellType()
voxelType = vtk.vtkVoxel().GetCellType()
tetraType = vtk.vtkTetra().GetCellType()
if visMesh.polygons != None:
for visPolygon in visMesh.polygons:
pts = vtk.vtkIdList()
polygonPoints = visPolygon.pointIndices
for p in polygonPoints:
pts.InsertNextId(p)
numPoints = len(polygonPoints)
if numPoints == 4:
vtkgrid.InsertNextCell(quadType, pts)
elif numPoints == 3:
vtkgrid.InsertNextCell(triangleType, pts)
else:
vtkgrid.InsertNextCell(polygonType, pts)
#
# replace any VisIrregularPolyhedron with a list of VisTetrahedron
#
if visMesh.visVoxels != None:
for voxel in visMesh.visVoxels:
pts = vtk.vtkIdList()
polyhedronPoints = voxel.pointIndices
for p in polyhedronPoints:
pts.InsertNextId(p)
vtkgrid.InsertNextCell(voxelType, pts)
if visMesh.tetrahedra != None:
for visTet in visMesh.tetrahedra:
assert isinstance(visTet, VisTetrahedron)
pts = vtk.vtkIdList()
tetPoints = visTet.pointIndices
for p in tetPoints:
pts.InsertNextId(p)
vtkgrid.InsertNextCell(tetraType, pts)
bInitializedFaces = False
if visMesh.irregularPolyhedra != None:
for clippedPolyhedron in visMesh.irregularPolyhedra:
if bClipPolyhedra == True:
tets = createTetrahedra(clippedPolyhedron, visMesh)
for visTet in tets:
pts = vtk.vtkIdList()
tetPoints = visTet.getPointIndices()
for p in tetPoints:
pts.InsertNextId(p)
vtkgrid.InsertNextCell(tetraType, pts)
else:
faceStreamList = vtk.vtkIdList()
faceStream = getVtkFaceStream(clippedPolyhedron)
for p in faceStream:
faceStreamList.InsertNextId(p)
if bInitializedFaces == False and vtkgrid.GetNumberOfCells() > 0:
vtkgrid.InitializeFacesRepresentation(vtkgrid.GetNumberOfCells())
bInitializedFaces = True
vtkgrid.InsertNextCell(polyhedronType, faceStreamList)
vtkgrid.BuildLinks()
# vtkgrid.Squeeze()
return vtkgrid
def getVtkFaceStream(irregularPolyhedron: VisIrregularPolyhedron) -> list[int]:
faceStream = [len(irregularPolyhedron.polyhedronFaces), ]
for polyhedronFace in irregularPolyhedron.polyhedronFaces:
faceStream.append(len(polyhedronFace.getVertices()))
for v in polyhedronFace.vertices:
faceStream.append(v)
intFaceStream = [int(v) for v in faceStream]
return intFaceStream
def smoothUnstructuredGridSurface(vtkGrid: vtk.vtkUnstructuredGrid) -> vtk.vtkUnstructuredGrid:
ugGeometryFilter = vtk.vtkUnstructuredGridGeometryFilter()
ugGeometryFilter.PassThroughPointIdsOn()
ugGeometryFilter.MergingOff()
try:
ugGeometryFilter.SetInputData(vtkGrid)
except AttributeError:
ugGeometryFilter.SetInput(vtkGrid)
ugGeometryFilter.Update()
surfaceUnstructuredGrid: vtk.vtkUnstructuredGrid = ugGeometryFilter.GetOutput()
originalPointsIdsName = ugGeometryFilter.GetOriginalPointIdsName()
cellData = surfaceUnstructuredGrid.GetCellData()
numCellArrays = cellData.GetNumberOfArrays()
for i in range(0, numCellArrays):
cellArrayName = cellData.GetArrayName(i)
print("CellArray(" + str(i) + ") '" + cellArrayName + "')")
pointData: vtk.vtkPointData = surfaceUnstructuredGrid.GetPointData()
numPointArrays = pointData.GetNumberOfArrays()
for i in range(0, numPointArrays):
pointArrayName = pointData.GetArrayName(i)
print("PointArray(" + str(i) + ") '" + pointArrayName + "'")
geometryFilter = vtk.vtkGeometryFilter()
try:
geometryFilter.SetInputData(surfaceUnstructuredGrid)
except AttributeError:
geometryFilter.SetInput(surfaceUnstructuredGrid)
geometryFilter.Update()
polyData: vtk.vtkPolyData = geometryFilter.GetOutput()
filter = vtk.vtkWindowedSincPolyDataFilter()
try:
filter.SetInputData(polyData)
except AttributeError:
filter.SetInput(polyData)
filter.SetNumberOfIterations(15)
filter.BoundarySmoothingOff()
filter.FeatureEdgeSmoothingOff()
filter.SetFeatureAngle(120.0)
filter.SetPassBand(0.001)
filter.NonManifoldSmoothingOff()
filter.NormalizeCoordinatesOn()
filter.Update()
smoothedPolydata = filter.GetOutput()
smoothedPoints: vtk.vtkPoints = smoothedPolydata.GetPoints()
smoothedPointData: vtk.vtkPointData = smoothedPolydata.GetPointData()
pointIdsArray: vtk.vtkIdTypeArray = smoothedPointData.GetArray(originalPointsIdsName)
pointsIdsArraySize = pointIdsArray.GetSize()
origPoints = vtkGrid.GetPoints()
for i in range(0, pointsIdsArraySize):
pointId = pointIdsArray.GetValue(i)
smoothedPoint = smoothedPoints.GetPoint(i)
origPoints.SetPoint(pointId, smoothedPoint)
return vtkGrid
def getPointIndices(irregularPolyhedron: VisIrregularPolyhedron) -> list[int]:
assert isinstance(irregularPolyhedron, VisIrregularPolyhedron)
pointIndicesSet = set()
for face in irregularPolyhedron.polyhedronFaces:
assert(isinstance(face, PolyhedronFace))
for pointIndex in face.vertices:
pointIndicesSet.add(pointIndex)
pointArray = [int(x) for x in pointIndicesSet]
return pointArray
def createTetrahedra(clippedPolyhedron: VisIrregularPolyhedron, visMesh: VisMesh):
vtkpolydata = vtk.vtkPolyData()
vtkpoints = vtk.vtkPoints()
polygonType = vtk.vtkPolygon().GetCellType()
uniquePointIndices = getPointIndices(clippedPolyhedron)
for point in uniquePointIndices:
visPoint = visMesh.points[point]
vtkpoints.InsertNextPoint(visPoint.x, visPoint.y, visPoint.z)
vtkpolydata.Allocate(100, 100)
vtkpolydata.SetPoints(vtkpoints)
for face in clippedPolyhedron.polyhedronFaces:
faceIdList = vtk.vtkIdList()
for visPointIndex in face.vertices:
vtkpointid = -1
for i in range(0, len(uniquePointIndices)):
if uniquePointIndices[i] == visPointIndex:
vtkpointid = i
faceIdList.InsertNextId(vtkpointid)
vtkpolydata.InsertNextCell(polygonType, faceIdList)
delaunayFilter = vtk.vtkDelaunay3D()
try:
delaunayFilter.SetInputData(vtkpolydata)
except AttributeError:
delaunayFilter.SetInput(vtkpolydata)
delaunayFilter.Update()
delaunayFilter.SetAlpha(0.1)
vtkgrid2: vtk.vtkUnstructuredGrid = delaunayFilter.GetOutput()
assert isinstance(vtkgrid2, vtk.vtkUnstructuredGrid) # runtime check, remove later
visTets = []
numTets = vtkgrid2.GetNumberOfCells()
if numTets < 1:
if len(uniquePointIndices)==4:
visTet = VisTetrahedron(uniquePointIndices)
visTet.chomboVolumeIndex = clippedPolyhedron.chomboVolumeIndex
visTet.finiteVolumeIndex = clippedPolyhedron.finiteVolumeIndex
visTets.append(visTet)
print("made trivial tet ... maybe inside out")
else:
print("found no tets, there are "+str(len(uniquePointIndices))+" unique point indices")
# print("numFaces = "+str(vtkpolydata.GetNumberOfCells())+", numTets = "+str(numTets));
for cellIndex in range(0, numTets):
cell = vtkgrid2.GetCell(cellIndex)
if isinstance(cell, vtk.vtkTetra):
vtkTet: vtk.vtkTetra = cell
tetPointIds: vtk.vtkIdList = vtkTet.GetPointIds()
assert isinstance(tetPointIds, vtk.vtkIdList)
#
# translate from vtkgrid pointids to visMesh point ids
#
numPoints = tetPointIds.GetNumberOfIds()
visPointIds = []
for p in range(0, numPoints):
visPointIds.append(uniquePointIndices[tetPointIds.GetId(p)])
visTet = VisTetrahedron(visPointIds)
if clippedPolyhedron.chomboVolumeIndex != None:
visTet.chomboVolumeIndex = clippedPolyhedron.chomboVolumeIndex
if clippedPolyhedron.finiteVolumeIndex != None:
visTet.finiteVolumeIndex = clippedPolyhedron.finiteVolumeIndex
visTets.append(visTet)
else:
print("ChomboMeshMapping.createTetrahedra(): expecting a tet, found a " + cell.__type__)
return visTets
def main():
# sys.setrecursionlimit(100000)
try:
parser = argparse.ArgumentParser()
list_of_meshtypes = ["chombovolume", "chombomembrane", "finitevolume", "movingboundary", "comsolvolume"]
parser.add_argument("meshtype", help="type of visMesh processing required and index file generated", choices=list_of_meshtypes)
parser.add_argument("domainname", help="domain name for output mesh")
parser.add_argument("vismeshfile", help="filename of input visMesh to be processed (thrift serialization via TBinaryProtocol)")
parser.add_argument("vtkfile", help="filename of output vtk mesh (VTK XML unstructured grid")
parser.add_argument("indexfile", help="filename of output ChomboIndexData or FiniteVolumeIndexData (thrift serialization via TBinaryProtocol)")
args = parser.parse_args()
f_vismesh = open(args.vismeshfile, "rb")
blob_vismesh = f_vismesh.read()
print("read "+str(len(blob_vismesh))+" bytes from "+args.vismeshfile)
f_vismesh.close()
visMesh = VisMesh()
protocol_factory = TBinaryProtocol.TBinaryProtocolFactory
# deserialize(visMesh, blob_vismesh, protocol_factory = protocol_factory())
print("starting deserialization")
deserialize(visMesh, blob_vismesh, protocol_factory=protocol_factory())
print("done with deserialization")
if args.meshtype == "chombovolume":
writeChomboVolumeVtkGridAndIndexData(visMesh, args.domainname, args.vtkfile, args.indexfile)
elif args.meshtype == "chombomembrane":
writeChomboMembraneVtkGridAndIndexData(visMesh, args.domainname, args.vtkfile, args.indexfile)
elif args.meshtype == "finitevolume":
writeFiniteVolumeSmoothedVtkGridAndIndexData(visMesh, args.domainname, args.vtkfile, args.indexfile)
elif args.meshtype == "movingboundary":
writeMovingBoundaryVolumeVtkGridAndIndexData(visMesh, args.domainname, args.vtkfile, args.indexfile)
elif args.meshtype == "comsolvolume":
writeComsolVolumeVtkGridAndIndexData(visMesh, args.domainname, args.vtkfile, args.indexfile)
else:
raise Exception("meshtype "+str(args.meshtype)+" not supported")
except:
e_info = sys.exc_info()
traceback.print_exception(e_info[0], e_info[1], e_info[2], file=sys.stdout)
sys.stderr.write("exception: "+str(e_info[0])+": "+str(e_info[1])+"\n")
sys.stderr.flush()
sys.exit(-1)
else:
sys.exit(0)
if __name__ == '__main__':
main()
|