geom_check is now using vtk class, other scripts stop execution in case of invalid grid or size

This commit is contained in:
Martin Diehl 2013-05-14 21:09:37 +00:00
parent 9093cf2072
commit 0b4a5cfa9b
9 changed files with 146 additions and 161 deletions

View File

@ -81,7 +81,11 @@ file = {'name':'STDIN',
}
if numpy.any(options.grid < 2):
file['croak'].write('grid too low...\n')
file['croak'].write('grid too small...\n')
sys.exit()
if numpy.any(options.size <= 0.0):
file['croak'].write('size too small...\n')
sys.exit()
options.omega *= math.pi/180.0 # rescale ro radians
@ -135,6 +139,13 @@ file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,info['grid'])))
'homogenization: %i\n'%info['homogenization'])
file['croak'].write("bounding box: %s\n"%(numpy.sqrt(numpy.sum(box*box,0))))
if numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
# -------------------------------------- switch according to task ----------------------------------
formatwidth = 1+int(math.floor(math.log10(info['microstructures']-1)))
if options.config:

View File

@ -1,12 +1,12 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,string,re,numpy
import os,sys,string,re,numpy,vtk
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
# -----------------------------
#--------------------------------------------------------------------------------------------------
class extendedOption(Option):
# -----------------------------
#--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments
# taken from online tutorial http://docs.python.org/library/optparse.html
@ -23,74 +23,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser)
def outStdout(cmd,locals):
if cmd[0:3] == '(!)':
exec(cmd[3:])
elif cmd[0:3] == '(?)':
cmd = eval(cmd[3:])
print cmd
else:
print cmd
return
def outFile(cmd,locals):
if cmd[0:3] == '(!)':
exec(cmd[3:])
elif cmd[0:3] == '(?)':
cmd = eval(cmd[3:])
locals['filepointer'].write(cmd+'\n')
else:
locals['filepointer'].write(cmd+'\n')
return
def output(cmds,locals,dest):
for cmd in cmds:
if isinstance(cmd,list):
output(cmd,locals,dest)
else:
{\
'File': outFile,\
'Stdout': outStdout,\
}[dest](str(cmd),locals)
return
# +++++++++++++++++++++++++++++++++++++++++++++++++++
def vtk_writeASCII_mesh(dim,res,origin,data):
# +++++++++++++++++++++++++++++++++++++++++++++++++++
""" function writes data array defined on a rectilinear grid """
N = res[0]*res[1]*res[2]
cmds = [\
'# vtk DataFile Version 3.1',
string.replace('powered by $Id$','\n','\\n'),
'ASCII',
'DATASET RECTILINEAR_GRID',
'DIMENSIONS %i %i %i'%(res[0]+1,res[1]+1,res[2]+1),
'X_COORDINATES %i float'%(res[0]+1),
' '.join(map(str,[i*dim[0]/res[0]+origin[0] for i in range(res[0]+1)])),
'Y_COORDINATES %i float'%(res[1]+1),
' '.join(map(str,[i*dim[1]/res[1]+origin[1] for i in range(res[1]+1)])),
'Z_COORDINATES %i float'%(res[2]+1),
' '.join(map(str,[i*dim[2]/res[2]+origin[2] for i in range(res[2]+1)])),
'CELL_DATA %i'%N,
]
for datatype in data:
for item in data[datatype]:
cmds += [\
'%s %s float'%(datatype.upper()+{True:'',False:'S'}[datatype.lower().endswith('s')],item),
'LOOKUP_TABLE default',
[[['\t'.join(map(str,data[datatype][item][:,j,k]))] for j in range(res[1])] for k in range(res[2])]
]
return cmds
# ----------------------- MAIN -------------------------------
#--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
identifiers = {
'grid': ['a','b','c'],
'size': ['x','y','z'],
@ -112,8 +47,7 @@ Produce VTK rectilinear mesh of structure data from geom description
(options, filenames) = parser.parse_args()
# ------------------------------------------ setup file handles ---------------------------------------
#--- setup file handles --------------------------------------------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN',
@ -128,13 +62,10 @@ else:
'croak':sys.stdout,
})
# ------------------------------------------ loop over input files ---------------------------------------
#--- loop over input files ------------------------------------------------------------------------
for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n')
# get labels by either read the first row, or - if keyword header is present - the last line of the header
firstline = file['input'].readline()
m = re.search('(\d+)\s*head', firstline.lower())
if m:
@ -147,11 +78,13 @@ for file in files:
content = file['input'].readlines()
file['input'].close()
info = {'grid': [0,0,0],
'size': [0.0,0.0,0.0],
'origin': [0.0,0.0,0.0],
'homogenization': 0,
#--- interprete header ----------------------------------------------------------------------------
info = {
'grid': numpy.zeros(3,'i'),
'size': numpy.zeros(3,'d'),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'homogenization': 0
}
for header in headers:
@ -166,36 +99,56 @@ for file in files:
else:
info[headitems[0]] = mappings[headitems[0]](headitems[1])
if numpy.all(info['grid'] == 0):
file['croak'].write('no grid info found.\n')
continue
if numpy.all(info['size'] == 0.0):
file['croak'].write('no size info found.\n')
continue
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'])
data = {'scalar':{'structure':numpy.zeros(info['grid'],'i')}}
i = 0
if numpy.all(any['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
#--- generate grid --------------------------------------------------------------------------------
grid = vtk.vtkRectilinearGrid()
grid.SetDimensions([x+1 for x in info['grid']])
temp = vtk.vtkDoubleArray()
for i in xrange(3):
temp.SetNumberOfTuples(info['grid'][i]+1)
for j in range(info['grid'][i]+1):
temp.InsertTuple1(j,j*info['size'][i]/info['grid'][i]+info['origin'][i])
if i == 0: grid.SetXCoordinates(temp)
if i == 1: grid.SetYCoordinates(temp)
if i == 2: grid.SetZCoordinates(temp)
#--- read microstructure information --------------------------------------------------------------
structure = vtk.vtkIntArray()
structure.SetName('Microstructures')
for line in content:
for item in map(int,line.split()):
data['scalar']['structure'][i%info['grid'][0],(i/info['grid'][0])%info['grid'][1],i/info['grid'][0]/info['grid'][1]] = item
i += 1
structure.InsertNextValue(item)
grid.GetCellData().AddArray(structure)
out = {}
out['mesh'] = vtk_writeASCII_mesh(info['size'],info['grid'],info['origin'],data)
for what in out.keys():
#--- write data -----------------------------------------------------------------------------------
if file['name'] == 'STDIN':
output(out[what],{},'Stdout')
outWriter = vtk.vtkRectilinearGridWriter()
outWriter.WriteToOutputStringOn()
outWriter.SetFileTypeToASCII()
outWriter.SetHeader('# powered by $Id$')
outWriter.SetInput(grid)
outWriter.Write()
sys.stdout.write(outWriter.GetOutputString()[0:outWriter.GetOutputStringLength()])
else:
(head,tail) = os.path.split(file['name'])
vtk = open(os.path.join(head,what+'_'+os.path.splitext(tail)[0]+'.vtk'), 'w')
output(out[what],{'filepointer':vtk},'File')
vtk.close()
outWriter = vtk.vtkXMLRectilinearGridWriter()
outWriter.SetDataModeToBinary()
outWriter.SetCompressorTypeToZLib()
outWriter.SetFileName(os.path.join(head,'mesh_'+os.path.splitext(tail)[0]
+'.'+outWriter.GetDefaultFileExtension()))
outWriter.SetInput(grid)
outWriter.Write()

View File

@ -202,19 +202,19 @@ for file in files:
else:
new_header.append(header)
if numpy.all(info['grid'] == 0):
file['croak'].write('no grid info found.\n')
continue
if numpy.all(info['size'] == 0.0):
file['croak'].write('no size info found.\n')
continue
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 numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
new_header.append('$Id$\n')
new_header.append("grid\ta %i\tb %i\tc %i\n"%(info['grid'][0],info['grid'][1],info['grid'][2],))
new_header.append("size\tx %f\ty %f\tz %f\n"%(info['size'][0],info['size'][1],info['size'][2],))

View File

@ -79,7 +79,7 @@ for file in files:
info = {
'grid': numpy.array([0,0,1]),
'size': numpy.array([0.0,0.0,0.0]),
'size': numpy.zeros(3,'d'),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'homogenization': options.homogenization
@ -126,6 +126,13 @@ for file in files:
'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n\n'%info['microstructures'])
if numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
#--- write data -----------------------------------------------------------------------------------
if options.config:
file['output'].write('\n'.join(microstructure) + \

View File

@ -74,15 +74,7 @@ file = {'name':'STDIN',
'output':sys.stdout,
'croak':sys.stderr,
}
if numpy.any(options.grid < 1):
file['croak'].write('invalid grid...\n')
sys.exit()
if numpy.any(options.size < 0.0):
file['croak'].write('invalid size...\n')
sys.exit()
info = {
info = {
'grid': numpy.array(options.grid),
'size': numpy.array(options.size),
'origin': numpy.zeros(3,'d'),
@ -97,6 +89,13 @@ file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,info['grid'])))
'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n\n'%info['microstructures'])
if numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
#--- write header ---------------------------------------------------------------------------------
header = ['$Id$\n']
header.append("grid\ta %i\tb %i\tc %i\n"%(info['grid'][0],info['grid'][1],info['grid'][2],))

View File

@ -77,8 +77,8 @@ for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n')
info = {
'grid': numpy.array([0,0,0]),
'size': numpy.array([0.0,0.0,0.0]),
'grid': numpy.zeros(3,'i'),
'size': numpy.zeros(3,'d'),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'homogenization': options.homogenization
@ -116,6 +116,13 @@ for file in files:
'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n\n'%info['microstructures'])
if numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
#--- write data -----------------------------------------------------------------------------------
if options.config:
file['output'].write('\n'.join(microstructure) + \

View File

@ -119,19 +119,19 @@ for file in files:
else:
new_header.append(header)
if numpy.all(info['grid'] == 0):
file['croak'].write('no grid info found.\n')
continue
if numpy.all(info['size'] == 0.0):
file['croak'].write('no size info found.\n')
continue
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\n'%info['microstructures'])
if numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
if numpy.all(info['grid'] == 0):
newInfo['grid'] = info['grid']
if numpy.all(info['size'] == 0.0)::
@ -156,6 +156,13 @@ for file in files:
if (newInfo['microstructures'] != info['microstructures']):
file['croak'].write('--> microstructures: %i\n'%newInfo['microstructures'])
if numpy.any(newInfo['grid'] < 1):
file['croak'].write('no valid new grid info found.\n')
sys.exit()
if numpy.any(newInfo['size'] <= 0.0):
file['croak'].write('no valid new size info found.\n')
sys.exit()
#--- assemble header ------------------------------------------------------------------------------
new_header.append('$Id$\n')
new_header.append("grid\ta %i\tb %i\tc %i\n"%(newInfo['grid'][0],newInfo['grid'][1],newInfo['grid'][2]))
@ -167,12 +174,12 @@ for file in files:
output += ''.join(new_header)
#--- scale microstructure -------------------------------------------------------------------------
for c in xrange(options.grid[2]):
z = int(info['grid'][2]*(c+0.5)/options.grid[2])%info['grid'][2]
for b in xrange(options.grid[1]):
y = int(info['grid'][1]*(b+0.5)/options.grid[1])%info['grid'][1]
for a in xrange(options.grid[0]):
x = int(info['grid'][0]*(a+0.5)/options.grid[0])%info['grid'][0]
for c in xrange(newInfo['grid'][2]):
z = int(info['grid'][2]*(c+0.5)/newInfo['grid'][2])%info['grid'][2]
for b in xrange(newInfo['grid'][1]):
y = int(info['grid'][1]*(b+0.5)/newInfo['grid'][1])%info['grid'][1]
for a in xrange(newInfo['grid'][0]):
x = int(info['grid'][0]*(a+0.5)/newInfo['grid'][0])%info['grid'][0]
output += str(microstructure[x,y,z]).rjust(formatwidth) + {True:' ',False:'\n'}[options.twoD]
output += {True:'\n',False:''}[options.twoD]
file['output'].write(output)

View File

@ -122,12 +122,6 @@ for file in files:
else:
new_header.append(header)
if numpy.all(info['grid'] == 0):
file['croak'].write('no grid info found.\n')
continue
if numpy.all(info['size'] == 0.0):
file['croak'].write('no size info found.\n')
continue
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']))) + \
@ -135,6 +129,13 @@ for file in files:
'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n\n'%info['microstructures'])
if numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
#--- process input --------------------------------------------------------------------------------
N = info['grid'][0]*info['grid'][1]*info['grid'][2]
microstructure = numpy.zeros(N,'i')

View File

@ -119,19 +119,19 @@ for file in files:
else:
new_header.append(header)
if numpy.all(info['grid'] == 0):
file['croak'].write('no grid info found.\n')
continue
if numpy.all(info['size'] == 0.0):
file['croak'].write('no dimension info found.\n')
continue
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 numpy.any(info['grid'] < 1):
file['croak'].write('no valid grid info found.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
file['croak'].write('no valid size info found.\n')
sys.exit()
#--- read data ------------------------------------------------------------------------------------
microstructure = numpy.zeros(info['grid'],'i')
i = 0