more improvements on structure, comments and header generation of pre processing tools

This commit is contained in:
Martin Diehl 2013-05-13 13:10:31 +00:00
parent 52af9aaabf
commit b2c50124b5
8 changed files with 189 additions and 163 deletions

View File

@ -188,7 +188,6 @@ for file in files:
} }
new_header = [] new_header = []
new_header.append('$Id$\n')
for header in headers: for header in headers:
headitems = map(str.lower,header.split()) headitems = map(str.lower,header.split())
if headitems[0] == 'resolution': headitems[0] = 'grid' if headitems[0] == 'resolution': headitems[0] = 'grid'
@ -216,6 +215,7 @@ for file in files:
'homogenization: %i\n'%info['homogenization'] + \ 'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n'%info['microstructures']) 'microstructures: %i\n'%info['microstructures'])
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("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],)) new_header.append("size\tx %f\ty %f\tz %f\n"%(info['size'][0],info['size'][1],info['size'][2],))
new_header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2],)) new_header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2],))

View File

@ -1,11 +1,12 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,math,string,numpy import os,sys,math,string,numpy
from optparse import OptionParser, Option from optparse import OptionParser, Option
# ----------------------------- #--------------------------------------------------------------------------------------------------
class extendableOption(Option): class extendableOption(Option):
# ----------------------------- #--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments # 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 # taken from online tutorial http://docs.python.org/library/optparse.html
@ -22,10 +23,9 @@ class extendableOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser) Option.take_action(self, action, dest, opt, value, values, parser)
# -------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------
# MAIN # MAIN
# -------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """ parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """
Generate geometry description and material configuration from EBSD data in given square-gridded 'ang' file. Generate geometry description and material configuration from EBSD data in given square-gridded 'ang' file.
Two phases can be discriminated based on threshold value in a given data column. Two phases can be discriminated based on threshold value in a given data column.
@ -55,8 +55,7 @@ parser.set_defaults(config = False)
(options,filenames) = parser.parse_args() (options,filenames) = parser.parse_args()
# ------------------------------------------ setup file handles --------------------------------------- #--- setup file handles ---------------------------------------------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', files.append({'name':'STDIN',
@ -74,16 +73,22 @@ else:
}) })
# ------------------------------------------ loop over input files --------------------------------------- #--- loop over input files ------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n')
point = 0 info = {
step = [0,0] 'grid': numpy.array([0,0,1]),
grid = [1,1] 'size': numpy.array([0.0,0.0,0.0]),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'homogenization': options.homogenization
}
microstructure = ['<microstructure>'] microstructure = ['<microstructure>']
texture = ['<texture>'] texture = ['<texture>']
point = 0
step = [0,0]
for line in file['input']: for line in file['input']:
words = line.split() words = line.split()
@ -94,9 +99,9 @@ for file in files:
if words[1] == 'XSTEP:': step[0] = float(words[2]) if words[1] == 'XSTEP:': step[0] = float(words[2])
if words[1] == 'YSTEP:': step[1] = float(words[2]) if words[1] == 'YSTEP:': step[1] = float(words[2])
if words[1] == 'NCOLS_ODD:': if words[1] == 'NCOLS_ODD:':
grid[0] = int(words[2]); formatwidth = 1+int(math.log10(grid[0]*grid[1])) info['grid'][0] = int(words[2]); formatwidth = 1+int(math.log10(info['grid'][0]*info['grid'][1]))
if words[1] == 'NROWS:': if words[1] == 'NROWS:':
grid[1] = int(words[2]); formatwidth = 1+int(math.log10(grid[0]*grid[1])) info['grid'][1] = int(words[2]); formatwidth = 1+int(math.log10(info['grid'][0]*info['grid'][1]))
else: # finished with comments block else: # finished with comments block
if options.config: # write configuration (line by line) if options.config: # write configuration (line by line)
point += 1 point += 1
@ -108,29 +113,34 @@ for file in files:
texture += ['[Grain%s]\n'%me + \ texture += ['[Grain%s]\n'%me + \
'(gauss)\tphi1 %4.2f\tPhi %4.2f\tphi2 %4.2f\tscatter 0.0\tfraction 1.0\n'%tuple(map(lambda x: float(x)*180.0/math.pi, words[:3])) '(gauss)\tphi1 %4.2f\tPhi %4.2f\tphi2 %4.2f\tscatter 0.0\tfraction 1.0\n'%tuple(map(lambda x: float(x)*180.0/math.pi, words[:3]))
] ]
else: else: # only info from header needed
grid.append(1)
file['output'].write("6 header\n" + \
"$Id$ \n"
"grid\ta %i\tb %i\tc 1\n"%(grid[0],grid[1]) + \
"size\tx %g\ty %g\tz %g\n"%(step[0]*grid[0],step[1]*grid[1],min(step)) + \
"origin\tx 0\ty 0\tz 0\n" + \
"microstructures\t%i\n"%(grid[0]*grid[1]) + \
"homogenization %i\n"%options.homogenization + \
"1 to %i\n"%(grid[0]*grid[1]))
break break
file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,grid))) + \
'size x y z: %s\n'%(' x '.join(map(str,[step[0]*grid[0],step[1]*grid[1],min(step)]))) + \
'origin x y z: %s\n'%(' : '.join(map(str,[0.0,0.0,0.0]))) + \
'microstructures: %i\n'%(grid[0]*grid[1]) + \
'homogenization: %i\n'%options.homogenization)
info['microstructures'] = info['grid'][0]*info['grid'][1]
info['size'] = step[0]*info['grid'][0],step[1]*info['grid'][1],min(step)
#--- report ---------------------------------------------------------------------------------------
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'])
#--- write data -----------------------------------------------------------------------------------
if options.config: if options.config:
file['output'].write('\n'.join(microstructure) + \ file['output'].write('\n'.join(microstructure) + \
'\n'.join(texture)) '\n'.join(texture))
else:
header = ['$Id$\n']
header.append("grid\ta %i\tb %i\tc %i\n"%(info['grid'][0],info['grid'][1],info['grid'][2],))
header.append("size\tx %f\ty %f\tz %f\n"%(info['size'][0],info['size'][1],info['size'][2],))
header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2],))
header.append("microstructures\t%i\n"%info['microstructures'])
header.append("homogenization\t%i\n"%info['homogenization'])
file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header))
file['output'].write("1 to %i\n"%(info['microstructures']))
# ------------------------------------------ output finalization --------------------------------------- #--- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN': if file['name'] != 'STDIN':
file['output'].close() file['output'].close()
os.rename(file['name']+'_tmp',os.path.splitext(file['name'])[0] + \ os.rename(file['name']+'_tmp',os.path.splitext(file['name'])[0] + \

View File

@ -5,9 +5,9 @@ import os,sys,string,math,numpy
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
# ----------------------------- #--------------------------------------------------------------------------------------------------
class extendedOption(Option): class extendedOption(Option):
# ----------------------------- #--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments # 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 # taken from online tutorial http://docs.python.org/library/optparse.html
@ -24,8 +24,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser) Option.take_action(self, action, dest, opt, value, values, parser)
# ----------------------- MAIN ------------------------------- #--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
minimal_surfaces = ['primitive','gyroid','diamond',] minimal_surfaces = ['primitive','gyroid','diamond',]
surface = { surface = {
@ -52,8 +53,8 @@ parser.add_option('-p', '--periods', dest='periods', type='int', \
help='number of repetitions of unit cell [%default]') help='number of repetitions of unit cell [%default]')
parser.add_option('--homogenization', dest='homogenization', type='int', \ parser.add_option('--homogenization', dest='homogenization', type='int', \
help='homogenization index to be used [%defaults]') help='homogenization index to be used [%defaults]')
parser.add_option('--phase', dest='phase', type='int', nargs = 2, \ parser.add_option('--m', dest='microstructure', type='int', nargs = 2, \
help='two phase indices to be used %default') help='two microstructure indices to be used %default')
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \ parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
help='output geom file with two-dimensional data arrangement [%default]') help='output geom file with two-dimensional data arrangement [%default]')
@ -63,13 +64,12 @@ parser.set_defaults(periods = 1)
parser.set_defaults(grid = numpy.array([16,16,16])) parser.set_defaults(grid = numpy.array([16,16,16]))
parser.set_defaults(size = numpy.array([1.0,1.0,1.0])) parser.set_defaults(size = numpy.array([1.0,1.0,1.0]))
parser.set_defaults(homogenization = 1) parser.set_defaults(homogenization = 1)
parser.set_defaults(phase = [1,2]) parser.set_defaults(microstructure = [1,2])
parser.set_defaults(twoD = False) parser.set_defaults(twoD = False)
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
# ------------------------------------------ setup file handles --------------------------------------- #--- setup file handles ---------------------------------------------------------------------------
file = {'name':'STDIN', file = {'name':'STDIN',
'input':sys.stdin, 'input':sys.stdin,
'output':sys.stdout, 'output':sys.stdout,
@ -83,17 +83,31 @@ if numpy.any(options.grid < 1):
if numpy.any(options.size < 0.0): if numpy.any(options.size < 0.0):
file['croak'].write('invalid size...\n') file['croak'].write('invalid size...\n')
sys.exit() sys.exit()
info = {
'grid': options.grid,
'size': options.size,
'origin': numpy.zeros(3,'d'),
'microstructures': max(options.microstructure),
'homogenization': options.homogenization
}
#--- report ---------------------------------------------------------------------------------------
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'])
file['output'].write("6 header\n" + \ #--- write header ---------------------------------------------------------------------------------
"$Id$\n" +\ header = ['$Id$\n']
"grid\ta %i\tb %i\tc %i\n"%(options.grid[0],options.grid[1],options.grid[2],) + \ header.append("grid\ta %i\tb %i\tc %i\n"%(info['grid'][0],info['grid'][1],info['grid'][2],))
"size\tx %g\ty %g\tz %g\n"%(options.size[0],options.size[1],options.size[2],) + \ header.append("size\tx %f\ty %f\tz %f\n"%(info['size'][0],info['size'][1],info['size'][2],))
"origin\tx 0\ty 0\tz 0\n" + \ header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2],))
"microstructures 2\n" +\ header.append("microstructures\t%i\n"%info['microstructures'])
"homogenization %i\n"%options.homogenization header.append("homogenization\t%i\n"%info['homogenization'])
) file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header))
#--- write data -----------------------------------------------------------------------------------
for z in xrange(options.grid[2]): for z in xrange(options.grid[2]):
Z = options.periods*2.0*math.pi*(z+0.5)/options.grid[2] Z = options.periods*2.0*math.pi*(z+0.5)/options.grid[2]
for y in xrange(options.grid[1]): for y in xrange(options.grid[1]):
@ -101,6 +115,6 @@ for z in xrange(options.grid[2]):
for x in xrange(options.grid[0]): for x in xrange(options.grid[0]):
X = options.periods*2.0*math.pi*(x+0.5)/options.grid[0] X = options.periods*2.0*math.pi*(x+0.5)/options.grid[0]
file['output'].write(\ file['output'].write(\
str({True:options.phase[0],False:options.phase[1]}[options.threshold > surface[options.type](X,Y,Z)]) + \ str({True:options.microstructure[0],False:options.microstructure[1]}[options.threshold > \
{True:' ',False:'\n'}[options.twoD] ) surface[options.type](X,Y,Z)]) + {True:' ',False:'\n'}[options.twoD] )
file['output'].write({True:'\n',False:''}[options.twoD]) file['output'].write({True:'\n',False:''}[options.twoD])

