polishing, unifying,simplifying

This commit is contained in:
Martin Diehl 2013-05-14 17:51:53 +00:00
parent 2acd737859
commit 9093cf2072
5 changed files with 57 additions and 73 deletions

View File

@ -4,10 +4,9 @@
import os,sys,string,math,numpy,time
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
@ -24,10 +23,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser)
# ----------------------- MAIN -------------------------------
#--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=extendedOption, usage='%prog', description = """
Generate a geometry file of an osteon enclosing the Harvesian canal and separated by interstitial tissue.
The osteon phase is lamellar with a twisted plywood structure.
@ -75,8 +73,7 @@ parser.set_defaults(twoD = False)
(options, args) = parser.parse_args()
# ------------------------------------------ setup file handles ---------------------------------------
#--- setup file handles ---------------------------------------------------------------------------
file = {'name':'STDIN',
'input':sys.stdin,
'output':sys.stdout,
@ -87,7 +84,7 @@ if numpy.any(options.grid < 2):
file['croak'].write('grid too low...\n')
sys.exit()
options.omega *= math.pi/180.0 # rescale ro radians
options.omega *= math.pi/180.0 # rescale ro radians
rotation = numpy.array([[ math.cos(options.omega),math.sin(options.omega),],
[-math.sin(options.omega),math.cos(options.omega),]],'d')
@ -98,11 +95,10 @@ info = {
'grid': numpy.ones(3,'i'),
'size': numpy.ones(3,'d'),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'microstructures': 3,
'homogenization': options.homogenization,
}
info['grid'][:2] = options.grid
info['size'][:2] = options.size
info['size'][2] = min(info['size'][0]/info['grid'][0],info['size'][1]/info['grid'][1])
@ -113,8 +109,8 @@ X0 = info['size'][0]/info['grid'][0]*\
Y0 = info['size'][1]/info['grid'][1]*\
(numpy.tile(numpy.arange(info['grid'][1]),(info['grid'][0],1)).transpose() - info['grid'][1]/2 + 0.5)
X = X0*rotation[0,0] + Y0*rotation[0,1] # rotate by omega
Y = X0*rotation[1,0] + Y0*rotation[1,1] # rotate by omega
X = X0*rotation[0,0] + Y0*rotation[0,1] # rotate by omega
Y = X0*rotation[1,0] + Y0*rotation[1,1] # rotate by omega
radius = numpy.sqrt(X*X + Y*Y/options.aspect/options.aspect)
alpha = numpy.degrees(numpy.arctan2(Y/options.aspect,X))
@ -122,7 +118,6 @@ beta = options.amplitude*numpy.sin(2.0*math.pi*(radius-options.canal)/options.pe
microstructure = numpy.where(radius < float(options.canal),1,0) + numpy.where(radius > float(options.osteon),2,0)
info['microstructures'] = 3
alphaOfGrain = numpy.zeros(info['grid'][0]*info['grid'][1],'d')
betaOfGrain = numpy.zeros(info['grid'][0]*info['grid'][1],'d')
for y in xrange(info['grid'][1]):
@ -165,15 +160,13 @@ if options.config:
betaOfGrain[i]))
else:
file['output'].write("6 header\n" + \
"$Id$\n" + \
"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"%(info['size'][0],info['size'][1],info['size'][2]) + \
"origin\tx %g\ty %g\tz %g\n"%(info['origin'][0],info['origin'][1],info['origin'][2]) + \
"microstructures\t%i\n"%(info['microstructures']) + \
"homogenization\t%i\n"%(info['homogenization'])
)
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(header))+''.join(header))
for y in xrange(info['grid'][1]):
for x in xrange(info['grid'][0]):
@ -183,6 +176,5 @@ else:
file['output'].write({True:'\n',False:''}[options.twoD])
# ------------------------------------------ output finalization ---------------------------------------
#--- output finalization --------------------------------------------------------------------------
file['output'].close()

View File

@ -154,7 +154,8 @@ else:
if os.path.exists(name):
files.append({'name':name,
'input':open(name),
'output':[open(features[feature]['names'][0]+'_'+name,'w') for feature in feature_list],
'output':[open(features[feature]['names'][0]+'_'+name,'w')
for string.split(feature,sep=',')[0] in feature_list],
'croak':sys.stdout,
})
@ -174,15 +175,14 @@ for file in files:
content = file['input'].readlines()
file['input'].close()
#--- interpretate header --------------------------------------------------------------------------
#--- interprete header ----------------------------------------------------------------------------
info = {
'grid': numpy.array([0,0,0]),
'size': numpy.array([0.0,0.0,0.0]),
'origin': numpy.array([0.0,0.0,0.0]),
'microstructures': 0,
'homogenization': 0
'grid': numpy.zeros(3,'i'),
'size': numpy.zeros(3,'d'),
'origin': numpy.zeros(3,'d'),
'microstructures': 0,
'homogenization': 0
}
newInfo = {
'microstructures': 0,
}
@ -264,8 +264,7 @@ for file in files:
formatwidth = int(math.floor(math.log10(distance[i,:,:,:].max())+1))
#--- assemble header and report changes -----------------------------------------------------------
output = '%i\theader\n'%(len(new_header)+1)
output += ''.join(new_header)
output = '%i\theader\n'%(len(new_header)+1)+''.join(new_header)
output += "microstructures\t%i\n"%newInfo['microstructures']
file['croak'].write('\n'+features[i]['names'][0]+'\n')
if (newInfo['microstructures'] != info['microstructures']):

