updated python style

This commit is contained in:
Martin Diehl 2014-10-09 17:03:06 +00:00
parent 45bedec229
commit 57e522566a
5 changed files with 121 additions and 189 deletions

View File

@ -1,39 +1,23 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,math,string,numpy as np
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
import os,sys,math,string
import numpy as np
from optparse import OptionParser
import damask
scriptID = '$Id$'
scriptName = scriptID.split()[1]
#--------------------------------------------------------------------------------------------------
class extendableOption(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
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
#--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """
parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """
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.
""" + string.replace(scriptID,'\n','\\n')
)
""", version = scriptID)
parser.add_option('--column', dest='column', type='int', metavar = 'int', \
help='data column to discriminate phase 1 from 2 [%default]')
@ -208,7 +192,7 @@ for file in files:
#--- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN':
table.output_close()
file['output'].close()
os.rename(file['name']+'_tmp',os.path.splitext(file['name'])[0] + \
{True: '_material.config',
False:'.geom'}[options.config])

View File

@ -1,42 +1,25 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,re,sys,math,numpy,string,damask
import os,sys,string,re,math
import numpy as np
from scipy import ndimage
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
scriptID = '$Id$'
scriptName = scriptID.split()[1]
#--------------------------------------------------------------------------------------------------
class extendableOption(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
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
from optparse import OptionParser
import damask
scriptID = string.replace('$Id$','\n','\\n')
scriptName = scriptID.split()[1][:-3]
def periodic_3Dpad(array, rimdim=(1,1,1)):
rimdim = numpy.array(rimdim,'i')
size = numpy.array(array.shape,'i')
padded = numpy.empty(size+2*rimdim,array.dtype)
rimdim = np.array(rimdim,'i')
size = np.array(array.shape,'i')
padded = np.empty(size+2*rimdim,array.dtype)
padded[rimdim[0]:rimdim[0]+size[0],
rimdim[1]:rimdim[1]+size[1],
rimdim[2]:rimdim[2]+size[2]] = array
p = numpy.zeros(3,'i')
p = np.zeros(3,'i')
for side in xrange(3):
for p[(side+2)%3] in xrange(padded.shape[(side+2)%3]):
for p[(side+1)%3] in xrange(padded.shape[(side+1)%3]):
@ -75,7 +58,7 @@ features = [
]
neighborhoods = {
'neumann':numpy.array([
'neumann':np.array([
[-1, 0, 0],
[ 1, 0, 0],
[ 0,-1, 0],
@ -83,7 +66,7 @@ neighborhoods = {
[ 0, 0,-1],
[ 0, 0, 1],
]),
'moore':numpy.array([
'moore':np.array([
[-1,-1,-1],
[ 0,-1,-1],
[ 1,-1,-1],
@ -116,11 +99,11 @@ neighborhoods = {
])
}
parser = OptionParser(option_class=extendableOption, usage='%prog options [file[s]]', description = """
parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """
Produce geom files containing Euclidean distance to grain structural features:
boundaries, triple lines, and quadruple points.
""" + string.replace(scriptID,'\n','\\n')
)
""", version = scriptID)
parser.add_option('-t','--type', dest = 'type', action = 'extend', type = 'string', metavar = '<string LIST>',
help = 'feature type (%s) '%(', '.join(map(lambda x:'|'.join(x['names']),features))) )
@ -166,25 +149,25 @@ 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')
theTable = damask.ASCIItable(file['input'],file['output'][0],labels = False)
theTable.head_read()
table = damask.ASCIItable(file['input'],file['output'][0],labels = False)
table.head_read()
#--- interpret header ----------------------------------------------------------------------------
info = {
'grid': numpy.zeros(3,'i'),
'size': numpy.zeros(3,'d'),
'origin': numpy.zeros(3,'d'),
'grid': np.zeros(3,'i'),
'size': np.zeros(3,'d'),
'origin': np.zeros(3,'d'),
'homogenization': 0,
'microstructures': 0,
}
newInfo = {
'grid': numpy.zeros(3,'i'),
'origin': numpy.zeros(3,'d'),
'grid': np.zeros(3,'i'),
'origin': np.zeros(3,'d'),
'microstructures': 0,
}
extra_header = []
for header in theTable.info:
for header in table.info:
headitems = map(str.lower,header.split())
if len(headitems) == 0: continue # skip blank lines
for synonym,alternatives in synonyms.iteritems():
@ -205,19 +188,19 @@ for file in files:
'homogenization: %i\n'%info['homogenization'] + \
'microstructures: %i\n'%info['microstructures'])
if numpy.any(info['grid'] < 1):
if np.any(info['grid'] < 1):
file['croak'].write('invalid grid a b c.\n')
continue
if numpy.any(info['size'] <= 0.0):
if np.any(info['size'] <= 0.0):
file['croak'].write('invalid size x y z.\n')
continue
#--- read data ------------------------------------------------------------------------------------
microstructure = numpy.zeros(info['grid'].prod(),'i') # initialize as flat array
microstructure = np.zeros(info['grid'].prod(),'i') # initialize as flat array
i = 0
while theTable.data_read():
items = theTable.data
while table.data_read():
items = table.data
if len(items) > 2:
if items[1].lower() == 'of': items = [int(items[2])]*int(items[0])
elif items[1].lower() == 'to': items = xrange(int(items[0]),1+int(items[2]))
@ -230,30 +213,30 @@ for file in files:
neighborhood = neighborhoods[options.neighborhood]
convoluted = numpy.empty([len(neighborhood)]+list(info['grid']+2),'i')
convoluted = np.empty([len(neighborhood)]+list(info['grid']+2),'i')
structure = periodic_3Dpad(microstructure.reshape(info['grid'],order='F'))
for i,p in enumerate(neighborhood):
stencil = numpy.zeros((3,3,3),'i')
stencil = np.zeros((3,3,3),'i')
stencil[1,1,1] = -1
stencil[p[0]+1,
p[1]+1,
p[2]+1] = 1
convoluted[i,:,:,:] = ndimage.convolve(structure,stencil)
distance = numpy.ones((len(feature_list),info['grid'][0],info['grid'][1],info['grid'][2]),'d')
distance = np.ones((len(feature_list),info['grid'][0],info['grid'][1],info['grid'][2]),'d')
convoluted = numpy.sort(convoluted,axis = 0)
uniques = numpy.where(convoluted[0,1:-1,1:-1,1:-1] != 0, 1,0) # initialize unique value counter (exclude myself [= 0])
convoluted = np.sort(convoluted,axis = 0)
uniques = np.where(convoluted[0,1:-1,1:-1,1:-1] != 0, 1,0) # initialize unique value counter (exclude myself [= 0])
for i in xrange(1,len(neighborhood)): # check remaining points in neighborhood
uniques += numpy.where(numpy.logical_and(
uniques += np.where(np.logical_and(
convoluted[i,1:-1,1:-1,1:-1] != convoluted[i-1,1:-1,1:-1,1:-1], # flip of ID difference detected?
convoluted[i,1:-1,1:-1,1:-1] != 0), # not myself?
1,0) # count flip
for i,feature_id in enumerate(feature_list):
distance[i,:,:,:] = numpy.where(uniques >= features[feature_id]['aliens'],0.0,1.0) # seed with 0.0 when enough unique neighbor IDs are present
distance[i,:,:,:] = np.where(uniques >= features[feature_id]['aliens'],0.0,1.0) # seed with 0.0 when enough unique neighbor IDs are present
for i in xrange(len(feature_list)):
distance[i,:,:,:] = ndimage.morphology.distance_transform_edt(distance[i,:,:,:])*[options.scale]*3
@ -262,10 +245,10 @@ for file in files:
newInfo['microstructures'] = int(math.ceil(distance[i,:,:,:].max()))
#--- write header ---------------------------------------------------------------------------------
theTable = damask.ASCIItable(file['input'],file['output'][i],labels = False)
theTable.labels_clear()
theTable.info_clear()
theTable.info_append(extra_header+[
table = damask.ASCIItable(file['input'],file['output'][i],labels = False)
table.labels_clear()
table.info_clear()
table.info_append(extra_header+[
scriptID + ' ' + ' '.join(sys.argv[1:]),
"grid\ta %i\tb %i\tc %i"%(info['grid'][0],info['grid'][1],info['grid'][2],),
"size\tx %f\ty %f\tz %f"%(info['size'][0],info['size'][1],info['size'][2],),
@ -273,13 +256,13 @@ for file in files:
"homogenization\t%i"%info['homogenization'],
"microstructures\t%i"%(newInfo['microstructures']),
])
theTable.head_write()
theTable.output_flush()
table.head_write()
table.output_flush()
# --- write microstructure information ------------------------------------------------------------
formatwidth = int(math.floor(math.log10(distance[i,:,:,:].max())+1))
theTable.data = distance[i,:,:,:].reshape((info['grid'][0],info['grid'][1]*info['grid'][2]),order='F').transpose()
theTable.data_writeArray('%%%ii'%(formatwidth),delimiter=' ')
table.data = distance[i,:,:,:].reshape((info['grid'][0],info['grid'][1]*info['grid'][2]),order='F').transpose()
table.data_writeArray('%%%ii'%(formatwidth),delimiter=' ')
file['output'][i].close()
#--- output finalization --------------------------------------------------------------------------

View File

@ -1,34 +1,18 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,string,math,numpy
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
import os,sys,string,re,math,random
import numpy as np
from optparse import OptionParser
import damask
scriptID = '$Id$'
scriptName = scriptID.split()[1]
scriptID = string.replace('$Id$','\n','\\n')
scriptName = scriptID.split()[1][:-3]
#--------------------------------------------------------------------------------------------------
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
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
#--------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------
minimal_surfaces = ['primitive','gyroid','diamond',]
surface = {
@ -37,11 +21,11 @@ surface = {
'diamond': lambda x,y,z: math.cos(x-y)*math.cos(z)+math.sin(x+y)*math.sin(z),
}
parser = OptionParser(option_class=extendedOption, usage='%prog', description = """
parser = OptionParser(option_class=damask.extendableOption, usage='%prog', description = """
Generate a geometry file of a bicontinuous structure of given type.
""" + string.replace(scriptID,'\n','\\n')
)
""", version = scriptID)
parser.add_option('-t','--type', dest='type', choices=minimal_surfaces, metavar='string', \
help='type of minimal surface (%s) [primitive]' %(','.join(minimal_surfaces)))
@ -63,24 +47,24 @@ parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
parser.set_defaults(type = minimal_surfaces[0])
parser.set_defaults(threshold = 0.0)
parser.set_defaults(periods = 1)
parser.set_defaults(grid = numpy.array([16,16,16]))
parser.set_defaults(size = numpy.array([1.0,1.0,1.0]))
parser.set_defaults(grid = np.array([16,16,16]))
parser.set_defaults(size = np.array([1.0,1.0,1.0]))
parser.set_defaults(homogenization = 1)
parser.set_defaults(microstructure = [1,2])
parser.set_defaults(twoD = False)
(options, args) = parser.parse_args()
(options,filename) = parser.parse_args()
# ------------------------------------------ setup file handle -------------------------------------
if filename == []:
file = {'output':sys.stdout, 'croak':sys.stderr}
else:
file = {'output':open(filename[0],'w'), 'croak':sys.stderr}
#--- setup file handles ---------------------------------------------------------------------------
file = {'name':'STDIN',
'input':sys.stdin,
'output':sys.stdout,
'croak':sys.stderr,
}
info = {
'grid': numpy.array(options.grid),
'size': numpy.array(options.size),
'origin': numpy.zeros(3,'d'),
'grid': np.array(options.grid),
'size': np.array(options.size),
'origin': np.zeros(3,'d'),
'microstructures': max(options.microstructure),
'homogenization': options.homogenization
}
@ -93,10 +77,10 @@ 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):
if np.any(info['grid'] < 1):
file['croak'].write('invalid grid a b c.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
if np.any(info['size'] <= 0.0):
file['croak'].write('invalid size x y z.\n')
sys.exit()

View File

@ -1,40 +1,25 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,string,math,numpy,time
from optparse import OptionParser, OptionGroup, Option, SUPPRESS_HELP
import os,sys,string,re,math
import numpy as np
from optparse import OptionParser
import damask
scriptID = '$Id$'
scriptName = scriptID.split()[1]
scriptID = string.replace('$Id$','\n','\\n')
scriptName = scriptID.split()[1][:-3]
#------------------------------------------------------------------------------------------------
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
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
#--------------------------------------------------------------------------------------------------
# --------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=extendedOption, usage='%prog', description = """
# --------------------------------------------------------------------
parser = OptionParser(option_class=damask.extendableOption, usage='%prog [options]', 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.
Its fiber orientation is oscillating by +/- amplitude within one period.
""" + string.replace(scriptID,'\n','\\n')
)
""", version = scriptID)
parser.add_option('-g', '--grid', dest='grid', type='int', nargs=2, metavar = 'int int', \
help='a,b grid of hexahedral box %default')
@ -67,41 +52,40 @@ parser.set_defaults(aspect = 1.0)
parser.set_defaults(omega = 0.0)
parser.set_defaults(period = 5e-6)
parser.set_defaults(amplitude = 60)
parser.set_defaults(size = numpy.array([300e-6,300e-6],'d'))
parser.set_defaults(grid = numpy.array([512,512],'i'))
parser.set_defaults(size = np.array([300e-6,300e-6],'d'))
parser.set_defaults(grid = np.array([512,512],'i'))
parser.set_defaults(homogenization = 1)
parser.set_defaults(crystallite = 1)
parser.set_defaults(config = False)
parser.set_defaults(twoD = False)
(options, args) = parser.parse_args()
(options,filename) = parser.parse_args()
#--- setup file handles ---------------------------------------------------------------------------
file = {'name':'STDIN',
'input':sys.stdin,
'output':sys.stdout,
'croak':sys.stderr,
}
# ------------------------------------------ setup file handle -------------------------------------
if filename == []:
file = {'output':sys.stdout, 'croak':sys.stderr}
else:
file = {'output':open(filename[0],'w'), 'croak':sys.stderr}
if numpy.any(options.grid < 2):
if np.any(options.grid < 2):
file['croak'].write('grid too small...\n')
sys.exit()
if numpy.any(options.size <= 0.0):
if np.any(options.size <= 0.0):
file['croak'].write('size too small...\n')
sys.exit()
options.omega *= math.pi/180.0 # rescale ro radians
rotation = numpy.array([[ math.cos(options.omega),math.sin(options.omega),],
rotation = np.array([[ math.cos(options.omega),math.sin(options.omega),],
[-math.sin(options.omega),math.cos(options.omega),]],'d')
box = numpy.dot(numpy.array([[options.canal,0.],[0.,options.aspect*options.canal]]).transpose(),rotation)
box = np.dot(np.array([[options.canal,0.],[0.,options.aspect*options.canal]]).transpose(),rotation)
info = {
'grid': numpy.ones(3,'i'),
'size': numpy.ones(3,'d'),
'origin': numpy.zeros(3,'d'),
'grid': np.ones(3,'i'),
'size': np.ones(3,'d'),
'origin': np.zeros(3,'d'),
'microstructures': 3,
'homogenization': options.homogenization,
}
@ -112,21 +96,21 @@ info['size'][2] = min(info['size'][0]/info['grid'][0],info['size'][1]/info['gri
info['origin'] = -info['size']/2.0
X0 = info['size'][0]/info['grid'][0]*\
(numpy.tile(numpy.arange(info['grid'][0]),(info['grid'][1],1)) - info['grid'][0]/2 + 0.5)
(np.tile(np.arange(info['grid'][0]),(info['grid'][1],1)) - info['grid'][0]/2 + 0.5)
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)
(np.tile(np.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
radius = numpy.sqrt(X*X + Y*Y/options.aspect/options.aspect)
alpha = numpy.degrees(numpy.arctan2(Y/options.aspect,X))
beta = options.amplitude*numpy.sin(2.0*math.pi*(radius-options.canal)/options.period)
radius = np.sqrt(X*X + Y*Y/options.aspect/options.aspect)
alpha = np.degrees(np.arctan2(Y/options.aspect,X))
beta = options.amplitude*np.sin(2.0*math.pi*(radius-options.canal)/options.period)
microstructure = numpy.where(radius < float(options.canal),1,0) + numpy.where(radius > float(options.osteon),2,0)
microstructure = np.where(radius < float(options.canal),1,0) + np.where(radius > float(options.osteon),2,0)
alphaOfGrain = numpy.zeros(info['grid'][0]*info['grid'][1],'d')
betaOfGrain = numpy.zeros(info['grid'][0]*info['grid'][1],'d')
alphaOfGrain = np.zeros(info['grid'][0]*info['grid'][1],'d')
betaOfGrain = np.zeros(info['grid'][0]*info['grid'][1],'d')
for y in xrange(info['grid'][1]):
for x in xrange(info['grid'][0]):
if microstructure[y,x] == 0:
@ -141,12 +125,12 @@ file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,info['grid'])))
'origin x y z: %s\n'%(' : '.join(map(str,info['origin']))) + \
'microstructures: %i\n'%info['microstructures'] + \
'homogenization: %i\n'%info['homogenization'])
file['croak'].write("bounding box: %s\n"%(numpy.sqrt(numpy.sum(box*box,0))))
file['croak'].write("bounding box: %s\n"%(np.sqrt(np.sum(box*box,0))))
if numpy.any(info['grid'] < 1):
if np.any(info['grid'] < 1):
file['croak'].write('invalid grid a b c.\n')
sys.exit()
if numpy.any(info['size'] <= 0.0):
if np.any(info['size'] <= 0.0):
file['croak'].write('invalid size x y z.\n')
sys.exit()
@ -189,7 +173,4 @@ else:
str(microstructure[y,x]).rjust(formatwidth) + \
{True:' ',False:'\n'}[options.twoD] )
file['output'].write({True:'\n',False:''}[options.twoD])
#--- output finalization --------------------------------------------------------------------------
table.output_close()

View File

@ -9,9 +9,10 @@ import damask
scriptID = '$Id$'
scriptName = scriptID.split()[1]
def meshgrid2(*arrs):
'''
code inspired by http://stackoverflow.com/questions/1827489/np-meshgrid-in-3d
code inspired by http://stackoverflow.com/questions/1827489/numpy-meshgrid-in-3d
'''
arrs = tuple(reversed(arrs))
arrs = tuple(arrs)
@ -50,10 +51,9 @@ mappings = {
'homogenization': lambda x: int(x),
'microstructures': lambda x: int(x),
}
parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """
Generate geometry description and material configuration by standard Voronoi tessellation of given seeds file.
""", version = scriptID)
parser.add_option('-g', '--grid', dest='grid', type='int', nargs = 3, metavar = 'int int int', \