View File

@ -1,11 +1,12 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,math,string,numpy import os,sys,math,string,numpy
from optparse import OptionParser, Option from optparse import OptionParser, Option
# ----------------------------- #--------------------------------------------------------------------------------------------------
class extendableOption(Option): class extendableOption(Option):
# ----------------------------- #--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments # 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 # taken from online tutorial http://docs.python.org/library/optparse.html
@ -22,10 +23,9 @@ class extendableOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser) Option.take_action(self, action, dest, opt, value, values, parser)
# -------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------
# MAIN # MAIN
# -------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """ parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """
Generate geometry description and material configuration from input files used by R.A. Lebensohn Generate geometry description and material configuration from input files used by R.A. Lebensohn
""" + string.replace('$Id$','\n','\\n') """ + string.replace('$Id$','\n','\\n')
@ -54,8 +54,7 @@ parser.set_defaults(config = False)
(options,filenames) = parser.parse_args() (options,filenames) = parser.parse_args()
# ------------------------------------------ setup file handles --------------------------------------- #--- setup file handles --------------------------------------------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', files.append({'name':'STDIN',
@ -73,22 +72,32 @@ else:
}) })
# ------------------------------------------ loop over input files --------------------------------------- #--- loop over input files ------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n') if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n')
point = 0 info = {
geomdim = [0.0,0.0,0.0] 'grid': numpy.array([0,0,0]),
'size': numpy.array([0.0,0.0,0.0]),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'homogenization': options.homogenization
}
needInfo = [True,True,True] needInfo = [True,True,True]
resolution = [0,0,0]
microstructure = ['<microstructure>'] microstructure = ['<microstructure>']
texture = ['<texture>'] texture = ['<texture>']
point = 0
for line in file['input']: for line in file['input']:
if line.strip(): if line.strip():
point += 1 point += 1
words = line.split() words = line.split()
currPos = map(float,words[3:6])
for i in xrange(3):
if currPos[i] > info['grid'][i]:
info['size'][i] = currPos[i]
info['grid'][i]+=1
if options.config: # write configuration (line by line) if options.config: # write configuration (line by line)
me = str(point) me = str(point)
microstructure += ['[Grain%s]\n'%me + \ microstructure += ['[Grain%s]\n'%me + \
@ -98,26 +107,30 @@ for file in files:
texture += ['[Grain%s]\n'%me + \ texture += ['[Grain%s]\n'%me + \
'(gauss)\tphi1 %s\tPhi %s\tphi2 %s\tscatter 0.0\tfraction 1.0\n'%tuple(words[:3]) '(gauss)\tphi1 %s\tPhi %s\tphi2 %s\tscatter 0.0\tfraction 1.0\n'%tuple(words[:3])
] ]
else: info['microstructures'] = info['grid'][0]*info['grid'][1]*info['grid'][2]
currPos = map(float,words[3:6])
for i in xrange(3):
if currPos[i] > geomdim[i]:
geomdim[i] = currPos[i]
resolution[i]+=1
#--- report ---------------------------------------------------------------------------------------
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'])
#--- write data -----------------------------------------------------------------------------------
if options.config: if options.config:
file['output'].write('\n'.join(microstructure) + \ file['output'].write('\n'.join(microstructure) + \
'\n'.join(texture)) '\n'.join(texture))
else: else:
file['output'].write("4 header\n" + \ header = ['$Id$\n']
"resolution\ta %i\tb %i\tc %i\n"%tuple(resolution) + \ header.append("grid\ta %i\tb %i\tc %i\n"%(info['grid'][0],info['grid'][1],info['grid'][2],))
"dimension\tx %g\ty %g\tz %g\n"%tuple(geomdim) + \ header.append("size\tx %f\ty %f\tz %f\n"%(info['size'][0],info['size'][1],info['size'][2],))
"origin\tx 0\ty 0\tz 0\n" + \ header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2],))
"homogenization %i\n"%options.homogenization + \ header.append("microstructures\t%i\n"%info['microstructures'])
"1 to %i\n"%(resolution[0]*resolution[1]*resolution[2])) header.append("homogenization\t%i\n"%info['homogenization'])
file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header))
# ------------------------------------------ output finalization --------------------------------------- file['output'].write("1 to %i\n"%(info['microstructures']))
#--- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN': if file['name'] != 'STDIN':
file['output'].close() file['output'].close()
os.rename(file['name']+'_tmp',os.path.splitext(file['name'])[0] + \ os.rename(file['name']+'_tmp',os.path.splitext(file['name'])[0] + \

View File

@ -4,10 +4,9 @@
import os,sys,string,re,math,numpy import os,sys,string,re,math,numpy
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
#--------------------------------------------------------------------------------------------------
# -----------------------------
class extendedOption(Option): class extendedOption(Option):
# ----------------------------- #--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments # 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 # taken from online tutorial http://docs.python.org/library/optparse.html
@ -24,8 +23,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser) Option.take_action(self, action, dest, opt, value, values, parser)
# ----------------------- MAIN ------------------------------- #--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
identifiers = { identifiers = {
'grid': ['a','b','c'], 'grid': ['a','b','c'],
'size': ['x','y','z'], 'size': ['x','y','z'],
@ -47,8 +47,7 @@ compress geometry files with ranges "a to b" and/or multiples "n of x".
(options, filenames) = parser.parse_args() (options, filenames) = parser.parse_args()
# ------------------------------------------ setup file handles --------------------------------------- #--- setup file handles ---------------------------------------------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', files.append({'name':'STDIN',
@ -65,12 +64,10 @@ else:
'croak':sys.stdout, 'croak':sys.stdout,
}) })
# ------------------------------------------ loop over input files --------------------------------------- #--- loop over input files ------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n') 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() firstline = file['input'].readline()
m = re.search('(\d+)\s*head', firstline.lower()) m = re.search('(\d+)\s*head', firstline.lower())
if m: if m:
@ -83,6 +80,7 @@ for file in files:
content = file['input'].readlines() content = file['input'].readlines()
file['input'].close() file['input'].close()
#--- interpretate header --------------------------------------------------------------------------
info = {'grid': [0,0,0], info = {'grid': [0,0,0],
'size': [0.0,0.0,0.0], 'size': [0.0,0.0,0.0],
'origin': [0.0,0.0,0.0], 'origin': [0.0,0.0,0.0],
@ -116,13 +114,9 @@ for file in files:
'origin x y z: %s\n'%(' : '.join(map(str,info['origin']))) + \ 'origin x y z: %s\n'%(' : '.join(map(str,info['origin']))) + \
'homogenization: %i\n'%info['homogenization'] + \ 'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n'%info['microstructures']) 'microstructures: %i\n'%info['microstructures'])
# ------------------------------------------ assemble header ---------------------------------------
file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header)) file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header))
# ------------------------------------------ pack input --------------------------------------- #--- pack input -----------------------------------------------------------------------------------
type = '' type = ''
former = -1 former = -1
start = -1 start = -1
@ -148,17 +142,13 @@ for file in files:
reps = 1 reps = 1
former = current former = current
# write out last item...
output = {'.': str(former), output = {'.': str(former),
'to': '%i to %i'%(former-reps+1,former), 'to': '%i to %i'%(former-reps+1,former),
'of': '%i of %i'%(reps,former), 'of': '%i of %i'%(reps,former),
}[type] }[type]
file['output'].write(output+'\n') file['output'].write(output+'\n')
# ------------------------------------------ output finalization --------------------------------------- #--- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN': if file['name'] != 'STDIN':
file['output'].close() file['output'].close()
os.rename(file['name']+'_tmp',file['name']) os.rename(file['name']+'_tmp',file['name'])