View File

@ -87,9 +87,9 @@ for file in files:
microstructure = ['<microstructure>']
texture = ['<texture>']
point = 0
step = [0,0]
point = 0
for line in file['input']:
words = line.split()
if words[0] == '#': # process initial comments block
@ -137,7 +137,7 @@ for file in files:
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('%i\theader\n'%(len(header))+''.join(header))
file['output'].write("1 to %i\n"%(info['microstructures']))
#--- output finalization --------------------------------------------------------------------------

View File

@ -54,7 +54,7 @@ parser.set_defaults(config = False)
(options,filenames) = parser.parse_args()
#--- setup file handles --------------------------------------------------------------------------
#--- setup file handles ---------------------------------------------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN',
@ -127,7 +127,7 @@ for file in files:
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('%i\theader\n'%(len(header))+''.join(header))
file['output'].write("1 to %i\n"%(info['microstructures']))
#--- output finalization --------------------------------------------------------------------------

View File

@ -4,10 +4,9 @@
import os,sys,string,re,math,numpy
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
@ -24,8 +23,9 @@ class extendedOption(Option):
Option.take_action(self, action, dest, opt, value, values, parser)
# ----------------------- MAIN -------------------------------
#--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
identifiers = {
'grid': ['a','b','c'],
'size': ['x','y','z'],
@ -39,7 +39,6 @@ mappings = {
'microstructures': lambda x: int(x),
}
parser = OptionParser(option_class=extendedOption, usage='%prog options [file[s]]', description = """
Offset microstructure index for points which see a microstructure different from themselves within a given (cubic) vicinity,
i.e. within the region close to a grain/phase boundary.
@ -59,8 +58,7 @@ parser.set_defaults(twoD = False)
(options, filenames) = parser.parse_args()
# ------------------------------------------ setup file handles ---------------------------------------
#--- setup file handles --------------------------------------------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN',
@ -77,14 +75,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:
@ -97,6 +91,7 @@ for file in files:
content = file['input'].readlines()
file['input'].close()
#--- interprete header ----------------------------------------------------------------------------
info = {
'grid': numpy.zeros(3,'i'),
'size': numpy.zeros(3,'d'),
@ -104,6 +99,9 @@ for file in files:
'microstructures': 0,
'homogenization': 0
}
newInfo = {
'microstructures': 0,
}
new_header = []
new_header.append('$Id$\n')
@ -128,13 +126,13 @@ for file in files:
file['croak'].write('no dimension info found.\n')
continue
file['croak'].write('-- input --\n' +\
'grid a b c: %s\n'%(' x '.join(map(str,info['grid']))) + \
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'])
#--- read data ------------------------------------------------------------------------------------
microstructure = numpy.zeros(info['grid'],'i')
i = 0
for line in content:
@ -149,6 +147,7 @@ for file in files:
options.offset = microstructure.max()
formatwidth = 1+int(math.floor(math.log10(abs(microstructure.max()+options.offset))))
#--- search ---------------------------------------------------------------------------------------
for x in xrange(info['grid'][0]):
for y in xrange(info['grid'][1]):
for z in xrange(info['grid'][2]):
@ -161,8 +160,8 @@ for file in files:
for dz in xrange(-options.vicinity,options.vicinity+1):
they = microstructure[(x+dx)%info['grid'][0],(y+dy)%info['grid'][1],(z+dz)%info['grid'][2]]
if they != me and they != me+options.offset: # located alien microstructure in vicinity
microstructure[x,y,z] += options.offset # tag myself as close to aliens!
if they != me and they != me+options.offset: # located alien microstructure in vicinity
microstructure[x,y,z] += options.offset # tag myself as close to aliens!
breaker = True
break
@ -170,33 +169,27 @@ for file in files:
if breaker: break
info['microstructures'] = microstructure.max()
file['croak'].write('-- output --\n' +\
'microstructures: %i\n'%info['microstructures'])
newInfo['microstructures'] = microstructure.max()
if (newInfo['microstructures'] != info['microstructures']):
file['croak'].write('--> microstructures: %i\n'%newInfo['microstructures'])
# ------------------------------------------ assemble header ---------------------------------------
# --- assemble header -----------------------------------------------------------------------------
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'][0]))
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"%info['microstructures'])
new_header.append("microstructures\t%i\n"%newInfo['microstructures'])
new_header.append("homogenization\t%i\n"%info['homogenization'])
file['output'].write('%i\theader\n'%(len(new_header))+''.join(new_header))
output = '%i\theader\n'%(len(new_header))
output += ''.join(new_header)
# ------------------------------------- regenerate texture information ----------------------------------
# --- write microstructure information ------------------------------------------------------------
for z in xrange(info['grid'][2]):
for y in xrange(info['grid'][1]):
output += {True:' ',False:'\n'}[options.twoD].join(map(lambda x: str(x).rjust(formatwidth), microstructure[:,y,z])) + '\n'
output += '\n'
# ------------------------------------------ output result ---------------------------------------
file['output'].write(output)
#--- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN':
file['output'].close
file['output'].close()
os.rename(file['name']+'_tmp',file['name'])