now works with recent changes of ASCIItable and with STDIN to STDOUT.

This commit is contained in:
Philip Eisenlohr 2015-08-24 14:01:24 +00:00
parent afc88c7029
commit c215139ce1
1 changed files with 85 additions and 130 deletions

View File

@ -9,21 +9,6 @@ import damask
scriptID = '$Id$' scriptID = '$Id$'
scriptName = os.path.splitext(scriptID.split()[1])[0] scriptName = os.path.splitext(scriptID.split()[1])[0]
synonyms = {
'grid': ['resolution'],
'size': ['dimension'],
}
identifiers = {
'grid': ['a','b','c'],
'size': ['x','y','z'],
'origin': ['x','y','z'],
}
mappings = {
'grid': lambda x: int(x),
'size': lambda x: float(x),
'origin': lambda x: float(x),
'microstructures': lambda x: int(x),
}
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# MAIN # MAIN
@ -34,138 +19,96 @@ Create hexahedral voxels around points in an ASCIItable.
""", version = scriptID) """, version = scriptID)
parser.add_option('-p', '--positions', dest='pos', type='string', metavar = 'string', parser.add_option('-p', '--positions',
dest = 'position',
type = 'string', metavar = 'string',
help = 'coordinate label [%default]') help = 'coordinate label [%default]')
parser.add_option('-s', '--size', dest='size', type='float', nargs=3, metavar = 'float float float', parser.add_option('-s', '--size',
dest = 'size',
type = 'float', nargs = 3, metavar = 'float float float',
help = 'x,y,z size of voxel') help = 'x,y,z size of voxel')
parser.add_option('-o', '--origin', dest='origin', type='float', nargs=3, metavar = 'float float float', parser.add_option('-o', '--origin',
dest = 'origin',
type = 'float', nargs = 3, metavar = 'float float float',
help = 'x,y,z origin of coordinate system') help = 'x,y,z origin of coordinate system')
parser.add_option('-g', '--geom', dest='geom', action='store_true', parser.add_option('-g', '--geom',
help = 'derive geometry from geom-file header information') dest = 'geom', action='store_true',
parser.set_defaults(pos = 'pos') help = 'derive geometry from geom-file header information [%default]')
parser.set_defaults(origin = (0.0,0.0,0.0)) parser.set_defaults(position = 'pos',
parser.set_defaults(geom = False) origin = (0.0,0.0,0.0),
geom = False,
)
(options, filenames) = parser.parse_args() (options, filenames) = parser.parse_args()
if options.size == None and not options.geom: if options.size == None and not options.geom:
parser.error('no size sprecified.') parser.error('no size specified.')
datainfo = { # list of requested labels per datatype # --- loop over input files -------------------------------------------------------------------------
'vector': {'len':3,
'label':[]},
}
if options.pos != None: datainfo['vector']['label'] += [options.pos] if filenames == []: filenames = [None]
# ------------------------------------------ setup file handles ---------------------------------------
files = []
for name in filenames: for name in filenames:
if os.path.exists(name): try:
files.append({'name':name, 'input':open(name), 'output':os.path.splitext(name)[0]+'.vtu', 'croak':sys.stderr}) table = damask.ASCIItable(name = name,
buffered = False, readonly = True)
except: continue
table.croak(damask.util.emph(scriptName)+(': '+name if name else ''))
#--- loop over input files ------------------------------------------------------------------------ # --- interpret header ----------------------------------------------------------------------------
for file in files:
if file['name'] != 'STDIN': file['croak'].write('\033[1m'+scriptName+'\033[0m: '+file['name']+'\n')
else: file['croak'].write('\033[1m'+scriptName+'\033[0m\n')
table = damask.ASCIItable(file['input'],file['croak'],False) # make unbuffered ASCII_table
table.head_read() # read ASCII header info
#--- interpret header ----------------------------------------------------------------------------
info = {
'grid': np.zeros(3,'i'),
'size': np.zeros(3,'d'),
'origin': np.zeros(3,'d'),
'homogenization': 0,
'microstructures': 0,
}
table.head_read()
if options.geom: if options.geom:
for header in table.info: info,extra_header = table.head_getGeom()
headitems = map(str.lower,header.split())
if len(headitems) == 0: continue table.croak(['grid a b c: %s'%(' x '.join(map(str,info['grid']))),
for synonym,alternatives in synonyms.iteritems(): 'size x y z: %s'%(' x '.join(map(str,info['size']))),
if headitems[0] in alternatives: headitems[0] = synonym 'origin x y z: %s'%(' : '.join(map(str,info['origin']))),
if headitems[0] in mappings.keys(): 'homogenization: %i'%info['homogenization'],
if headitems[0] in identifiers.keys(): 'microstructures: %i'%info['microstructures'],
for i in xrange(len(identifiers[headitems[0]])): ])
info[headitems[0]][i] = \
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
else:
info[headitems[0]] = mappings[headitems[0]](headitems[1])
file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,info['grid']))) + \
'size x y z: %s\n'%(' x '.join(map(str,info['size']))) + \
'origin x y z: %s\n'%(' : '.join(map(str,info['origin']))) + \
'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n'%info['microstructures'])
if np.any(info['grid'] < 1):
file['croak'].write('invalid grid a b c.\n')
continue
if np.any(info['size'] <= 0.0):
file['croak'].write('invalid size x y z.\n')
continue
else: else:
info = {}
info['size'] = np.ones(3) info['size'] = np.ones(3)
info['grid'] = info['size'] / options.size info['grid'] = info['size'] / options.size
info['origin'] = options.origin info['origin'] = options.origin
# --------------- figure out columns to process errors = []
active = {} if table.label_dimension(options.position) != 3: errors.append('columns "{}" have dimension {}'.format(options.position,
column = {} table.label_dimension(options.position)))
head = [] if np.any(info['grid'] < 1): errors.append('invalid grid a b c.')
if np.any(info['size'] <= 0.0): errors.append('invalid size x y z.')
for datatype,infos in datainfo.items(): if errors != []:
for label in infos['label']: table.croak(errors)
foundIt = False table.close(dismiss = True)
for key in ['1_'+label,label]: continue
if key in table.labels:
foundIt = True
if datatype not in active: active[datatype] = []
if datatype not in column: column[datatype] = {}
active[datatype].append(label)
column[datatype][label] = table.labels.index(key) # remember columns of requested data
if not foundIt:
file['croak'].write('column %s not found...\n'%label)
break
# ------------------------------------------ process data --------------------------------------- # ------------------------------------------ process data ---------------------------------------
hexPoints = np.array([[-1,-1,-1], table.data_readArray(options.position)
[ 1,-1,-1],
[ 1, 1,-1],
[-1, 1,-1],
[-1,-1, 1],
[ 1,-1, 1],
[ 1, 1, 1],
[-1, 1, 1],
])
Points = vtk.vtkPoints()
Hex = vtk.vtkHexahedron()
uGrid = vtk.vtkUnstructuredGrid()
table.data_readArray(range(column['vector'][options.pos],\
column['vector'][options.pos]+datainfo['vector']['len']))
table.data[:,0:3] *= info['size'] table.data[:,0:3] *= info['size']
table.data[:,0:3] += info['origin'] table.data[:,0:3] += info['origin']
# minD = np.array(options.size,dtype=float) hexPoints = np.array([[-1,-1,-1],
# for i in xrange(3): [ 1,-1,-1],
# coords = np.unique(table.data[:,i]) [ 1, 1,-1],
# minD[i] = coords[-1]-coords[0] [-1, 1,-1],
# for j in xrange(len(coords)-1): [-1,-1, 1],
# d = coords[j+1]-coords[j] [ 1,-1, 1],
# if d < minD[i]: [ 1, 1, 1],
# minD[i] = d [-1, 1, 1],
])
halfDelta = 0.5*info['size']/info['grid']
Points = vtk.vtkPoints()
Hex = vtk.vtkHexahedron()
uGrid = vtk.vtkUnstructuredGrid()
for p in table.data: for p in table.data:
for i,h in enumerate(hexPoints): for i,h in enumerate(hexPoints):
id = Points.InsertNextPoint(p+h*info['size']/info['grid']/2.) id = Points.InsertNextPoint(p+h*halfDelta)
Hex.GetPointIds().SetId(i,id) Hex.GetPointIds().SetId(i,id)
uGrid.InsertNextCell(Hex.GetCellType(), Hex.GetPointIds()) uGrid.InsertNextCell(Hex.GetCellType(), Hex.GetPointIds())
@ -174,14 +117,26 @@ for file in files:
# ------------------------------------------ output result --------------------------------------- # ------------------------------------------ output result ---------------------------------------
writer = vtk.vtkXMLUnstructuredGridWriter() if name:
writer.SetDataModeToBinary() (dir,filename) = os.path.split(name)
writer.SetCompressorTypeToZLib() writer = vtk.vtkXMLUnstructuredGridWriter()
writer.SetFileName(file['output']) writer.SetDataModeToBinary()
if vtk.VTK_MAJOR_VERSION <= 5: writer.SetCompressorTypeToZLib()
writer.SetInput(uGrid) writer.SetFileName(os.path.join(dir,os.path.splitext(filename)[0]+'_{}'.format(options.position) \
else: +'.'+writer.GetDefaultFileExtension()))
writer.SetInputData(uGrid) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(uGrid)
writer.Write() else: writer.SetInputData(uGrid)
writer.Write()
else:
writer = vtk.vtkUnstructuredGridWriter()
writer.WriteToOutputStringOn()
writer.SetFileTypeToASCII()
writer.SetHeader('# powered by '+scriptID)
if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(uGrid)
else: writer.SetInputData(uGrid)
writer.Write()
sys.stdout.write(writer.GetOutputString()[0:writer.GetOutputStringLength()])
table.close() # close input ASCII table
table.input_close() # close input ASCII table