View File

@ -4,10 +4,9 @@
import os,sys,string,re,math,numpy import os,sys,string,re,math,numpy
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
#--------------------------------------------------------------------------------------------------
# -----------------------------
class extendedOption(Option): class extendedOption(Option):
# ----------------------------- #--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments # 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 # taken from online tutorial http://docs.python.org/library/optparse.html
@ -24,8 +23,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser) Option.take_action(self, action, dest, opt, value, values, parser)
# ----------------------- MAIN ------------------------------- #--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
identifiers = { identifiers = {
'grid': ['a','b','c'], 'grid': ['a','b','c'],
'size': ['x','y','z'], 'size': ['x','y','z'],
@ -50,7 +50,7 @@ parser.add_option('-g', '--grid', dest='grid', type='int', nargs = 3, \
parser.add_option('-s', '--size', dest='size', type='float', nargs = 3, \ parser.add_option('-s', '--size', dest='size', type='float', nargs = 3, \
help='x,y,z size of hexahedral box [unchanged]') help='x,y,z size of hexahedral box [unchanged]')
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \ parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
help='output geom file with two-dimensional data arrangement') help='output geom file with two-dimensional data arrangement [%default]')
parser.set_defaults(grid = [0,0,0]) parser.set_defaults(grid = [0,0,0])
parser.set_defaults(size = [0.0,0.0,0.0]) parser.set_defaults(size = [0.0,0.0,0.0])
@ -58,8 +58,7 @@ parser.set_defaults(twoD = False)
(options, filenames) = parser.parse_args() (options, filenames) = parser.parse_args()
# ------------------------------------------ setup file handles --------------------------------------- #--- setup file handles ---------------------------------------------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', files.append({'name':'STDIN',
@ -76,13 +75,10 @@ else:
'croak':sys.stdout, 'croak':sys.stdout,
}) })
# ------------------------------------------ loop over input files --------------------------------------- #--- loop over input files ------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n') 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() firstline = file['input'].readline()
m = re.search('(\d+)\s*head', firstline.lower()) m = re.search('(\d+)\s*head', firstline.lower())
if m: if m:
@ -95,6 +91,7 @@ for file in files:
content = file['input'].readlines() content = file['input'].readlines()
file['input'].close() file['input'].close()
#--- interpretate header --------------------------------------------------------------------------
info = { info = {
'grid': numpy.array(options.grid), 'grid': numpy.array(options.grid),
'size': numpy.array(options.size), 'size': numpy.array(options.size),
@ -103,8 +100,13 @@ for file in files:
'homogenization': 0 'homogenization': 0
} }
newInfo = {
'grid': numpy.array(options.grid),
'size': numpy.array(options.size),
'microstructures': 0,
}
new_header = [] new_header = []
new_header.append('$Id$\n')
for header in headers: for header in headers:
headitems = map(str.lower,header.split()) headitems = map(str.lower,header.split())
if headitems[0] == 'resolution': headitems[0] = 'grid' if headitems[0] == 'resolution': headitems[0] = 'grid'
@ -126,17 +128,16 @@ for file in files:
file['croak'].write('no size info found.\n') file['croak'].write('no size info found.\n')
continue continue
file['croak'].write('-- input --\n' +\ file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,info['grid']))) + \
'grid a b c: %s\n'%(' x '.join(map(str,info['grid']))) + \
'size x y z: %s\n'%(' x '.join(map(str,info['size']))) + \ 'size x y z: %s\n'%(' x '.join(map(str,info['size']))) + \
'origin x y z: %s\n'%(' : '.join(map(str,info['origin']))) + \ 'origin x y z: %s\n'%(' : '.join(map(str,info['origin']))) + \
'homogenization: %i\n'%info['homogenization'] + \ 'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n'%info['microstructures']) 'microstructures: %i\n\n'%info['microstructures'])
if options.grid == [0,0,0]: if options.grid == [0,0,0]:
options.grid = info['grid'] newInfo['grid'] = info['grid']
if options.size == [0.0,0.0,0.0]: if options.size == [0.0,0.0,0.0]:
options.size = info['size'] newInfo['size'] = info['size']
microstructure = numpy.zeros(info['grid'],'i') microstructure = numpy.zeros(info['grid'],'i')
i = 0 i = 0
@ -146,18 +147,21 @@ for file in files:
(i/info['grid'][0])%info['grid'][1], (i/info['grid'][0])%info['grid'][1],
i/info['grid'][0] /info['grid'][1]] = item i/info['grid'][0] /info['grid'][1]] = item
i += 1 i += 1
info['microstructures'] = microstructure.max() newInfo['microstructures'] = microstructure.max()
formatwidth = 1+int(math.floor(math.log10(microstructure.max()))) formatwidth = 1+int(math.floor(math.log10(microstructure.max())))
file['croak'].write('-- output --\n' +\ if (any(newInfo['grid'] != info['grid'])):
'grid a b c: %s\n'%(' x '.join(map(str,options.grid))) + \ file['croak'].write('--> grid a b c: %s\n'%(' x '.join(map(str,newInfo['grid']))))
'size x y z: %s\n'%(' x '.join(map(str,options.size))) + \ if (any(newInfo['size'] != info['size'])):
'microstructures: %i\n'%info['microstructures']) file['croak'].write('--> size x y z: %s\n'%(' x '.join(map(str,newInfo['size']))))
if (newInfo['microstructures'] != info['microstructures']):
file['croak'].write('--> microstructures: %i\n'%newInfo['microstructures'])
new_header.append("grid\ta %i\tb %i\tc %i\n"%(options.grid[0],options.grid[1],options.grid[2],)) new_header.append('$Id$\n')
new_header.append("size\tx %f\ty %f\tz %f\n"%(options.size[0],options.size[1],options.size[2],)) new_header.append("grid\ta %i\tb %i\tc %i\n"%(newInfo['grid'][0],newInfo['grid'][1],newInfo['grid'][2]))
new_header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2],)) new_header.append("size\tx %f\ty %f\tz %f\n"%(newInfo['size'][0],newInfo['size'][1],newInfo['size'][2]))
new_header.append("microstructures\t%i\n"%info['microstructures']) new_header.append("origin\tx %f\ty %f\tz %f\n"%(info['origin'][0],info['origin'][1],info['origin'][2]))
new_header.append("microstructures\t%i\n"%newInfo['microstructures'])
new_header.append("homogenization\t%i\n"%info['homogenization']) new_header.append("homogenization\t%i\n"%info['homogenization'])
# ------------------------------------------ assemble header --------------------------------------- # ------------------------------------------ assemble header ---------------------------------------

