renaming of (loosely related) "spectral" scripts to (more tightly related) "geom" versions.
This commit is contained in:
parent
639d6e0655
commit
1bd4262cfb
|
@ -45,9 +45,9 @@ Changes the (three-dimensional) canvas of a spectral geometry description.
|
|||
)
|
||||
|
||||
parser.add_option('-b', '--box', dest='resolution', type='int', nargs = 3, \
|
||||
help='resolution of new canvas (a,b,c)')
|
||||
help='resolution of new canvas (a,b,c) %default')
|
||||
parser.add_option('-o', '--offset', dest='offset', type='int', nargs = 3, \
|
||||
help='offset from old to new origin of grid')
|
||||
help='offset from old to new origin of grid %default')
|
||||
parser.add_option('-f', '--fill', dest='fill', type='int', \
|
||||
help='(background) canvas grain index')
|
||||
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
|
||||
|
@ -64,16 +64,24 @@ parser.set_defaults(fill = 0)
|
|||
|
||||
files = []
|
||||
if filenames == []:
|
||||
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout})
|
||||
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')})
|
||||
files.append({'name':name,
|
||||
'input':open(name),
|
||||
'output':open(name+'_tmp','w'),
|
||||
'croak':sys.stdout,
|
||||
})
|
||||
|
||||
# ------------------------------------------ loop over input files ---------------------------------------
|
||||
|
||||
for file in files:
|
||||
if file['name'] != 'STDIN': print file['name']
|
||||
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
|
||||
|
||||
|
@ -88,17 +96,10 @@ for file in files:
|
|||
|
||||
content = file['input'].readlines()
|
||||
file['input'].close()
|
||||
if 0 in options.resolution:
|
||||
for header in headers:
|
||||
headitems = header.split()
|
||||
if headitems[0] == 'resolution': # located resolution entry
|
||||
for i in xrange(3):
|
||||
options.resolution[i] = \
|
||||
mappings['resolution'](headitems[headitems.index(identifiers['resolution'][i])+1])
|
||||
|
||||
info = {'resolution': [0,0,0],
|
||||
'dimension': [0.0,0.0,0.0],
|
||||
'origin': [0.0,0.0,0.0],
|
||||
info = {'resolution': numpy.array(options.resolution),
|
||||
'dimension': numpy.array([0.0,0.0,0.0]),
|
||||
'origin': numpy.array([0.0,0.0,0.0]),
|
||||
'homogenization': 1,
|
||||
}
|
||||
|
||||
|
@ -113,17 +114,19 @@ for file in files:
|
|||
else:
|
||||
info[headitems[0]] = mappings[headitems[0]](headitems[1])
|
||||
|
||||
if info['resolution'] == [0,0,0]:
|
||||
print 'no resolution info found.'
|
||||
if options.resolution == [0,0,0]:
|
||||
options.resolution = info['resolution']
|
||||
if info['resolution'].all() == 0:
|
||||
file['croak'].write('no resolution info found.\n')
|
||||
continue
|
||||
if info['dimension'] == [0.0,0.0,0.0]:
|
||||
print 'no dimension info found.'
|
||||
file['croak'].write('no dimension info found.\n')
|
||||
continue
|
||||
|
||||
if file['name'] != 'STDIN':
|
||||
print 'resolution: %s'%(' x '.join(map(str,info['resolution'])))
|
||||
print 'dimension: %s'%(' x '.join(map(str,info['dimension'])))
|
||||
print 'origin: %s'%(' x '.join(map(str,info['origin'])))
|
||||
file['croak'].write('resolution: %s\n'%(' x '.join(map(str,info['resolution']))) + \
|
||||
'dimension: %s\n'%(' x '.join(map(str,info['dimension']))) + \
|
||||
'origin: %s\n'%(' : '.join(map(str,info['origin']))) + \
|
||||
'homogenization: %i\n'%info['homogenization'])
|
||||
|
||||
new_header.append("resolution\ta %i\tb %i\tc %i\n"%(
|
||||
options.resolution[0],
|
||||
|
@ -145,7 +148,7 @@ for file in files:
|
|||
for item in map(int,line.split()):
|
||||
microstructure[i%info['resolution'][0],
|
||||
(i/info['resolution'][0])%info['resolution'][1],
|
||||
i/info['resolution'][0]/info['resolution'][1]] = item
|
||||
i/info['resolution'][0] /info['resolution'][1]] = item
|
||||
i += 1
|
||||
|
||||
microstructure_cropped = numpy.zeros(options.resolution,'i')
|
|
@ -0,0 +1,232 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
import os,sys,math,string,re,numpy, damask
|
||||
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
|
||||
|
||||
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
|
||||
# --------------------------------------------------------------------
|
||||
identifiers = {
|
||||
'resolution': ['a','b','c'],
|
||||
}
|
||||
mappings = {
|
||||
'resolution': lambda x: int(x),
|
||||
'grains': lambda x: int(x),
|
||||
}
|
||||
|
||||
parser = OptionParser(option_class=extendedOption, usage='%prog options [file[s]]', description = """
|
||||
generates geom file and material_config file using seeds file
|
||||
|
||||
""" + string.replace('$Id$','\n','\\n')
|
||||
)
|
||||
|
||||
parser.add_option('-r', '--resolution', dest='resolution', type='int', nargs = 3, \
|
||||
help='a,b,c resolution of specimen')
|
||||
parser.add_option('-d', '--dimension', dest='dimension', type='float', nargs = 3, \
|
||||
help='x,y,z dimension of specimen')
|
||||
parser.add_option('--homogenization', dest='homogenization', type='int', \
|
||||
help='homogenization index to be used')
|
||||
parser.add_option('--phase', dest='phase', type='int', \
|
||||
help='phase index to be used')
|
||||
parser.add_option('-c', '--configuration', dest='config', action='store_true', \
|
||||
help='output material configuration')
|
||||
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
|
||||
help='output geom file with two-dimensional data arrangement')
|
||||
|
||||
|
||||
parser.set_defaults(resolution = [0,0,0])
|
||||
parser.set_defaults(dimension = [0.0,0.0,0.0])
|
||||
parser.set_defaults(homogenization = 1)
|
||||
parser.set_defaults(phase = 1)
|
||||
parser.set_defaults(config = False)
|
||||
parser.set_defaults(twoD = False)
|
||||
|
||||
(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,
|
||||
})
|
||||
|
||||
|
||||
# ------------------------------------------ loop over input files ---------------------------------------
|
||||
|
||||
for file in files:
|
||||
if file['name'] != 'STDIN': file['croak'].write(file['name']+'\n')
|
||||
|
||||
firstline = file['input'].readline()
|
||||
m = re.search('(\d+)\s*head', firstline.lower())
|
||||
if m:
|
||||
headerlines = int(m.group(1))
|
||||
headers = [firstline]+[file['input'].readline() for i in range(headerlines)]
|
||||
else:
|
||||
headerlines = 1
|
||||
headers = firstline
|
||||
|
||||
content = file['input'].readlines()
|
||||
file['input'].close()
|
||||
|
||||
info = {'grains': 0,
|
||||
'resolution': numpy.array([0,0,0]),
|
||||
'dimension': numpy.array(options.dimension),
|
||||
'origin': numpy.array([0.0,0.0,0.0]),
|
||||
'homogenization': options.homogenization,
|
||||
}
|
||||
|
||||
new_header = []
|
||||
for header in headers:
|
||||
headitems = map(str.lower,header.split())
|
||||
if headitems[0] in mappings.keys():
|
||||
if headitems[0] in identifiers.keys():
|
||||
for i in xrange(len(identifiers[headitems[0]])):
|
||||
info[headitems[0]][i] = \
|
||||
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
|
||||
else:
|
||||
info[headitems[0]] = mappings[headitems[0]](headitems[1])
|
||||
|
||||
if info['grains'] == 0:
|
||||
file['croak'].write('no grains found.\n')
|
||||
continue
|
||||
if info['grains'] != len(content):
|
||||
file['croak'].write('grain data not matching grain count...\n')
|
||||
info['grains'] = min(info['grains'],len(content))
|
||||
|
||||
if 0 not in options.resolution: # user-specified resolution
|
||||
info['resolution'] = numpy.array(options.resolution)
|
||||
|
||||
if info['resolution'].all() == 0:
|
||||
file['croak'].write('no resolution info found.\n')
|
||||
continue
|
||||
|
||||
twoD = info['resolution'][2] < 2
|
||||
|
||||
for i in xrange(3):
|
||||
if info['dimension'][i] <= 0.0: # any invalid dimension?
|
||||
info['dimension'][i] = float(info['resolution'][i])/max(info['resolution'])
|
||||
file['croak'].write('rescaling dimension %i...\n'%i)
|
||||
|
||||
file['croak'].write('grains: %i\n'%info['grains'] + \
|
||||
'resolution: %s\n'%(' x '.join(map(str,info['resolution']))) + \
|
||||
'dimension: %s\n'%(' x '.join(map(str,info['dimension']))) + \
|
||||
'origin: %s\n'%(' : '.join(map(str,info['origin']))) + \
|
||||
'homogenization: %i\n'%info['homogenization'])
|
||||
|
||||
new_header.append("resolution\ta %i\tb %i\tc %i\n"%(
|
||||
info['resolution'][0],
|
||||
info['resolution'][1],
|
||||
info['resolution'][2],))
|
||||
new_header.append("dimension\tx %f\ty %f\tz %f\n"%(
|
||||
info['dimension'][0],
|
||||
info['dimension'][1],
|
||||
info['dimension'][2],))
|
||||
new_header.append("origin\tx %f\ty %f\tz %f\n"%(
|
||||
info['origin'][0],
|
||||
info['origin'][1],
|
||||
info['origin'][2],))
|
||||
new_header.append("homogenization\t%i\n"%info['homogenization'])
|
||||
|
||||
# -------------------------------------- prepare data ----------------------------------
|
||||
|
||||
formatwidth = 1+int(math.log10(info['grains']))
|
||||
coords = numpy.zeros((3,info['grains']),'d')
|
||||
eulers = numpy.zeros((3,info['grains']),'d')
|
||||
|
||||
for i in xrange(info['grains']):
|
||||
coords[:,i] = map(float,content[i].split()[:3])*info['dimension']
|
||||
eulers[:,i] = map(float,content[i].split()[3:6])
|
||||
|
||||
# -------------------------------------- switch according to task ----------------------------------
|
||||
|
||||
if options.config:
|
||||
file['output'].write('<microstructure>\n')
|
||||
for i in xrange(info['grains']):
|
||||
file['output'].write('\n[Grain%s]\n'%(str(i+1).zfill(formatwidth)) + \
|
||||
'crystallite 1\n' + \
|
||||
'(constituent)\tphase %i\ttexture %s\tfraction 1.0\n'%(options.phase,str(i+1).rjust(formatwidth)))
|
||||
|
||||
file['output'].write('\n<texture>\n')
|
||||
for i in xrange(info['grains']):
|
||||
file['output'].write('\n[Grain%s]\n'%(str(i+1).zfill(formatwidth)) + \
|
||||
'(gauss)\tphi1 %g\tPhi %g\tphi2 %g\tscatter 0.0\tfraction 1.0\n'%(eulers[0,i],eulers[1,i],eulers[2,i]))
|
||||
|
||||
else:
|
||||
file['output'].write('%i\theader\n'%(len(new_header)) + ''.join(new_header))
|
||||
|
||||
N = info['resolution'].prod()
|
||||
shift = 0.5*info['dimension']/info['resolution'] # shift by half of side length to center of element
|
||||
undeformed = numpy.zeros((3,N),'d')
|
||||
|
||||
for i in xrange(N):
|
||||
undeformed[0,i] = info['dimension'][0]\
|
||||
* float(i % info['resolution'][0])\
|
||||
/float(info['resolution'][0])
|
||||
undeformed[1,i] = info['dimension'][1]\
|
||||
* float(i//info['resolution'][0] % info['resolution'][1])\
|
||||
/float(info['resolution'][1])
|
||||
undeformed[2,i] = info['dimension'][2]\
|
||||
* float(i//info['resolution'][0]//info['resolution'][1] % info['resolution'][2])\
|
||||
/float(info['resolution'][2])
|
||||
undeformed[:,i] += shift
|
||||
|
||||
indices = damask.core.math.math_nearestNeighborSearch(3,\
|
||||
numpy.array(([1.0,0.0,0.0],\
|
||||
[0.0,1.0,0.0],\
|
||||
[0.0,0.0,1.0]),'d'),\
|
||||
info['dimension'],\
|
||||
N,info['grains'],undeformed,coords)//3**3 + 1 # floor division to kill periodic images
|
||||
|
||||
for n in xrange(info['resolution'][1:3].prod()): # loop over 2nd and 3rd dimension
|
||||
file['output'].write({ True: ' ',
|
||||
False:'\n'}[options.twoD].\
|
||||
join(map(lambda x: str(x).rjust(formatwidth),\
|
||||
indices[n*info['resolution'][0]:(n+1)*info['resolution'][0]]))+'\n')
|
||||
|
||||
missing = 0
|
||||
for i in xrange(info['grains']):
|
||||
if i+1 not in indices: missing += 1
|
||||
file['croak'].write({True:'all',False:'only'}[missing == 0] + ' %i grains mapped.\n'%(info['grains']-missing))
|
||||
|
||||
# ------------------------------------------ output finalization ---------------------------------------
|
||||
|
||||
if file['name'] != 'STDIN':
|
||||
file['output'].close()
|
||||
os.rename(file['name']+'_tmp',os.path.splitext(file['name'])[0] + \
|
||||
{True: '_material.config',
|
||||
False:'.geom'}[options.config])
|
||||
|
|
@ -0,0 +1,179 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: UTF-8 no BOM -*-
|
||||
|
||||
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
|
||||
|
||||
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 -------------------------------
|
||||
|
||||
identifiers = {
|
||||
'resolution': ['a','b','c'],
|
||||
'dimension': ['x','y','z'],
|
||||
'origin': ['x','y','z'],
|
||||
}
|
||||
mappings = {
|
||||
'resolution': lambda x: int(x),
|
||||
'dimension': lambda x: float(x),
|
||||
'origin': lambda x: float(x),
|
||||
'homogenization': lambda x: int(x),
|
||||
}
|
||||
|
||||
|
||||
parser = OptionParser(option_class=extendedOption, usage='%prog options [file[s]]', description = """
|
||||
Scales a geometry description independently in x, y, and z direction in terms of resolution and/or dimension.
|
||||
""" + string.replace('$Id$','\n','\\n')
|
||||
)
|
||||
|
||||
parser.add_option('-r', '--resolution', dest='resolution', type='int', nargs = 3, \
|
||||
help='new resolution (a,b,c)')
|
||||
parser.add_option('-d', '--dimension', dest='dimension', type='float', nargs = 3, \
|
||||
help='new dimension (x,y,z)')
|
||||
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
|
||||
help='output geom file with two-dimensional data arrangement')
|
||||
|
||||
parser.set_defaults(resolution = [0,0,0])
|
||||
parser.set_defaults(dimension = [0.0,0.0,0.0])
|
||||
parser.set_defaults(twoD = False)
|
||||
|
||||
(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,
|
||||
})
|
||||
|
||||
# ------------------------------------------ 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:
|
||||
headerlines = int(m.group(1))
|
||||
headers = [firstline]+[file['input'].readline() for i in range(headerlines)]
|
||||
else:
|
||||
headerlines = 1
|
||||
headers = firstline
|
||||
|
||||
content = file['input'].readlines()
|
||||
file['input'].close()
|
||||
|
||||
info = {'resolution': numpy.array(options.resolution),
|
||||
'dimension': numpy.array(options.dimension),
|
||||
'origin': numpy.array([0.0,0.0,0.0]),
|
||||
'homogenization': 1,
|
||||
}
|
||||
|
||||
new_header = []
|
||||
for header in headers:
|
||||
headitems = map(str.lower,header.split())
|
||||
if headitems[0] in mappings.keys():
|
||||
if headitems[0] in identifiers.keys():
|
||||
for i in xrange(len(identifiers[headitems[0]])):
|
||||
info[headitems[0]][i] = \
|
||||
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
|
||||
else:
|
||||
info[headitems[0]] = mappings[headitems[0]](headitems[1])
|
||||
|
||||
if info['resolution'].all() == 0:
|
||||
file['croak'].write('no resolution info found.\n')
|
||||
continue
|
||||
if info['dimension'].all() == 0.0:
|
||||
file['croak'].write('no dimension info found.\n')
|
||||
continue
|
||||
|
||||
if options.resolution == [0,0,0]:
|
||||
options.resolution = info['resolution']
|
||||
if options.dimension == [0.0,0.0,0.0]:
|
||||
options.dimension = info['dimension']
|
||||
|
||||
file['croak'].write('resolution: %s\n'%(' x '.join(map(str,info['resolution']))) + \
|
||||
'dimension: %s\n'%(' x '.join(map(str,info['dimension']))) + \
|
||||
'origin: %s\n'%(' : '.join(map(str,info['origin']))) + \
|
||||
'homogenization: %i\n'%info['homogenization'])
|
||||
|
||||
new_header.append("resolution\ta %i\tb %i\tc %i\n"%(
|
||||
options.resolution[0],
|
||||
options.resolution[1],
|
||||
options.resolution[2],))
|
||||
new_header.append("dimension\tx %f\ty %f\tz %f\n"%(
|
||||
options.dimension[0],
|
||||
options.dimension[1],
|
||||
options.dimension[2],))
|
||||
new_header.append("origin\tx %f\ty %f\tz %f\n"%(
|
||||
info['origin'][0],
|
||||
info['origin'][1],
|
||||
info['origin'][2],))
|
||||
new_header.append("homogenization\t%i\n"%info['homogenization'])
|
||||
|
||||
microstructure = numpy.zeros(info['resolution'],'i')
|
||||
i = 0
|
||||
for line in content:
|
||||
for item in map(int,line.split()):
|
||||
microstructure[i%info['resolution'][0],
|
||||
(i/info['resolution'][0])%info['resolution'][1],
|
||||
i/info['resolution'][0] /info['resolution'][1]] = item
|
||||
i += 1
|
||||
|
||||
formatwidth = 1+int(math.floor(math.log10(microstructure.max())))
|
||||
|
||||
# ------------------------------------------ assemble header ---------------------------------------
|
||||
|
||||
output = '%i\theader\n'%(len(new_header))
|
||||
output += ''.join(new_header)
|
||||
|
||||
# ------------------------------------- regenerate texture information ----------------------------------
|
||||
|
||||
for c in xrange(options.resolution[2]):
|
||||
z = int(info['resolution'][2]*(c+0.5)/options.resolution[2])%info['resolution'][2]
|
||||
for b in xrange(options.resolution[1]):
|
||||
y = int(info['resolution'][1]*(b+0.5)/options.resolution[1])%info['resolution'][1]
|
||||
for a in xrange(options.resolution[0]):
|
||||
x = int(info['resolution'][0]*(a+0.5)/options.resolution[0])%info['resolution'][0]
|
||||
output += str(microstructure[x,y,z]).rjust(formatwidth) + {True:' ',False:'\n'}[options.twoD]
|
||||
output += {True:'\n',False:''}[options.twoD]
|
||||
|
||||
# ------------------------------------------ output result ---------------------------------------
|
||||
|
||||
file['output'].write(output)
|
||||
|
||||
file['input'].close()
|
||||
if file['name'] != 'STDIN':
|
||||
file['output'].close()
|
||||
|
|
@ -68,16 +68,24 @@ for i in xrange(len(options.substitute)/2):
|
|||
|
||||
files = []
|
||||
if filenames == []:
|
||||
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout})
|
||||
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')})
|
||||
files.append({'name':name,
|
||||
'input':open(name),
|
||||
'output':open(name+'_tmp','w'),
|
||||
'croak':sys.stdout,
|
||||
})
|
||||
|
||||
# ------------------------------------------ loop over input files ---------------------------------------
|
||||
|
||||
for file in files:
|
||||
if file['name'] != 'STDIN': print file['name']
|
||||
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
|
||||
|
||||
|
@ -93,9 +101,9 @@ for file in files:
|
|||
content = file['input'].readlines()
|
||||
file['input'].close()
|
||||
|
||||
info = {'resolution': [0,0,0],
|
||||
'dimension': [0.0,0.0,0.0],
|
||||
'origin': [0.0,0.0,0.0],
|
||||
info = {'resolution': numpy.array([0,0,0]),
|
||||
'dimension': numpy.array([0.0,0.0,0.0]),
|
||||
'origin': numpy.array([0.0,0.0,0.0]),
|
||||
'homogenization': 1,
|
||||
}
|
||||
|
||||
|
@ -110,17 +118,17 @@ for file in files:
|
|||
else:
|
||||
info[headitems[0]] = mappings[headitems[0]](headitems[1])
|
||||
|
||||
if info['resolution'] == [0,0,0]:
|
||||
print 'no resolution info found.'
|
||||
if info['resolution'].all() == 0:
|
||||
file['croak'].write('no resolution info found.\n')
|
||||
continue
|
||||
if info['dimension'] == [0.0,0.0,0.0]:
|
||||
print 'no dimension info found.'
|
||||
file['croak'].write('no dimension info found.\n')
|
||||
continue
|
||||
|
||||
if file['name'] != 'STDIN':
|
||||
print 'resolution: %s'%(' x '.join(map(str,info['resolution'])))
|
||||
print 'dimension: %s'%(' x '.join(map(str,info['dimension'])))
|
||||
print 'origin: %s'%(' : '.join(map(str,info['origin'])))
|
||||
file['croak'].write('resolution: %s\n'%(' x '.join(map(str,info['resolution']))) + \
|
||||
'dimension: %s\n'%(' x '.join(map(str,info['dimension']))) + \
|
||||
'origin: %s\n'%(' : '.join(map(str,info['origin']))) + \
|
||||
'homogenization: %i\n'%info['homogenization'])
|
||||
|
||||
new_header.append("resolution\ta %i\tb %i\tc %i\n"%(
|
||||
info['resolution'][0],
|
|
@ -29,10 +29,13 @@ class extendedOption(Option):
|
|||
identifiers = {
|
||||
'resolution': ['a','b','c'],
|
||||
'dimension': ['x','y','z'],
|
||||
'origin': ['x','y','z'],
|
||||
}
|
||||
mappings = {
|
||||
'resolution': lambda x: int(x),
|
||||
'dimension': lambda x: float(x),
|
||||
'origin': lambda x: float(x),
|
||||
'homogenization': lambda x: int(x),
|
||||
}
|
||||
|
||||
|
||||
|
@ -43,13 +46,14 @@ i.e. within the region close to a grain/phase boundary.
|
|||
)
|
||||
|
||||
parser.add_option('-v', '--vicinity', dest='vicinity', type='int', \
|
||||
help='voxel distance checked for presence of other microstructure')
|
||||
help='voxel distance checked for presence of other microstructure [%default]')
|
||||
parser.add_option('-o', '--offset', dest='offset', type='int', \
|
||||
help='integer offset for tagged microstructure')
|
||||
help='integer offset for tagged microstructure [%default]')
|
||||
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
|
||||
help='output geom file with two-dimensional data arrangement')
|
||||
|
||||
parser.set_defaults(vicinity = 1)
|
||||
parser.set_defaults(offset = 0)
|
||||
parser.set_defaults(twoD = False)
|
||||
|
||||
(options, filenames) = parser.parse_args()
|
||||
|
@ -58,16 +62,25 @@ parser.set_defaults(twoD = False)
|
|||
|
||||
files = []
|
||||
if filenames == []:
|
||||
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout})
|
||||
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')})
|
||||
files.append({'name':name,
|
||||
'input':open(name),
|
||||
'output':open(name+'_tmp','w'),
|
||||
'croak':sys.stdout,
|
||||
})
|
||||
|
||||
|
||||
# ------------------------------------------ loop over input files ---------------------------------------
|
||||
|
||||
for file in files:
|
||||
if file['name'] != 'STDIN': print file['name']
|
||||
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
|
||||
|
||||
|
@ -83,40 +96,52 @@ for file in files:
|
|||
content = file['input'].readlines()
|
||||
file['input'].close()
|
||||
|
||||
resolution = [0,0,0]
|
||||
dimension = [0.0,0.0,0.0]
|
||||
info = {'resolution': numpy.array([0,0,0]),
|
||||
'dimension': numpy.array([0.0,0.0,0.0]),
|
||||
'origin': numpy.array([0.0,0.0,0.0]),
|
||||
'homogenization': 1,
|
||||
}
|
||||
|
||||
new_header = []
|
||||
for header in headers:
|
||||
headitems = header.split()
|
||||
if headitems[0] == 'resolution': # located resolution entry
|
||||
for i in xrange(3):
|
||||
resolution[i] = mappings['resolution'](headitems[headitems.index(identifiers['resolution'][i])+1])
|
||||
if headitems[0] == 'dimension': # located dimension entry
|
||||
for i in xrange(3):
|
||||
dimension[i] = mappings['dimension'](headitems[headitems.index(identifiers['dimension'][i])+1])
|
||||
headitems = map(str.lower,header.split())
|
||||
if headitems[0] in mappings.keys():
|
||||
if headitems[0] in identifiers.keys():
|
||||
for i in xrange(len(identifiers[headitems[0]])):
|
||||
info[headitems[0]][i] = \
|
||||
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
|
||||
else:
|
||||
info[headitems[0]] = mappings[headitems[0]](headitems[1])
|
||||
|
||||
if resolution == [0,0,0]:
|
||||
print 'no resolution info found.'
|
||||
sys.exit(1)
|
||||
if dimension == [0.0,0.0,0.0]:
|
||||
print 'no dimension info found.'
|
||||
sys.exit(1)
|
||||
if info['resolution'].all() == 0:
|
||||
file['croak'].write('no resolution info found.\n')
|
||||
continue
|
||||
if info['dimension'].all() == 0:
|
||||
file['croak'].write('no dimension info found.\n')
|
||||
continue
|
||||
|
||||
if file['name'] != 'STDIN':
|
||||
print 'resolution: %s'%(' x '.join(map(str,resolution)))
|
||||
print 'dimension: %s'%(' x '.join(map(str,dimension)))
|
||||
file['croak'].write('resolution: %s\n'%(' x '.join(map(str,info['resolution']))) + \
|
||||
'dimension: %s\n'%(' x '.join(map(str,info['dimension']))) + \
|
||||
'origin: %s\n'%(' : '.join(map(str,info['origin']))) + \
|
||||
'homogenization: %i\n'%info['homogenization'])
|
||||
|
||||
microstructure = numpy.zeros(resolution,'i')
|
||||
microstructure = numpy.zeros(info['resolution'],'i')
|
||||
i = 0
|
||||
for line in content:
|
||||
for item in map(int,line.split()):
|
||||
microstructure[i%resolution[0],(i/resolution[0])%resolution[1],i/resolution[0]/resolution[1]] = item
|
||||
microstructure[i%info['resolution'][0],
|
||||
(i/info['resolution'][0])%info['resolution'][1],
|
||||
i/info['resolution'][0] /info['resolution'][1]] = item
|
||||
i += 1
|
||||
|
||||
formatwidth = 1+int(math.floor(math.log10(abs(microstructure.max()+options.offset))))
|
||||
if options.offset == 0:
|
||||
options.offset = microstructure.max()
|
||||
file['croak'].write('offset: %i\n'%options.offset)
|
||||
|
||||
formatwidth = int(math.floor(math.log10(microstructure.max())))
|
||||
|
||||
for x in xrange(resolution[0]):
|
||||
for y in xrange(resolution[1]):
|
||||
for z in xrange(resolution[2]):
|
||||
for x in xrange(info['resolution'][0]):
|
||||
for y in xrange(info['resolution'][1]):
|
||||
for z in xrange(info['resolution'][2]):
|
||||
|
||||
me = microstructure[x,y,z]
|
||||
breaker = False
|
||||
|
@ -125,7 +150,7 @@ for file in files:
|
|||
for dy in xrange(-options.vicinity,options.vicinity+1):
|
||||
for dz in xrange(-options.vicinity,options.vicinity+1):
|
||||
|
||||
they = microstructure[(x+dx)%resolution[0],(y+dy)%resolution[1],(z+dz)%resolution[2]]
|
||||
they = microstructure[(x+dx)%info['resolution'][0],(y+dy)%info['resolution'][1],(z+dz)%info['resolution'][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!
|
||||
breaker = True
|
||||
|
@ -142,9 +167,9 @@ for file in files:
|
|||
|
||||
# ------------------------------------- regenerate texture information ----------------------------------
|
||||
|
||||
for z in xrange(resolution[2]):
|
||||
for y in xrange(resolution[1]):
|
||||
output += {True:' ',False:'\n'}[options.twoD].join(map(lambda x: ('%%%ii'%formatwidth)%x, microstructure[:,y,z])) + '\n'
|
||||
for z in xrange(info['resolution'][2]):
|
||||
for y in xrange(info['resolution'][1]):
|
||||
output += {True:' ',False:'\n'}[options.twoD].join(map(lambda x: str(x).rjust(formatwidth), microstructure[:,y,z])) + '\n'
|
||||
|
||||
output += '\n'
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: UTF-8 no BOM -*-
|
||||
|
||||
import os,sys,string,re,math,numpy,random
|
||||
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
|
||||
|
||||
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 -------------------------------
|
||||
|
||||
identifiers = {
|
||||
'resolution': ['a','b','c'],
|
||||
'dimension': ['x','y','z'],
|
||||
}
|
||||
mappings = {
|
||||
'resolution': lambda x: int(x),
|
||||
'dimension': lambda x: float(x),
|
||||
}
|
||||
|
||||
|
||||
parser = OptionParser(option_class=extendedOption, usage='%prog [options]', description = """
|
||||
Distribute given number of points randomly within the three-dimensional cube [0,0,0]--[1,1,1].
|
||||
Reports positions with random crystal orientations in seeds file format to STDOUT.
|
||||
""" + string.replace('$Id$','\n','\\n')
|
||||
)
|
||||
|
||||
parser.add_option('-N', dest='N', type='int', \
|
||||
help='number of seed points to distribute [%default]')
|
||||
parser.add_option('-r','--resolution', dest='res', type='int', nargs=3, \
|
||||
help='Min Fourier points in x, y, z %default')
|
||||
parser.add_option('-s', '--rnd', dest='randomSeed', type='int', \
|
||||
help='seed of random number generator [%default]')
|
||||
|
||||
parser.set_defaults(randomSeed = 0)
|
||||
parser.set_defaults(res = [16,16,16])
|
||||
parser.set_defaults(N = 20)
|
||||
|
||||
(options, extras) = parser.parse_args()
|
||||
|
||||
Npoints = options.res[0]*options.res[1]*options.res[2]
|
||||
if options.N > Npoints:
|
||||
sys.stderr.write('Warning: more seeds than grid points at minimum resolution.\n')
|
||||
options.N = Npoints
|
||||
|
||||
seeds = numpy.zeros((3,options.N),float)
|
||||
numpy.random.seed(options.randomSeed)
|
||||
|
||||
grainEuler = numpy.random.rand(3,options.N)
|
||||
grainEuler[0,:] *= 360.0
|
||||
grainEuler[1,:] = numpy.arccos(2*grainEuler[1,:]-1)*180.0/math.pi
|
||||
grainEuler[2,:] *= 360.0
|
||||
|
||||
seedpoint = numpy.random.permutation(Npoints)[:options.N]
|
||||
seeds[0,:] = (numpy.mod(seedpoint ,options.res[0])+numpy.random.random())/options.res[0]
|
||||
seeds[1,:] = (numpy.mod(seedpoint// options.res[0] ,options.res[1])+numpy.random.random())/options.res[1]
|
||||
seeds[2,:] = (numpy.mod(seedpoint//(options.res[1]*options.res[0]),options.res[2])+numpy.random.random())/options.res[2]
|
||||
|
||||
print "4\theader"
|
||||
print "resolution\ta %i\tb %i\tc %i"%(options.res[0],options.res[1],options.res[2],)
|
||||
print "grains\t%i"%options.N
|
||||
print "randomSeed\t%f"%(options.randomSeed)
|
||||
print "x\ty\tz\tphi1\tPhi\tphi2"
|
||||
|
||||
numpy.savetxt(sys.stdout,numpy.transpose(numpy.concatenate((seeds,grainEuler),axis = 0)),fmt='%10.6f',delimiter='\t')
|
|
@ -1,170 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
import os,sys,math,string,numpy, damask
|
||||
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
|
||||
|
||||
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 options [file[s]]', description = """
|
||||
generates geom file and material_config file using seeds file
|
||||
|
||||
""" + string.replace('$Id$','\n','\\n')
|
||||
)
|
||||
|
||||
|
||||
parser.add_option('-d', '--dimension', dest='dimension', type='float', nargs = 3, \
|
||||
help='x,y,z dimension of specimen')
|
||||
parser.add_option('-r', '--resolution', dest='resolution', type='int', nargs = 3, \
|
||||
help='a,b,c resolution of specimen')
|
||||
parser.add_option('-o', '--outputName', dest='outputName', type='string', nargs = 1, \
|
||||
help='Output Name')
|
||||
|
||||
parser.set_defaults(resolution = (0,0,0))
|
||||
parser.set_defaults(dimension = (0.0,0.0,0.0))
|
||||
parser.set_defaults(outputName = '')
|
||||
|
||||
(options,filenames) = parser.parse_args()
|
||||
|
||||
# ------------------------------------------ setup file handles ---------------------------------------
|
||||
|
||||
files = []
|
||||
if filenames == []:
|
||||
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout})
|
||||
else:
|
||||
for name in filenames:
|
||||
if os.path.splitext(name)[1]=='': name = name+'.seeds'
|
||||
if options.outputName=='': options.outputName = name
|
||||
if os.path.exists(name):
|
||||
files.append({'name':name,\
|
||||
'input':open(name),\
|
||||
'geom':open(os.path.splitext(options.outputName)[0]+'.geom','w+'),\
|
||||
'material.config':open(os.path.splitext(options.outputName)[0]+'_material.config','w+')})
|
||||
|
||||
# ------------------------------------------ loop over input files ---------------------------------------
|
||||
for file in files:
|
||||
spatialDim = 3
|
||||
unmapped = 0
|
||||
|
||||
if file['name'] != 'STDIN': print file['name']
|
||||
Favg = numpy.array(([1.0,0.0,0.0],\
|
||||
[0.0,1.0,0.0],\
|
||||
[0.0,0.0,1.0]),'d')
|
||||
|
||||
for lineCount, line in enumerate(file['input']):
|
||||
words = line.split()
|
||||
if('head' in line): headCount=int(words[0])+1
|
||||
if(lineCount<=headCount):
|
||||
if('grains'.lower()==words[0]):
|
||||
N_seeds=int(words[1])
|
||||
checkGrain=numpy.zeros(N_seeds)
|
||||
if 'resolution'==words[0] :
|
||||
if options.resolution==(0,0,0):
|
||||
resolution=[int(words[2]),int(words[4]),int(words[6])]
|
||||
else:
|
||||
resolution = [options.resolution[0],options.resolution[1],options.resolution[2]]
|
||||
|
||||
if lineCount==headCount: # all header info there, allocating arrays
|
||||
if resolution[2]==1: spatialDim=2
|
||||
validDim = numpy.zeros(3)
|
||||
dimension = numpy.zeros(3)
|
||||
for i in xrange(3):
|
||||
if(options.dimension[i]>0): validDim[i]= 1
|
||||
for i in xrange(3):
|
||||
if(any(validDim) and options.dimension[i]==0):
|
||||
dimension[i] = max(numpy.array(options.dimension,dtype='float')/resolution) *resolution[i]
|
||||
print 'rescaling invalid dimension '+str(i+1)
|
||||
if(any(validDim)==0):
|
||||
print 'No valid dimension specified, rescaling all dimensions'
|
||||
for i in xrange(spatialDim): dimension[i]=1.0/max(resolution)*resolution[i]
|
||||
if(all(validDim)): dimension= [options.dimension[0],options.dimension[1],options.dimension[2]]
|
||||
coords = numpy.zeros((spatialDim,N_seeds),'d')
|
||||
eulers = numpy.zeros((N_seeds,3),'d')
|
||||
|
||||
else:
|
||||
Npoints = resolution[0]*resolution[1]*resolution[2]
|
||||
|
||||
coords[0:spatialDim,lineCount-headCount] = numpy.array(words[0:spatialDim],'d')
|
||||
eulers[lineCount-headCount,0:3] = words[3:6]
|
||||
undeformed = numpy.zeros((spatialDim,Npoints),'d').reshape(spatialDim,Npoints)
|
||||
|
||||
for i in xrange(spatialDim):
|
||||
for j in xrange(N_seeds):
|
||||
if(coords[i][j]>=1.0 or coords[i][j]<0.0):
|
||||
print 'WARNING: Seed Coordinate '+ str(coords[i][j]) +' located outside Grid '
|
||||
digits = 1+int(math.log10(int(N_seeds)))
|
||||
|
||||
file['geom'].write('3 header' +'\n')
|
||||
file['geom'].write('resolution a '+ str(resolution[0])+ ' b '+str(resolution[1])+ ' c '+str( resolution[2])+'\n')
|
||||
file['geom'].write('dimension x '+ str(dimension[0]) + ' y '+ str(dimension[1])+ ' z '+ str( dimension[2])+'\n')
|
||||
file['geom'].write('homogenization 1'+'\n')
|
||||
|
||||
file['material.config'].write('<microstructure>'+'\n')
|
||||
|
||||
for i in xrange(N_seeds):
|
||||
|
||||
|
||||
file['material.config'].write('[Grain' +str( i+1).zfill(digits)+']'+'\n')
|
||||
file['material.config'].write('crystallite 1'+'\n')
|
||||
file['material.config'].write('(constituent) phase 1 texture '+ str(i+1).zfill(digits)+ ' fraction 1.0'+'\n')
|
||||
file['material.config'].write('\n'+'<texture>'+'\n')
|
||||
for i in xrange(N_seeds):
|
||||
file['material.config'].write('[Grain'+ str(i+1).zfill(digits)+ ']'+'\n')
|
||||
file['material.config'].write('(gauss) phi1 '+ str(eulers[i][0])+ ' Phi '+ str(eulers[i][1])+ \
|
||||
' phi2 '+ str(eulers[i][2])+ ' scatter 0.0 fraction 1.0'+'\n')
|
||||
|
||||
|
||||
|
||||
shift = dimension[0:spatialDim]/numpy.array( resolution,dtype='float')[0:spatialDim]*0.5 # shift by half of side length to center of element
|
||||
for i in xrange(Npoints):
|
||||
undeformed[0,i] = dimension[0]\
|
||||
* float(i % resolution[0])\
|
||||
/float( resolution[0])
|
||||
undeformed[1,i] = dimension[1]\
|
||||
* float(i// resolution[0] % resolution[1])\
|
||||
/float( resolution[1])
|
||||
|
||||
if spatialDim==3:
|
||||
undeformed[2,i] = dimension[2]\
|
||||
* float(i// resolution[0]// resolution[1] % resolution[2])\
|
||||
/float( resolution[2])
|
||||
undeformed[0:spatialDim,i] += shift
|
||||
|
||||
|
||||
indices=damask.core.math.math_nearestNeighborSearch(spatialDim,Favg,numpy.array( dimension,dtype='float'),Npoints,N_seeds,undeformed,coords)
|
||||
|
||||
for n in xrange(Npoints):
|
||||
file['geom'].write( str(indices[n]//3**spatialDim+1).zfill(digits)+{True:'\n',False:' '}[(n+1)% resolution[0] == 0])
|
||||
grainIndex=indices//3**spatialDim+1
|
||||
for i in xrange(1,N_seeds+1):
|
||||
if i not in grainIndex: unmapped+=1
|
||||
if(unmapped == 0): print 'All Grains Mapped'
|
||||
else: print 'Only '+str(N_seeds-unmapped )+' Grains mapped'
|
||||
|
||||
|
||||
file['geom'].close()
|
||||
file['material.config'].close()
|
||||
file['input'].close()
|
||||
|
|
@ -1,154 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: UTF-8 no BOM -*-
|
||||
|
||||
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
|
||||
|
||||
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 -------------------------------
|
||||
|
||||
identifiers = {
|
||||
'resolution': ['a','b','c'],
|
||||
'dimension': ['x','y','z'],
|
||||
}
|
||||
mappings = {
|
||||
'resolution': lambda x: int(x),
|
||||
'dimension': lambda x: float(x),
|
||||
}
|
||||
|
||||
|
||||
parser = OptionParser(option_class=extendedOption, usage='%prog options [file[s]]', description = """
|
||||
Multiplies a spectral geometry description independently in x, y, and z direction at fixed dimension.
|
||||
""" + string.replace('$Id$','\n','\\n')
|
||||
)
|
||||
|
||||
parser.add_option('-f', '--factor', dest='factor', type='int', nargs = 3, \
|
||||
help='multiplication factors of a,b,c resolution')
|
||||
parser.add_option('-2', '--twodimensional', dest='twoD', action='store_true', \
|
||||
help='output geom file with two-dimensional data arrangement')
|
||||
parser.add_option('-k', '--keep', dest='keepDimension', action='store_true', \
|
||||
help='keep dimension as before')
|
||||
|
||||
parser.set_defaults(factor = [1,1,1])
|
||||
parser.set_defaults(twoD = False)
|
||||
parser.set_defaults(keepDimension = False)
|
||||
|
||||
(options, filenames) = parser.parse_args()
|
||||
|
||||
prefix = 'mult%ix%ix%i'%(options.factor[0],options.factor[1],options.factor[2])
|
||||
|
||||
# ------------------------------------------ setup file handles ---------------------------------------
|
||||
|
||||
files = []
|
||||
if filenames == []:
|
||||
files.append({'name':'STDIN', 'input':sys.stdin, 'output':sys.stdout})
|
||||
else:
|
||||
for name in filenames:
|
||||
if os.path.exists(name):
|
||||
files.append({'name':name, 'input':open(name), 'output':open(prefix+'_'+name,'w')})
|
||||
|
||||
|
||||
# ------------------------------------------ loop over input files ---------------------------------------
|
||||
|
||||
for file in files:
|
||||
if file['name'] != 'STDIN': print file['name']
|
||||
|
||||
# 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:
|
||||
headerlines = int(m.group(1))
|
||||
headers = [firstline]+[file['input'].readline() for i in range(headerlines)]
|
||||
else:
|
||||
headerlines = 1
|
||||
headers = firstline
|
||||
|
||||
content = file['input'].readlines()
|
||||
file['input'].close()
|
||||
|
||||
resolution = [0,0,0]
|
||||
dimension = [0.0,0.0,0.0]
|
||||
resolution_blown = [0,0,0]
|
||||
dimension_blown = [0.0,0.0,0.0]
|
||||
new_header = []
|
||||
for header in headers:
|
||||
headitems = header.split()
|
||||
if headitems[0] == 'resolution': # located resolution entry
|
||||
for i in xrange(3):
|
||||
resolution[i] = mappings['resolution'](headitems[headitems.index(identifiers['resolution'][i])+1])
|
||||
resolution_blown[i] = resolution[i]*options.factor[i]
|
||||
header = "resolution\ta %i\tb %i\tc %i\n"%(resolution_blown[0],resolution_blown[1],resolution_blown[2])
|
||||
if headitems[0] == 'dimension': # located dimension entry
|
||||
for i in xrange(3):
|
||||
dimension[i] = mappings['dimension'](headitems[headitems.index(identifiers['dimension'][i])+1])
|
||||
if options.keepDimension: dimension_blown[i] = dimension[i]
|
||||
else: dimension_blown[i] = dimension[i]*options.factor[i]
|
||||
header = "dimension\tx %f\ty %f\tz %f\n"%(dimension_blown[0],dimension_blown[1],dimension_blown[2])
|
||||
|
||||
new_header.append(header)
|
||||
|
||||
if resolution == [0,0,0]:
|
||||
print 'no resolution info found.'
|
||||
continue
|
||||
if dimension == [0.0,0.0,0.0]:
|
||||
print 'no dimension info found.'
|
||||
continue
|
||||
|
||||
if file['name'] != 'STDIN':
|
||||
print 'resolution: %s'%(' x '.join(map(str,resolution_blown)))
|
||||
print 'dimension: %s'%(' x '.join(map(str,dimension_blown)))
|
||||
|
||||
microstructure = numpy.zeros(resolution,'i')
|
||||
i = 0
|
||||
for line in content:
|
||||
for item in map(int,line.split()):
|
||||
microstructure[i%resolution[0],(i/resolution[0])%resolution[1],i/resolution[0]/resolution[1]] = item
|
||||
i += 1
|
||||
|
||||
formatwidth = int(math.floor(math.log10(microstructure.max())))
|
||||
|
||||
|
||||
|
||||
# ------------------------------------------ assemble header ---------------------------------------
|
||||
|
||||
output = ''.join(new_header)
|
||||
|
||||
# ------------------------------------- regenerate texture information ----------------------------------
|
||||
|
||||
for z in xrange(resolution[2]):
|
||||
for c in xrange(options.factor[2]):
|
||||
for y in xrange(resolution[1]):
|
||||
for b in xrange(options.factor[1]):
|
||||
for x in xrange(resolution[0]):
|
||||
for a in xrange(options.factor[0]):
|
||||
output += ('%%%ii'%formatwidth)%microstructure[x,y,z] + {True:' ',False:'\n'}[options.twoD]
|
||||
output += {True:'\n',False:''}[options.twoD]
|
||||
|
||||
# ------------------------------------------ output result ---------------------------------------
|
||||
|
||||
file['output'].write(output)
|
||||
|
||||
file['input'].close()
|
||||
if file['name'] != 'STDIN':
|
||||
file['output'].close()
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: UTF-8 no BOM -*-
|
||||
|
||||
import os,sys,string,re,math,numpy,random
|
||||
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
|
||||
|
||||
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 -------------------------------
|
||||
|
||||
identifiers = {
|
||||
'resolution': ['a','b','c'],
|
||||
'dimension': ['x','y','z'],
|
||||
}
|
||||
mappings = {
|
||||
'resolution': lambda x: int(x),
|
||||
'dimension': lambda x: float(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.
|
||||
""" + string.replace('$Id$','\n','\\n')
|
||||
)
|
||||
|
||||
parser.add_option('-f', '--file', dest='filename', type="string", \
|
||||
help='output seed file name [%default]')
|
||||
parser.add_option('-s', '--seed', dest='randomSeed', type='int', \
|
||||
help='seed of random number generator [%default]')
|
||||
parser.add_option('-n', '--ngrains', dest='N_Seeds', type='int', \
|
||||
help='seed of random number generator[%default]')
|
||||
parser.add_option('-r','--res', dest='res', type='int', nargs=3, \
|
||||
help='Min Fourier points in x, y, z [%default]')
|
||||
|
||||
parser.set_defaults(filename = 'seeds')
|
||||
parser.set_defaults(randomSeed = 0)
|
||||
parser.set_defaults(res=[16,16,16])
|
||||
parser.set_defaults(N_Seeds=50)
|
||||
|
||||
(options, filenames) = parser.parse_args()
|
||||
|
||||
if options.N_Seeds > options.res[0]*options.res[1]*options.res[2]:
|
||||
print 'Warning: Number of grains exceeds min resolution'
|
||||
options.N_Seeds = options.res[0]*options.res[1]*options.res[2]
|
||||
|
||||
seeds = numpy.zeros((3,options.N_Seeds),float)
|
||||
numpy.random.seed(options.randomSeed)
|
||||
|
||||
grainEuler=numpy.random.rand(3,options.N_Seeds)
|
||||
grainEuler[0,:] = 360*grainEuler[0,:]
|
||||
grainEuler[1,:] = numpy.arccos(2*grainEuler[1,:]-1)*180/math.pi
|
||||
grainEuler[2,:] = 360*grainEuler[2,:]
|
||||
|
||||
seedpoint = numpy.random.permutation(options.res[0]*options.res[1]*options.res[2])[:options.N_Seeds]
|
||||
seeds[0,:]=(numpy.mod(seedpoint ,options.res[0])+numpy.random.random())/options.res[0]
|
||||
seeds[1,:]=(numpy.mod(seedpoint// options.res[0] ,options.res[1])+numpy.random.random())/options.res[1]
|
||||
seeds[2,:]=(numpy.mod(seedpoint//(options.res[1]*options.res[0]),options.res[2])+numpy.random.random())/options.res[2]
|
||||
|
||||
f = open(options.filename+'.seeds', 'w')
|
||||
|
||||
f.write("{0:1d} {1:6s}\n".format(4,'header'))
|
||||
f.write("{0:s} {1:8d} {2:s} {3:8d} {4:s} {5:8d}\n".format('resolution a',options.res[0],'b',options.res[1],'c',options.res[2]))
|
||||
f.write("{0:s} {1:8d}\n".format('grains',options.N_Seeds))
|
||||
f.write("{0:s} {1:8d}\n".format('random seed',options.randomSeed))
|
||||
f.write("x y z phi1 Phi phi2\n")
|
||||
f.close()
|
||||
f=file(options.filename+'.seeds','a')
|
||||
numpy.savetxt(f,numpy.transpose(numpy.concatenate((seeds,grainEuler),axis=0)),fmt='%10.6f',delimiter=' ')
|
||||
f.close()
|
|
@ -82,17 +82,17 @@ bin_link = { \
|
|||
'mentat_spectralBox.py',
|
||||
'OIMang_hex2cub.py',
|
||||
'patchFromReconstructedBoundaries.py',
|
||||
'spectral_geomCanvas.py',
|
||||
'spectral_geomCheck.py',
|
||||
'spectral_geomFromAng.py',
|
||||
'spectral_geomFromMinimalSurface.py',
|
||||
'spectral_geomFromVoronoiTessellation.py',
|
||||
'spectral_geomMultiply.py',
|
||||
'spectral_geomPack.py',
|
||||
'spectral_geomTranslate.py',
|
||||
'spectral_geomUnpack.py',
|
||||
'spectral_geomVicinityOffset.py',
|
||||
'spectral_randomSeeding.py',
|
||||
'geom_canvas.py',
|
||||
'geom_check.py',
|
||||
'geom_fromVoronoiTessellation.py',
|
||||
'geom_rescale.py',
|
||||
'geom_pack.py',
|
||||
'geom_unpack.py',
|
||||
'geom_translate.py',
|
||||
'geom_vicinityOffset.py',
|
||||
'randomSeeding.py',
|
||||
],
|
||||
'post' : [
|
||||
'3Dvisualize.py',
|
||||
|
|
Loading…
Reference in New Issue