same functionality can be accomplished with existing scripts.

addEuclideanDistance + geom_fromTable
(reLabel) + specify grid and size
This commit is contained in:
Philip Eisenlohr 2016-04-24 14:18:29 -05:00
parent 2daa162da2
commit db7c4bba45
2 changed files with 0 additions and 357 deletions

View File

@ -1,219 +0,0 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,sys,math,itertools
import numpy as np
from scipy import ndimage
from optparse import OptionParser
import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0]
scriptID = ' '.join([scriptName,damask.version])
def periodic_3Dpad(array, rimdim=(1,1,1)):
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 = 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]):
for p[side%3] in xrange(rimdim[side%3]):
spot = (p-rimdim)%size
padded[p[0],p[1],p[2]] = array[spot[0],spot[1],spot[2]]
for p[side%3] in xrange(rimdim[side%3]+size[side%3],size[side%3]+2*rimdim[side%3]):
spot = (p-rimdim)%size
padded[p[0],p[1],p[2]] = array[spot[0],spot[1],spot[2]]
return padded
#--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
features = [
{'aliens': 1, 'alias': ['boundary','biplane'],},
{'aliens': 2, 'alias': ['tripleline',],},
{'aliens': 3, 'alias': ['quadruplepoint',],}
]
neighborhoods = {
'neumann':np.array([
[-1, 0, 0],
[ 1, 0, 0],
[ 0,-1, 0],
[ 0, 1, 0],
[ 0, 0,-1],
[ 0, 0, 1],
]),
'moore':np.array([
[-1,-1,-1],
[ 0,-1,-1],
[ 1,-1,-1],
[-1, 0,-1],
[ 0, 0,-1],
[ 1, 0,-1],
[-1, 1,-1],
[ 0, 1,-1],
[ 1, 1,-1],
#
[-1,-1, 0],
[ 0,-1, 0],
[ 1,-1, 0],
[-1, 0, 0],
#
[ 1, 0, 0],
[-1, 1, 0],
[ 0, 1, 0],
[ 1, 1, 0],
#
[-1,-1, 1],
[ 0,-1, 1],
[ 1,-1, 1],
[-1, 0, 1],
[ 0, 0, 1],
[ 1, 0, 1],
[-1, 1, 1],
[ 0, 1, 1],
[ 1, 1, 1],
])
}
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.
""", version = scriptID)
parser.add_option('-t','--type',
dest = 'type',
action = 'extend', metavar = '<string LIST>',
help = 'feature type {%s} '%(', '.join(map(lambda x:'|'.join(x['alias']),features))) )
parser.add_option('-n','--neighborhood',
dest = 'neighborhood',
choices = neighborhoods.keys(), metavar = 'string',
help = 'type of neighborhood {%s} [neumann]'%(', '.join(neighborhoods.keys())))
parser.add_option('-s', '--scale',
dest = 'scale',
type = 'float', metavar = 'float',
help = 'voxel size [%default]')
parser.set_defaults(type = [],
neighborhood = 'neumann',
scale = 1.0,
)
(options,filenames) = parser.parse_args()
if len(options.type) == 0 or \
not set(options.type).issubset(set(list(itertools.chain(*map(lambda x: x['alias'],features))))):
parser.error('sleect feature type from (%s).'%(', '.join(map(lambda x:'|'.join(x['alias']),features))) )
if 'biplane' in options.type and 'boundary' in options.type:
parser.error("only one alias out 'biplane' and 'boundary' required")
feature_list = []
for i,feature in enumerate(features):
for name in feature['alias']:
for myType in options.type:
if name.startswith(myType):
feature_list.append(i) # remember selected features
break
# --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None]
for name in filenames:
try:
table = damask.ASCIItable(name = name,
buffered = False, labeled = False, readonly = True)
except: continue
damask.util.report(scriptName,name)
# --- interpret header ----------------------------------------------------------------------------
table.head_read()
info,extra_header = table.head_getGeom()
damask.util.croak(['grid a b c: %s'%(' x '.join(map(str,info['grid']))),
'size x y z: %s'%(' x '.join(map(str,info['size']))),
'origin x y z: %s'%(' : '.join(map(str,info['origin']))),
'homogenization: %i'%info['homogenization'],
'microstructures: %i'%info['microstructures'],
])
errors = []
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.')
if errors != []:
damask.util.croak(errors)
table.close(dismiss = True)
continue
# --- read data ------------------------------------------------------------------------------------
microstructure = table.microstructure_read(info['grid']).reshape(info['grid'],order='F') # read microstructure
table.close()
neighborhood = neighborhoods[options.neighborhood]
convoluted = np.empty([len(neighborhood)]+list(info['grid']+2),'i')
structure = periodic_3Dpad(microstructure)
for i,p in enumerate(neighborhood):
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)
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 += 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 feature in feature_list:
try:
table = damask.ASCIItable(outname = features[feature]['alias'][0]+'_'+name if name else name,
buffered = False, labeled = False)
except: continue
damask.util.croak(features[feature]['alias'][0])
distance = np.where(uniques >= features[feature]['aliens'],0.0,1.0) # seed with 0.0 when enough unique neighbor IDs are present
distance = ndimage.morphology.distance_transform_edt(distance)*[options.scale]*3
info['microstructures'] = int(math.ceil(distance.max()))
#--- write header ---------------------------------------------------------------------------------
table.info_clear()
table.info_append(extra_header+[
scriptID + ' ' + ' '.join(sys.argv[1:]),
"grid\ta {grid[0]}\tb {grid[1]}\tc {grid[2]}".format(grid=info['grid']),
"size\tx {size[0]}\ty {size[1]}\tz {size[2]}".format(size=info['size']),
"origin\tx {origin[0]}\ty {origin[1]}\tz {origin[2]}".format(origin=info['origin']),
"homogenization\t{homog}".format(homog=info['homogenization']),
"microstructures\t{microstructures}".format(microstructures=info['microstructures']),
])
table.labels_clear()
table.head_write()
# --- write microstructure information ------------------------------------------------------------
formatwidth = int(math.floor(math.log10(distance.max())+1))
table.data = distance.reshape((info['grid'][0],info['grid'][1]*info['grid'][2]),order='F').transpose()
table.data_writeArray('%%%ii'%(formatwidth),delimiter=' ')
#--- output finalization --------------------------------------------------------------------------
table.close()

View File

@ -1,138 +0,0 @@
#!/usr/bin/env python
# -*- coding: UTF-8 no BOM -*-
import os,itertools
import numpy as np
from optparse import OptionParser
import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0]
scriptID = ' '.join([scriptName,damask.version])
#--------------------------------------------------------------------------------------------------
# MAIN
#--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """
Create seed file by taking microstructure indices from given ASCIItable column.
White and black-listing of microstructure indices is possible.
Examples:
--white 1,2,5 --index grainID isolates grainID entries of value 1, 2, and 5;
--black 1 --index grainID takes all grainID entries except for value 1.
""", version = scriptID)
parser.add_option('-p',
'--pos', '--seedposition',
dest = 'pos',
type = 'string', metavar = 'string',
help = 'label of coordinates [%default]')
parser.add_option('--boundingbox',
dest = 'box',
type = 'float', nargs = 6, metavar = ' '.join(['float']*6),
help = 'min (x,y,z) and max (x,y,z) coordinates of bounding box [tight]')
parser.add_option('-m',
'--microstructure',
dest = 'microstructure',
type = 'string', metavar = 'string',
help = 'label of microstructures [%default]')
parser.add_option('--weight',
dest = 'weight',
type = 'string', metavar = 'string',
help = 'label of weights [%default]')
parser.add_option('-w',
'--white',
dest = 'whitelist',
action = 'extend', metavar = '<int LIST>',
help = 'whitelist of microstructure indices')
parser.add_option('-b',
'--black',
dest = 'blacklist',
action = 'extend', metavar = '<int LIST>',
help = 'blacklist of microstructure indices')
parser.set_defaults(pos = 'pos',
microstructure = 'microstructure',
weight = None,
)
(options,filenames) = parser.parse_args()
if options.whitelist is not None: options.whitelist = map(int,options.whitelist)
if options.blacklist is not None: options.blacklist = map(int,options.blacklist)
# --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None]
for name in filenames:
try: table = damask.ASCIItable(name = name,
outname = os.path.splitext(name)[0]+'.seeds' if name else name,
buffered = False)
except: continue
damask.util.report(scriptName,name)
table.head_read() # read ASCII header info
# ------------------------------------------ sanity checks ---------------------------------------
missing_labels = table.data_readArray([options.pos,options.microstructure] +
([options.weight] if options.weight else []))
errors = []
if len(missing_labels) > 0:
errors.append('column{} {} not found'.format('s' if len(missing_labels) > 1 else '',
', '.join(missing_labels)))
input = {options.pos: 3,
options.microstructure: 1,}
if options.weight: input.update({options.weight: 1})
for label, dim in input.iteritems():
if table.label_dimension(label) != dim:
errors.append('column {} has wrong dimension'.format(label))
if errors != []:
damask.util.croak(errors)
table.close(dismiss = True) # close ASCII table file handles and delete output file
continue
# ------------------------------------------ process data ------------------------------------------
# --- finding bounding box -------------------------------------------------------------------------
boundingBox = np.array((np.amin(table.data[:,0:3],axis = 0),np.amax(table.data[:,0:3],axis = 0)))
if options.box:
boundingBox[0,:] = np.minimum(options.box[0:3],boundingBox[0,:])
boundingBox[1,:] = np.maximum(options.box[3:6],boundingBox[1,:])
# --- rescaling coordinates ------------------------------------------------------------------------
table.data[:,0:3] -= boundingBox[0,:]
table.data[:,0:3] /= boundingBox[1,:]-boundingBox[0,:]
# --- filtering of grain voxels --------------------------------------------------------------------
mask = np.logical_and(
np.ones_like(table.data[:,3],bool) if options.whitelist is None \
else np.in1d(table.data[:,3].ravel(), options.whitelist).reshape(table.data[:,3].shape),
np.ones_like(table.data[:,3],bool) if options.blacklist is None \
else np.invert(np.in1d(table.data[:,3].ravel(), options.blacklist).reshape(table.data[:,3].shape))
)
table.data = table.data[mask]
# ------------------------------------------ assemble header ---------------------------------------
table.info = [
scriptID,
'size {}'.format(' '.join(list(itertools.chain.from_iterable(zip(['x','y','z'],
map(str,boundingBox[1,:]-boundingBox[0,:])))))),
]
table.labels_clear()
table.labels_append(['1_pos','2_pos','3_pos','microstructure'] +
['weight'] if options.weight else []) # implicitly switching label processing/writing on
table.head_write()
# ------------------------------------------ output result ---------------------------------------
table.data_writeArray()
table.close() # close ASCII tables