DAMASK_EICMD/processing/post/vtk_rectilinearGrid.py

140 lines
4.9 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import os
import sys
from optparse import OptionParser
import vtk
import numpy as np
import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0]
scriptID = ' '.join([scriptName,damask.version])
# --------------------------------------------------------------------
# MAIN
# --------------------------------------------------------------------
2019-02-16 22:11:56 +05:30
parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [ASCIItable(s)]', description = """
2016-04-25 12:10:36 +05:30
Create regular voxel grid from points in an ASCIItable.
""", version = scriptID)
parser.add_option('-m',
'--mode',
dest = 'mode',
2016-05-13 12:58:54 +05:30
metavar='string',
type = 'choice', choices = ['cell','point'],
2016-04-23 00:50:36 +05:30
help = 'cell-centered or point-centered coordinates')
parser.add_option('-p',
'--pos', '--position',
dest = 'pos',
type = 'string', metavar = 'string',
2016-04-23 00:50:36 +05:30
help = 'label of coordinates [%default]')
parser.set_defaults(mode = 'cell',
pos = 'pos',
)
(options, filenames) = parser.parse_args()
# --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None]
for name in filenames:
try: table = damask.ASCIItable(name = name,
buffered = False,
2016-04-25 12:10:36 +05:30
labeled = True,
readonly = True,
)
except: continue
damask.util.report(scriptName,name)
# --- interpret header ----------------------------------------------------------------------------
table.head_read()
remarks = []
errors = []
2016-04-25 12:10:36 +05:30
coordDim = table.label_dimension(options.pos)
if not 3 >= coordDim >= 1: errors.append('coordinates "{}" need to have one, two, or three dimensions.'.format(options.pos))
elif coordDim < 3: remarks.append('appending {} dimension{} to coordinates "{}"...'.format(3-coordDim,
's' if coordDim < 2 else '',
options.pos))
if remarks != []: damask.util.croak(remarks)
if errors != []:
damask.util.croak(errors)
table.close(dismiss=True)
continue
# --------------- figure out size and grid ---------------------------------------------------------
2016-04-25 12:10:36 +05:30
table.data_readArray(options.pos)
if table.data.shape[1] < 3:
table.data = np.hstack((table.data,
np.zeros((table.data.shape[0],
3-table.data.shape[1]),dtype='f'))) # fill coords up to 3D with zeros
2016-10-25 00:46:29 +05:30
coords = [np.unique(table.data[:,i]) for i in range(3)]
2016-04-25 12:10:36 +05:30
if options.mode == 'cell':
coords = [0.5 * np.array([3.0 * coords[i][0] - coords[i][0 + int(len(coords[i]) > 1)]] + \
2016-10-25 00:46:29 +05:30
[coords[i][j-1] + coords[i][j] for j in range(1,len(coords[i]))] + \
[3.0 * coords[i][-1] - coords[i][-1 - int(len(coords[i]) > 1)]]) for i in range(3)]
grid = np.array(list(map(len,coords)),'i')
2016-04-25 12:10:36 +05:30
N = grid.prod() if options.mode == 'point' else (grid-1).prod()
2016-04-25 12:10:36 +05:30
if N != len(table.data):
errors.append('data count {} does not match grid {}x{}x{}.'.format(N,*(grid - (options.mode == 'cell')) ))
if errors != []:
damask.util.croak(errors)
table.close(dismiss = True)
continue
# ------------------------------------------ process data ---------------------------------------
rGrid = vtk.vtkRectilinearGrid()
coordArray = [vtk.vtkDoubleArray(),
vtk.vtkDoubleArray(),
vtk.vtkDoubleArray(),
]
rGrid.SetDimensions(*grid)
for i,points in enumerate(coords):
for point in points:
coordArray[i].InsertNextValue(point)
rGrid.SetXCoordinates(coordArray[0])
rGrid.SetYCoordinates(coordArray[1])
rGrid.SetZCoordinates(coordArray[2])
# ------------------------------------------ output result ---------------------------------------
if name:
writer = vtk.vtkXMLRectilinearGridWriter()
writer.SetCompressorTypeToZLib()
writer.SetDataModeToBinary()
writer.SetFileName(os.path.join(os.path.split(name)[0],
os.path.splitext(os.path.split(name)[1])[0] +
2016-04-25 12:10:36 +05:30
'_{}({})'.format(options.pos, options.mode) +
'.' + writer.GetDefaultFileExtension()))
else:
writer = vtk.vtkDataSetWriter()
writer.SetHeader('# powered by '+scriptID)
writer.WriteToOutputStringOn()
writer.SetInputData(rGrid)
writer.Write()
2019-05-27 12:04:36 +05:30
if name is None: sys.stdout.write(writer.GetOutputString())
table.close()