View File

@ -110,7 +110,6 @@ for file in files:
'microstructures': 0, 'microstructures': 0,
} }
new_header = [] new_header = []
new_header.append('$Id$\n')
for header in headers: for header in headers:
headitems = map(str.lower,header.split()) headitems = map(str.lower,header.split())
if headitems[0] == 'resolution': headitems[0] = 'grid' if headitems[0] == 'resolution': headitems[0] = 'grid'
@ -165,6 +164,7 @@ for file in files:
if (newInfo['microstructures'] != info['microstructures']): if (newInfo['microstructures'] != info['microstructures']):
file['croak'].write('--> microstructures: %i\n'%newInfo['microstructures']) file['croak'].write('--> microstructures: %i\n'%newInfo['microstructures'])
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("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],)) new_header.append("size\tx %f\ty %f\tz %f\n"%(info['size'][0],info['size'][1],info['size'][2],))
new_header.append("origin\tx %f\ty %f\tz %f\n"%( new_header.append("origin\tx %f\ty %f\tz %f\n"%(

View File

@ -5,9 +5,9 @@ import os,sys,string,re,math,numpy
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
# ----------------------------- #--------------------------------------------------------------------------------------------------
class extendedOption(Option): class extendedOption(Option):
# ----------------------------- #--------------------------------------------------------------------------------------------------
# used for definition of new option parser action 'extend', which enables to take multiple option arguments # 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 # taken from online tutorial http://docs.python.org/library/optparse.html
@ -24,8 +24,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser) Option.take_action(self, action, dest, opt, value, values, parser)
# ----------------------- MAIN ------------------------------- #--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
identifiers = { identifiers = {
'grid': ['a','b','c'], 'grid': ['a','b','c'],
'size': ['x','y','z'], 'size': ['x','y','z'],
@ -53,7 +54,7 @@ parser.set_defaults(twoD = False)
(options, filenames) = parser.parse_args() (options, filenames) = parser.parse_args()
# ------------------------------------------ setup file handles --------------------------------------- #--- setup file handles ---------------------------------------------------------------------------
files = [] files = []
if filenames == []: if filenames == []:
files.append({'name':'STDIN', files.append({'name':'STDIN',
@ -70,13 +71,10 @@ else:
'croak':sys.stdout, 'croak':sys.stdout,
}) })
# ------------------------------------------ loop over input files --------------------------------------- #--- loop over input files ------------------------------------------------------------------------
for file in files: for file in files:
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n') 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() firstline = file['input'].readline()
m = re.search('(\d+)\s*head', firstline.lower()) m = re.search('(\d+)\s*head', firstline.lower())
if m: if m:
@ -89,6 +87,7 @@ for file in files:
content = file['input'].readlines() content = file['input'].readlines()
file['input'].close() file['input'].close()
#--- interpretate header --------------------------------------------------------------------------
info = {'grid': [0,0,0], info = {'grid': [0,0,0],
'size': [0.0,0.0,0.0], 'size': [0.0,0.0,0.0],
'origin': [0.0,0.0,0.0], 'origin': [0.0,0.0,0.0],
@ -131,12 +130,9 @@ for file in files:
else: else:
digits = 1+int(math.log10(int(info['grid'][0]*info['grid'][1]*info['grid'][2]))) digits = 1+int(math.log10(int(info['grid'][0]*info['grid'][1]*info['grid'][2])))
# ------------------------------------------ assemble header ---------------------------------------
file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header)) file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header))
# ------------------------------------------ unpack input --------------------------------------- #--- unpack input ---------------------------------------------------------------------------------
wordsWritten = 0 wordsWritten = 0
for line in content: for line in content:
words = map(str.lower,line.split()) words = map(str.lower,line.split())
@ -148,8 +144,7 @@ for file in files:
wordsWritten += 1 wordsWritten += 1
file['output'].write(word.zfill(digits)+{True:'\n',False:' '}[wordsWritten%format == 0]) # newline every format words file['output'].write(word.zfill(digits)+{True:'\n',False:' '}[wordsWritten%format == 0]) # newline every format words
# ------------------------------------------ output finalization --------------------------------------- #--- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN': if file['name'] != 'STDIN':
file['output'].close() file['output'].close()
os.rename(file['name']+'_tmp',file['name']) os.rename(file['name']+'_tmp',file['name'])