more fixes following new possibilities of ascii table

This commit is contained in:
Martin Diehl 2015-09-08 19:42:14 +00:00
parent 4e9b27b0ce
commit 1c164574ac
2 changed files with 78 additions and 73 deletions

View File

@ -47,7 +47,7 @@ for name in filenames:
table = damask.ASCIItable(name = name, table = damask.ASCIItable(name = name,
buffered = False, labeled = False) buffered = False, labeled = False)
except: continue except: continue
table.croak('\033[1m'+scriptName+'\033[0m'+(': '+name if name else '')) table.croak(damask.util.emph(scriptName)+(': '+name if name else ''))
# --- interpret header ---------------------------------------------------------------------------- # --- interpret header ----------------------------------------------------------------------------

View File

@ -13,7 +13,9 @@ scriptName = os.path.splitext(scriptID.split()[1])[0]
# MAIN # MAIN
#-------------------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------
parser = OptionParser(option_class=damask.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 input files used by R.A. Lebensohn.
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.
""", version = scriptID) """, version = scriptID)
@ -31,65 +33,67 @@ parser.add_option('-c', '--configuration', dest='config', action='store_true',
help='output material configuration [%default]') help='output material configuration [%default]')
parser.add_option('--compress', dest='compress', action='store_true', parser.add_option('--compress', dest='compress', action='store_true',
help='lump identical microstructure and texture information [%default]') help='lump identical microstructure and texture information [%default]')
parser.add_option('-a', '--axes', dest='axes', nargs = 3, metavar = 'string string string',
help='Euler angle coordinate system for <texture> configuration x,y,z = %default')
parser.add_option('-p', '--precision', dest='precision', choices=['0','1','2','3'], metavar = 'int', parser.add_option('-p', '--precision', dest='precision', choices=['0','1','2','3'], metavar = 'int',
help = 'euler angles decimal places for output format and compressing (0,1,2,3) [2]') help = 'euler angles decimal places for output format and compressing (0,1,2,3) [2]')
parser.set_defaults(column = 7) parser.set_defaults(column = 11)
parser.set_defaults(threshold = 1.0) parser.set_defaults(threshold = 0.5)
parser.set_defaults(homogenization = 1) parser.set_defaults(homogenization = 1)
parser.set_defaults(phase = [1,2]) parser.set_defaults(phase = [1,2])
parser.set_defaults(crystallite = 1) parser.set_defaults(crystallite = 1)
parser.set_defaults(config = False) parser.set_defaults(config = False)
parser.set_defaults(compress = False) parser.set_defaults(compress = False)
parser.set_defaults(axes = ['y','x','-z'])
parser.set_defaults(precision = '2') parser.set_defaults(precision = '2')
(options,filenames) = parser.parse_args() (options,filenames) = parser.parse_args()
#--- setup file handles ---------------------------------------------------------------------------
files = []
if filenames == []:
files.append({'name':'STDIN',
'input':sys.stdin,
'output':sys.stdout,
'croak':sys.stderr,
})
else:
for name in filenames:
if os.path.exists(name):
files.append({'name':name,
'input':open(name),
'output':open(name+'_tmp','w'),
'croak':sys.stdout,
})
for i in options.axes:
if i.lower() not in ['x','+x','-x','y','+y','-y','z','+z','-z']:
parser.error('invalid axes %s %s %s' %(options.axes[0],options.axes[1],options.axes[2]))
#--- loop over input files ------------------------------------------------------------------------ # --- loop over input files -------------------------------------------------------------------------
for file in files:
file['croak'].write('\033[1m' + scriptName + '\033[0m: ' + (file['name'] if file['name'] != 'STDIN' else '') + '\n') if filenames == []: filenames = [None]
for name in filenames:
try:
table = damask.ASCIItable(name = name, outname = os.path.splitext(name)[0] +'%s'%('_material.config' if options.config else '.geom'),
buffered = False, labeled = False, readonly=True)
except: continue
table.croak(damask.util.emph(scriptName)+(': '+name if name else ''))
info = { info = {
'grid': np.zeros(3,'i'), 'grid': np.ones(3,'i'),
'size': np.zeros(3,'d'), 'size': np.zeros(3,'d'),
'origin': np.zeros(3,'d'), 'origin': np.zeros(3,'d'),
'microstructures': 0, 'microstructures': 0,
'homogenization': options.homogenization 'homogenization': options.homogenization
} }
coords = [{},{},{}] coords = [{},{},{1:True}]
pos = {'min':[ float("inf"), float("inf"), float("inf")], pos = {'min':[ float("inf"), float("inf")],
'max':[-float("inf"),-float("inf"),-float("inf")]} 'max':[-float("inf"),-float("inf")]}
phase = [] phase = []
eulerangles = [] eulerangles = []
# --------------- read data ----------------------------------------------------------------------- # --------------- read data -----------------------------------------------------------------------
for line in file['input']: while table.data_read():
if line.strip(): words = table.data
words = line.split() if words[0] == '#': # process initial comments/header block
currPos = words[3:6] if len(words) > 2:
for i in xrange(3): if words[2].lower() == 'hexgrid':
table.croak('The file has HexGrid format. Please first convert to SquareGrid...\n')
break
else:
currPos = words[3:5]
for i in xrange(2):
coords[i][currPos[i]] = True coords[i][currPos[i]] = True
currPos = map(float,currPos) currPos = map(float,currPos)
for i in xrange(3): for i in xrange(2):
pos['min'][i] = min(pos['min'][i],currPos[i]) pos['min'][i] = min(pos['min'][i],currPos[i])
pos['max'][i] = max(pos['max'][i],currPos[i]) pos['max'][i] = max(pos['max'][i],currPos[i])
eulerangles.append(map(math.degrees,map(float,words[:3]))) eulerangles.append(map(math.degrees,map(float,words[:3])))
@ -97,19 +101,19 @@ for file in files:
# --------------- determine size and grid --------------------------------------------------------- # --------------- determine size and grid ---------------------------------------------------------
info['grid'] = np.array(map(len,coords),'i') info['grid'] = np.array(map(len,coords),'i')
info['size'] = info['grid']/np.maximum(np.ones(3,'d'),info['grid']-1.0)* \ info['size'][0:2] = info['grid'][0:2]/(info['grid'][0:2]-1.0)* \
np.array([pos['max'][0]-pos['min'][0], np.array([pos['max'][0]-pos['min'][0],
pos['max'][1]-pos['min'][1], pos['max'][1]-pos['min'][1]],'d')
pos['max'][2]-pos['min'][2]],'d') info['size'][2]=info['size'][0]/info['grid'][0]
eulerangles = np.array(eulerangles,dtype='f').reshape(info['grid'].prod(),3) eulerangles = np.array(eulerangles,dtype='f').reshape(info['grid'].prod(),3)
phase = np.array(phase,dtype='i').reshape(info['grid'].prod()) phase = np.array(phase,dtype='i').reshape(info['grid'].prod())
limits = [360,180,360] limits = [360,180,360]
if any([np.any(eulerangles[:,i]>=limits[i]) for i in [0,1,2]]): if any([np.any(eulerangles[:,i]>=limits[i]) for i in [0,1,2]]):
file['croak'].write('Error: euler angles out of bound. Ang file might contain unidexed poins.\n') table.croak('Error: euler angles out of bound. Ang file might contain unidexed poins.\n')
for i,angle in enumerate(['phi1','PHI','phi2']): for i,angle in enumerate(['phi1','PHI','phi2']):
for n in np.nditer(np.where(eulerangles[:,i]>=limits[i]),['zerosize_ok']): for n in np.nditer(np.where(eulerangles[:,i]>=limits[i]),['zerosize_ok']):
file['croak'].write('%s in line %i (%4.2f %4.2f %4.2f)\n' table.croak('%s in line %i (%4.2f %4.2f %4.2f)\n'
%(angle,n,eulerangles[n,0],eulerangles[n,1],eulerangles[n,2])) %(angle,n,eulerangles[n,0],eulerangles[n,1],eulerangles[n,2]))
continue continue
eulerangles=np.around(eulerangles,int(options.precision)) # round to desired precision eulerangles=np.around(eulerangles,int(options.precision)) # round to desired precision
@ -121,7 +125,7 @@ for file in files:
euleranglesRadInt = (eulerangles*10**int(options.precision)).astype('int') # scale by desired precision and convert to int euleranglesRadInt = (eulerangles*10**int(options.precision)).astype('int') # scale by desired precision and convert to int
eulerKeys = np.array([int(''.join(map(formatString.format,euleranglesRadInt[i,:]))) \ eulerKeys = np.array([int(''.join(map(formatString.format,euleranglesRadInt[i,:]))) \
for i in xrange(info['grid'].prod())]) # create unique integer key from three euler angles by concatenating the string representation with leading zeros and store as integer for i in xrange(info['grid'].prod())]) # create unique integer key from three euler angles by concatenating the string representation with leading zeros and store as integer
devNull, texture, eulerKeys_idx = np.unique(eulerKeys, return_index = True, return_inverse=True)# search unique euler angle keys. Texture IDs are the indices of the first occurence, the inverse is used to construct the microstructure devNull, texture, eulerKeys_idx = np.unique(eulerKeys, return_index = True, return_inverse=True)# search unique euler angle keys. Texture IDs are the indices of the first occurrence, the inverse is used to construct the microstructure
msFull = np.array([[eulerKeys_idx[i],phase[i]] for i in xrange(info['grid'].prod())],'i8') # create a microstructure (texture/phase pair) for each point using unique texture IDs. Use longInt (64bit, i8) because the keys might be long msFull = np.array([[eulerKeys_idx[i],phase[i]] for i in xrange(info['grid'].prod())],'i8') # create a microstructure (texture/phase pair) for each point using unique texture IDs. Use longInt (64bit, i8) because the keys might be long
devNull,msUnique,matPoints = np.unique(msFull.view('c16'),True,True) devNull,msUnique,matPoints = np.unique(msFull.view('c16'),True,True)
matPoints+=1 matPoints+=1
@ -136,6 +140,7 @@ for file in files:
outStringAngles='(gauss) phi1 '+eulerFormatOut+' Phi '+eulerFormatOut+' phi2 '+eulerFormatOut+' scatter 0.0 fraction 1.0\n' outStringAngles='(gauss) phi1 '+eulerFormatOut+' Phi '+eulerFormatOut+' phi2 '+eulerFormatOut+' scatter 0.0 fraction 1.0\n'
for i in xrange(len(texture)): for i in xrange(len(texture)):
textureOut += ['[Texture%s]\n'%str(i+1).zfill(formatOut) + textureOut += ['[Texture%s]\n'%str(i+1).zfill(formatOut) +
'axes %s %s %s\n'%(options.axes[0],options.axes[1],options.axes[2]) +
outStringAngles%tuple(eulerangles[texture[i],...]) outStringAngles%tuple(eulerangles[texture[i],...])
] ]
formatOut = 1+int(math.log10(len(microstructure))) formatOut = 1+int(math.log10(len(microstructure)))
@ -149,41 +154,41 @@ for file in files:
info['microstructures'] = len(microstructure) info['microstructures'] = len(microstructure)
#--- report --------------------------------------------------------------------------------------- #--- report ---------------------------------------------------------------------------------------
file['croak'].write('grid a b c: %s\n'%(' x '.join(map(str,info['grid']))) + table.croak('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\n'%info['microstructures']) 'microstructures: %i\n\n'%info['microstructures'])
if np.any(info['grid'] < 1): if np.any(info['grid'] < 1):
file['croak'].write('invalid grid a b c.\n') table.croak('invalid grid a b c.\n')
continue continue
if np.any(info['size'] <= 0.0): if np.any(info['size'] <= 0.0):
file['croak'].write('invalid size x y z.\n') table.croak('invalid size x y z.\n')
continue continue
#--- write data ----------------------------------------------------------------------------------- #--- write data/header --------------------------------------------------------------------------------
table.info_clear()
if options.config: if options.config:
file['output'].write('\n'.join(microstructureOut+ textureOut) + '\n') table.output_write(line for line in microstructureOut+ textureOut)
else: else:
header = [' '.join([scriptID] + sys.argv[1:]), table.info_append([' '.join([scriptID] + sys.argv[1:]),
"grid\ta %i\tb %i\tc %i"%(info['grid'][0],info['grid'][1],info['grid'][2],), "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],), "size\tx %f\ty %f\tz %f"%(info['size'][0],info['size'][1],info['size'][2],),
"origin\tx %f\ty %f\tz %f"%(info['origin'][0],info['origin'][1],info['origin'][2],), "origin\tx %f\ty %f\tz %f"%(info['origin'][0],info['origin'][1],info['origin'][2],),
"microstructures\t%i"%info['microstructures'], "microstructures\t%i"%info['microstructures'],
"homogenization\t%i"%info['homogenization'], "homogenization\t%i"%info['homogenization'],
] ])
file['output'].write('\n'.join(['%i\theader'%(len(header))] + header) + '\n') table.head_write()
if options.compress: if options.compress:
matPoints = matPoints.reshape([info['grid'][1]*info['grid'][2],info['grid'][0]]) matPoints = matPoints.reshape((info['grid'][1],info['grid'][0]))
np.savetxt(file['output'],matPoints,fmt='%0'+str(1+int(math.log10(np.amax(matPoints))))+'d') table.data = matPoints
table.data_writeArray('%%%ii'%(1+int(math.log10(np.amax(matPoints)))),delimiter=' ')
else: else:
file['output'].write("1 to %i\n"%(info['microstructures'])) table.output_write("1 to %i\n"%(info['microstructures']))
table.output_flush()
#--- output finalization -------------------------------------------------------------------------- # --- output finalization --------------------------------------------------------------------------
if file['name'] != 'STDIN':
file['output'].close()
os.rename(file['name']+'_tmp',
os.path.splitext(file['name'])[0] +'%s'%('_material.config' if options.config else '.geom'))
table.close()