streamlining and bugfixing of geom-class

This commit is contained in:
Philip Eisenlohr 2019-05-27 19:14:09 -06:00
parent b69f0efbbc
commit 1f56ac6a4a
19 changed files with 495 additions and 309 deletions

View File

@ -78,7 +78,7 @@ parser.set_defaults(center = (.0,.0,.0),
if options.dimension is None:
parser.error('no dimension specified.')
if [options.angleaxis,options.quaternion].count(None) == 2:
if [options.angleaxis,options.quaternion].count(None) == 0:
parser.error('more than one rotation specified.')
if options.angleaxis is not None:
@ -99,27 +99,18 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid = geom.get_grid()
size = geom.get_size()
origin = geom.get_origin()
microstructure = geom.get_microstructure()
fill = options.fill if options.fill is not None else np.nanmax(microstructure)+1
origin = np.zeros(3)
for i,line in enumerate(geom.comments):
if line.lower().strip().startswith('origin'):
origin= np.array([float(line.split()[j]) for j in [2,4,6]]) # assume correct order (x,y,z)
# coordinates given in real space (default) vs voxel space
# coordinates given in real space, not (default) voxel space
if options.realspace:
options.center -= origin
options.center *= geom.get_grid() / geom.get_size()
options.dimension *= geom.get_grid() / geom.get_size()
options.center *= grid / size
options.dimension *= grid / size
grid = microstructure.shape
# change to coordinate space where the primitive is the unit sphere/cube/etc
if options.periodic: # use padding to achieve periodicity
@ -158,6 +149,7 @@ for name in filenames:
Y /= options.dimension[1] * 0.5
Z /= options.dimension[2] * 0.5
fill = np.nanmax(microstructure)+1 if options.fill is None else options.fill
# High exponents can cause underflow & overflow - loss of precision is okay here, we just compare it to 1, so +infinity and 0 are fine
old_settings = np.seterr()
@ -191,7 +183,7 @@ for name in filenames:
microstructure if options.inside else fill)
damask.util.croak(geom.update(microstructure))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -1,80 +1,111 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 no BOM -*-
import os
import sys
import numpy as np
import damask
from io import StringIO
from optparse import OptionParser
import numpy as np
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 [geomfile(s)]', description = """
Increases or decreases the (three-dimensional) canvas.
parser = OptionParser(option_class=damask.extendableOption, usage='%prog option(s) [geomfile(s)]', description = """
Changes the (three-dimensional) canvas of a spectral geometry description.
Grid can be given as absolute or relative values, e.g. 16 16 16 or 2x 0.5x 32.
""", version = scriptID)
parser.add_option('-g','--grid',
parser.add_option('-g',
'--grid',
dest = 'grid',
type = 'string', nargs = 3, metavar = ' '.join(['string']*3),
help = 'a,b,c grid of hexahedral box')
parser.add_option('-o','--offset',
help = 'a,b,c grid of hexahedral box. [auto]')
parser.add_option('-o',
'--offset',
dest = 'offset',
type = 'int', nargs = 3, metavar = ' '.join(['int']*3),
help = 'a,b,c offset from old to new origin of grid [%default]')
parser.add_option('-f','--fill',
parser.add_option('-f',
'--fill',
dest = 'fill',
type = 'float', metavar = 'int',
help = 'background microstructure index, defaults to max microstructure index + 1')
type = 'float', metavar = 'float',
help = '(background) canvas grain index. "0" selects maximum microstructure index + 1 [%default]')
parser.add_option('--blank',
dest = 'blank',
action = 'store_true',
help = 'blank out (optional) input canvas content')
parser.set_defaults(offset = (0,0,0))
parser.set_defaults(grid = ['0','0','0'],
offset = (0,0,0),
)
(options, filenames) = parser.parse_args()
options.grid = ['1','1','1'] if options.blank and options.grid == ['0','0','0'] else options.grid
options.fill = 1 if options.blank and options.fill is None else options.fill
# --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
if name is None and options.blank:
grid = np.array(list(map(int,options.grid)))
geom = damask.Geom(size=grid,microstructure=options.fill*np.ones(grid))
else:
geom = damask.Geom.from_file(name)
microstructure = geom.get_microstructure()
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid = geom.get_grid()
if options.grid is not None:
for i,g in enumerate(options.grid):
grid[i] = int(round(grid[i]*float(g.lower().replace('x','')))) if g.lower().endswith('x') \
else int(options.grid[i])
size = geom.get_size()
origin = geom.get_origin()
microstructure = geom.get_microstructure()
fill = np.nanmax(microstructure)+1 if options.fill is None else options.fill
dtype = float if np.isnan(fill) or int(fill) != fill or microstructure.dtype==np.float else int
new = np.full(grid,options.fill if options.fill is not None else np.nanmax(microstructure)+1,
microstructure.dtype)
damask.util.croak(geom)
for x in range(microstructure.shape[0]):
X = x + options.offset[0]
if not 0 <= X < new.shape[0]: continue
for y in range(microstructure.shape[1]):
Y = y + options.offset[1]
if not 0 <= Y < new.shape[1]: continue
for z in range(microstructure.shape[2]):
Z = z + options.offset[2]
if not 0 <= Z < new.shape[2]: continue
new[X,Y,Z] = microstructure[x,y,z]
# --- do work ------------------------------------------------------------------------------------
damask.util.croak(geom.update(new,rescale=True))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
new_grid = np.array([int(o*float(n.lower().replace('x',''))) if n.lower().endswith('x') \
else int(n) for o,n in zip(grid,options.grid)],dtype=int)
new_grid = np.where(new_grid > 0, new_grid,grid)
microstructure_cropped = np.zeros(new_grid,dtype=dtype)
microstructure_cropped.fill(fill)
if not options.blank:
xindex = np.arange(max(options.offset[0],0),min(options.offset[0]+new_grid[0],grid[0]))
yindex = np.arange(max(options.offset[1],0),min(options.offset[1]+new_grid[1],grid[1]))
zindex = np.arange(max(options.offset[2],0),min(options.offset[2]+new_grid[2],grid[2]))
translate_x = [i - options.offset[0] for i in xindex]
translate_y = [i - options.offset[1] for i in yindex]
translate_z = [i - options.offset[2] for i in zindex]
if 0 in map(len,[xindex,yindex,zindex,translate_x,translate_y,translate_z]):
damask.util.croak('invaldid combination of grid and offset.')
continue
microstructure_cropped[min(translate_x):max(translate_x)+1,
min(translate_y):max(translate_y)+1,
min(translate_z):max(translate_z)+1] \
= microstructure[min(xindex):max(xindex)+1,
min(yindex):max(yindex)+1,
min(zindex):max(zindex)+1]
new_size = size/grid*new_grid if np.all(grid > 0) else new_grid
new_origin = origin + (size/grid if np.all(grid > 0) else new_size/new_grid) * options.offset
geom.set_microstructure(microstructure_cropped)
geom.set_size(new_size)
geom.set_origin(new_origin)
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -44,18 +44,14 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
microstructure = ndimage.filters.generic_filter(microstructure,mostFrequent,
size=(options.stencil,)*3).astype(microstructure.dtype)
damask.util.croak(geom.update(microstructure))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -82,13 +82,14 @@ for name in filenames:
Y = options.periods*2.0*np.pi*(np.arange(options.grid[1])+0.5)/options.grid[1]
Z = options.periods*2.0*np.pi*(np.arange(options.grid[2])+0.5)/options.grid[2]
microstructure = np.empty(options.grid,dtype='int')
microstructure = np.empty(options.grid,dtype=int)
for x in range(options.grid[0]):
for y in range(options.grid[1]):
for z in range(options.grid[2]):
microstructure[x,y,z]=options.microstructure[options.threshold < surface[options.type](X[x],Y[y],Z[z])]
microstructure[x,y,z]=options.microstructure[int(options.threshold < surface[options.type](X[x],Y[y],Z[z]))]
geom=damask.Geom(microstructure,options.size,options.homogenization,
geom=damask.Geom(microstructure,options.size,
homogenization=options.homogenization,
comments=[scriptID + ' ' + ' '.join(sys.argv[1:])])
damask.util.croak(geom)

View File

@ -171,7 +171,8 @@ for name in filenames:
if options.axes is not None: config_header += ['axes\t{} {} {}'.format(*options.axes)]
header = [scriptID + ' ' + ' '.join(sys.argv[1:])] + config_header + ['origin x {} y {} z {}'.format(*origin)]
geom = damask.Geom(grain.reshape(grid,order='F'),size,options.homogenization,comments=header)
geom = damask.Geom(grain.reshape(grid,order='F'),size,
homogenization=options.homogenization,comments=header)
damask.util.croak(geom)
if name is None:

View File

@ -311,7 +311,8 @@ for name in filenames:
config_header += ['<!skip>']
header = [scriptID + ' ' + ' '.join(sys.argv[1:])] + config_header + ['origin x {} y {} z {}'.format(*info['origin'])]
geom = damask.Geom(indices.reshape(info['grid'],order='F'),info['size'],options.homogenization,comments=header)
geom = damask.Geom(indices.reshape(info['grid'],order='F'),info['size'],
homogenization=options.homogenization,comments=header)
damask.util.croak(geom)
if name is None:

View File

@ -59,11 +59,8 @@ options.immutable = list(map(int,options.immutable))
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
damask.util.croak(geom)
grid_original = geom.get_grid()
@ -171,7 +168,7 @@ for name in filenames:
microstructure = np.where(immutable, microstructure_original,microstructure)
damask.util.croak(geom.update(microstructure[0:grid_original[0],0:grid_original[1],0:grid_original[2]]))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -50,12 +50,8 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
microstructure = geom.microstructure
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
if 'z' in options.directions:
microstructure = np.concatenate([microstructure,microstructure[:,:,limits[0]:limits[1]:-1]],2)
@ -65,7 +61,7 @@ for name in filenames:
microstructure = np.concatenate([microstructure,microstructure[limits[0]:limits[1]:-1,:,:]],0)
damask.util.croak(geom.update(microstructure,rescale=True))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -29,14 +29,10 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
damask.util.croak(geom)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure().flatten('F')
damask.util.croak(geom)
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
compressType = None
former = start = -1
@ -51,13 +47,13 @@ for name in filenames:
reps += 1
else:
if compressType is None:
out = []
out = geom.get_header()
elif compressType == '.':
out.append('{}\n'.format(former))
out.append('{}'.format(former))
elif compressType == 'to':
out.append('{} to {}\n'.format(start,former))
out.append('{} to {}'.format(start,former))
elif compressType == 'of':
out.append('{} of {}\n'.format(reps,former))
out.append('{} of {}'.format(reps,former))
compressType = '.'
start = current
@ -66,18 +62,18 @@ for name in filenames:
former = current
if compressType == '.':
out.append('{}\n'.format(former))
out.append('{}'.format(former))
elif compressType == 'to':
out.append('{} to {}\n'.format(start,former))
out.append('{} to {}'.format(start,former))
elif compressType == 'of':
out.append('{} of {}\n'.format(reps,former))
out.append('{} of {}'.format(reps,former))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
comments = geom.get_comments()
if name is None:
sys.stdout.write('\n'.join(out)+'\n')
else:
with open(name,'w') as f:
f.write('{} header\n'.format(3+len(comments)))
f.writelines(["{}\n".format(comment) for comment in comments])
f.write('grid a {} b {} c {}\n'.format(*geom.get_grid()))
f.write('size x {} y {} z {}\n'.format(*geom.get_size()))
f.write('homogenization {}\n'.format(geom.get_homogenization()))
f.writelines(out)
f.write('\n'.join(out)+'\n')

View File

@ -31,11 +31,7 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
renumbered = np.copy(microstructure)
@ -43,7 +39,7 @@ for name in filenames:
renumbered = np.where(microstructure == oldID, i+1, renumbered)
damask.util.croak(geom.update(renumbered))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -2,9 +2,10 @@
import os
import sys
import numpy as np
from io import StringIO
from optparse import OptionParser
from scipy import ndimage
import damask
@ -41,30 +42,25 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
scale = geom.get_grid().astype('float')
if options.grid is not None:
for i,g in enumerate(options.grid):
scale[i] = scale[i]*float(g.lower().replace('x','')) if g.lower().endswith('x') \
else float(options.grid[i])/scale[i]
grid = geom.get_grid()
size = geom.get_size()
if options.size is not None:
for i,s in enumerate(options.size):
size[i] = size[i]*float(s.lower().replace('x','')) if s.lower().endswith('x') \
else options.size[i]
microstructure = ndimage.interpolation.zoom(microstructure, scale, output=microstructure.dtype,
new_grid = grid if options.grid is None else \
np.array([int(o*float(n.lower().replace('x',''))) if n.lower().endswith('x') \
else int(n) for o,n in zip(grid,options.grid)],dtype=int)
new_size = size if options.size is None else \
np.array([o*float(n.lower().replace('x','')) if n.lower().endswith('x') \
else float(n) for o,n in zip(size,options.size)],dtype=float)
if np.any(new_grid != grid):
microstructure = ndimage.interpolation.zoom(microstructure, new_grid/grid,output=microstructure.dtype,
order=0,mode='nearest', prefilter=False)
damask.util.croak(geom.update(microstructure,size))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak(geom.update(microstructure,new_size))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -27,7 +27,7 @@ Rotates original microstructure and embeddeds it into buffer material.
parser.add_option('-r', '--rotation',
dest='rotation',
type = 'float', nargs = 4, metavar = ' '.join(['float']*4),
help = 'rotation given as angle and axis')
help = 'rotation given as axis and angle')
parser.add_option('-e', '--eulers',
dest = 'eulers',
type = 'float', nargs = 3, metavar = ' '.join(['float']*3),
@ -59,41 +59,38 @@ if [options.rotation,options.eulers,options.matrix,options.quaternion].count(Non
parser.error('no rotation specified.')
if options.quaternion is not None:
eulers = damask.Rotation.fromQuaternion(np.array(options.quaternion)).asEulers(degrees=True)
rot = damask.Rotation.fromQuaternion(np.array(options.quaternion)) # we might need P=+1 here, too...
if options.rotation is not None:
eulers = damask.Rotation.fromAxisAngle(np.array(options.rotation,degrees=options.degrees)).asEulers(degrees=True)
rot = damask.Rotation.fromAxisAngle(np.array(options.rotation),degrees=options.degrees,P=+1)
if options.matrix is not None:
eulers = damask.Rotation.fromMatrix(np.array(options.Matrix)).asEulers(degrees=True)
rot = damask.Rotation.fromMatrix(np.array(options.Matrix))
if options.eulers is not None:
eulers = damask.Rotation.fromEulers(np.array(options.eulers),degrees=options.degrees).asEulers(degrees=True)
rot = damask.Rotation.fromEulers(np.array(options.eulers),degrees=options.degrees)
eulers = rot.asEulers(degrees=True)
if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
fill = options.fill if options.fill is not None else np.nanmax(microstructure)+1
fill = np.nanmax(microstructure)+1 if options.fill is None else options.fill
dtype = float if np.isnan(fill) or int(fill) != fill or microstructure.dtype==np.float else int
# These rotations are always applied in the reference coordinate system, i.e. (z,x,z) not (z,x',z'')
# this seems to be ok, see https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf
microstructure = ndimage.rotate(microstructure,eulers[2],(0,1),order=0,
prefilter=False,output=microstructure.dtype,cval=fill) # rotation around z
prefilter=False,output=dtype,cval=fill) # rotation around z
microstructure = ndimage.rotate(microstructure,eulers[1],(1,2),order=0,
prefilter=False,output=microstructure.dtype,cval=fill) # rotation around x
prefilter=False,output=dtype,cval=fill) # rotation around x
microstructure = ndimage.rotate(microstructure,eulers[0],(0,1),order=0,
prefilter=False,output=microstructure.dtype,cval=fill) # rotation around z
prefilter=False,output=dtype,cval=fill) # rotation around z
damask.util.croak(geom.update(microstructure,rescale=True))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -31,19 +31,12 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
damask.util.croak(geom)
microstructure = geom.get_microstructure().flatten('F')
grid = geom.get_grid()
size = geom.get_size()
for i,line in enumerate(geom.get_comments()):
if line.lower().strip().startswith('origin'):
origin= np.array([float(line.split()[j]) for j in [2,4,6]]) # assume correct order (x,y,z)
origin = geom.get_origin()
#--- generate grid --------------------------------------------------------------------------------
@ -58,7 +51,7 @@ for name in filenames:
# ------------------------------------------ finalize output ---------------------------------------
table = damask.ASCIItable(outname = os.path.splitext(name)[0]+'.txt' if name else name)
table.info_append([scriptID + '\t' + ' '.join(sys.argv[1:])] + geom.get_comments())
table.info_append(geom.get_comments() + [scriptID + '\t' + ' '.join(sys.argv[1:])])
table.labels_append(['{}_{}'.format(1+i,'pos') for i in range(3)]+['microstructure'])
table.head_write()
table.output_flush()

View File

@ -43,36 +43,22 @@ parser.set_defaults(origin = (0.0,0.0,0.0),
(options, filenames) = parser.parse_args()
sub = {}
for i in range(len(options.substitute)//2): # split substitution list into "from" -> "to"
sub[int(options.substitute[i*2])] = int(options.substitute[i*2+1])
sub = list(map(int,options.substitute))
if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
new = np.copy(microstructure)
substituted = np.copy(microstructure)
for k, v in sub.items(): new[microstructure==k] = v # substitute microstructure indices and shift
for old,new in zip(sub[0::2],sub[1::2]): substituted[microstructure==old] = new # substitute microstructure indices
substituted += options.microstructure # constant shift
microstructure += options.microstructure # constant shift
for i,line in enumerate(geom.get_comments()):
if line.lower().strip().startswith('origin'):
origin= np.array([float(line.split()[j]) for j in [2,4,6]]) # assume correct order (x,y,z)
origin += np.array(origin)
geom.comments[i] = 'origin x {} y {} z {}'.format(*origin)
damask.util.croak(geom.update(microstructure))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak(geom.update(substituted,origin=geom.get_origin()+options.origin))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -29,14 +29,10 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
damask.util.croak(geom)
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -41,10 +41,10 @@ parser.add_option('-v', '--vicinity',
dest = 'vicinity',
type = 'int', metavar = 'int',
help = 'voxel distance checked for presence of other microstructure [%default]')
parser.add_option('-m', '--microstructureoffset',
parser.add_option('-o', '--offset',
dest='offset',
type = 'int', metavar = 'int',
help='offset (positive or negative) to tag microstructure indices, defaults to max microstructure index + 1')
help='offset (positive or negative) to tag microstructure indices, defaults to max microstructure index')
parser.add_option('-t', '--trigger',
dest = 'trigger',
action = 'extend', metavar = '<int LIST>',
@ -69,14 +69,10 @@ if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file)
else:
geom = damask.Geom.from_file(name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure()
offset = options.offset if options.offset is not None else np.nanmax(microstructure)
offset = np.nanmax(microstructure) if options.offset is None else options.offset
microstructure = np.where(ndimage.filters.generic_filter(microstructure,
taintedNeighborhood,
@ -86,7 +82,7 @@ for name in filenames:
microstructure + offset,microstructure)
damask.util.croak(geom.update(microstructure))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
geom.add_comments(scriptID + ' ' + ' '.join(sys.argv[1:]))
if name is None:
sys.stdout.write(str(geom.show()))

View File

@ -9,102 +9,105 @@ from . import util
class Geom():
"""Geometry definition for grid solvers"""
def __init__(self,microstructure,size,homogenization=1,comments=[]):
def __init__(self,microstructure,size,origin=[0.0,0.0,0.0],homogenization=1,comments=[]):
"""New geometry definition from array of microstructures and size"""
self.set_size(size)
self.set_origin(origin)
self.set_microstructure(microstructure)
self.set_homogenization(homogenization)
self.set_comments(comments)
def __repr__(self):
"""Basic information on geometry definition"""
return 'grid a b c: {}\n'.format(' x '.join(map(str,self.get_grid ()))) + \
'size x y z: {}\n'.format(' x '.join(map(str,self.get_size ()))) + \
'origin x y z: {}\n'.format(' x '.join(map(str,self.get_origin()))) + \
'homogenization: {}\n'.format(self.get_homogenization()) + \
'# microstructures: {}\n'.format(len(np.unique(self.microstructure))) + \
'max microstructures: {}\n'.format(np.nanmax(self.microstructure))
def update(self,microstructure=None,size=None,origin=None,rescale=False):
"""Updates microstructure and size"""
grid_old = self.get_grid()
size_old = self.get_size()
origin_old = self.get_origin()
unique_old = len(np.unique(self.microstructure))
max_old = np.nanmax(self.microstructure)
if size is not None and rescale:
raise ValueError('Either set size explicitly or rescale automatically')
self.set_microstructure(microstructure)
self.set_size(self.get_grid()/grid_old if rescale else size)
self.set_origin(origin)
message = ['grid a b c: {}'.format(' x '.join(map(str,grid_old)))]
if np.any(grid_old != self.get_grid()):
message[-1] = util.delete(message[-1])
message.append('grid a b c: {}'.format(' x '.join(map(str,self.get_grid()))))
message.append('size x y z: {}'.format(' x '.join(map(str,size_old))))
if np.any(size_old != self.get_size()):
message[-1] = util.delete(message[-1])
message.append('size x y z: {}'.format(' x '.join(map(str,self.get_size()))))
message.append('origin x y z: {}'.format(' x '.join(map(str,origin_old))))
if np.any(origin_old != self.get_origin()):
message[-1] = util.delete(message[-1])
message.append('origin x y z: {}'.format(' x '.join(map(str,self.get_origin()))))
message.append('homogenization: {}'.format(self.get_homogenization()))
message.append('# microstructures: {}'.format(unique_old))
if unique_old != len(np.unique(self.microstructure)):
message[-1] = util.delete(message[-1])
message.append('# microstructures: {}'.format(len(np.unique(self.microstructure))))
message.append('max microstructure: {}'.format(max_old))
if max_old != np.nanmax(self.microstructure):
message[-1] = util.delete(message[-1])
message.append('max microstructure: {}'.format(np.nanmax(self.microstructure)))
return util.srepr(message)
def set_comments(self,comments):
self.comments = []
self.add_comments(comments)
def add_comments(self,comments):
self.comments += [str(c) for c in comments] if isinstance(comments,list) else [str(comments)]
def set_microstructure(self,microstructure):
if microstructure is not None:
if len(microstructure.shape) != 3:
raise ValueError('Invalid microstructure shape {}'.format(*microstructure.shape))
elif microstructure.dtype not in [int,float]:
raise TypeError('Invalid data type {} for microstructure'.format(microstructure.dtype))
else:
self.microstructure = microstructure
if len(size) != 3 or any(np.array(size)<=0):
raise ValueError('Invalid size {}'.format(*size))
else:
self.size = np.array(size)
if not isinstance(homogenization,int) or homogenization < 1:
raise TypeError('Invalid homogenization {}'.format(homogenization))
else:
self.homogenization = homogenization
if not isinstance(comments,list):
self.comments = [str(comments)]
else:
self.comments = [str(comment) for comment in comments]
def __repr__(self):
"""Basic information on geometry definition"""
return 'grid a b c: {}\n'.format(' x '.join(map(str,self.get_grid()))) + \
'size x y z: {}\n'.format(' x '.join(map(str,self.size))) + \
'homogenization: {}\n'.format(self.homogenization) + \
'# microstructures: {}\n'.format(len(np.unique(self.microstructure))) + \
'max microstructures: {}\n'.format(np.max(self.microstructure))
def update(self,microstructure=None,size=None,rescale=False):
"""Updates microstructure and size"""
grid_old = self.get_grid()
size_old = self.get_size()
unique_old = len(np.unique(self.microstructure))
max_old = np.max(self.microstructure)
if size is not None and rescale:
raise ValueError('Either set size explicitly or rescale automatically')
if microstructure is not None:
if len(microstructure.shape) != 3:
raise ValueError('Invalid microstructure shape {}'.format(*microstructure.shape))
elif microstructure.dtype not in ['int','float']:
raise TypeError('Invalid data type {} for microstructure'.format(microstructure.dtype))
else:
self.microstructure = microstructure
self.microstructure = np.copy(microstructure)
def set_size(self,size):
if size is not None:
if len(size) != 3 or any(np.array(size)<=0):
raise ValueError('Invalid size {}'.format(*size))
else:
self.size = np.array(size)
if rescale:
self.size = self.size * self.get_grid()/grid_old
message = ['grid a b c: {}'.format(' x '.join(map(str,grid_old)))]
if np.any(grid_old != self.get_grid()):
message[-1] = util.bcolors.CROSSOUT+message[-1]+util.bcolors.ENDC
message.append('grid a b c: {}'.format(' x '.join(map(str,self.get_grid()))))
message.append('size x y z: {}'.format(' x '.join(map(str,size_old))))
if np.any(size_old != self.size):
message[-1] = util.bcolors.CROSSOUT+message[-1]+util.bcolors.ENDC
message.append('size x y z: {}'.format(' x '.join(map(str,self.size))))
message.append('homogenization: {}'.format(self.homogenization))
message.append('# microstructures: {}'.format(unique_old))
if unique_old != len(np.unique(self.microstructure)):
message[-1] = util.bcolors.CROSSOUT+message[-1]+util.bcolors.ENDC
message.append('# microstructures: {}'.format(len(np.unique(self.microstructure))))
message.append('max microstructures: {}'.format(max_old))
if max_old != np.max(self.microstructure):
message[-1] = util.bcolors.CROSSOUT+message[-1]+util.bcolors.ENDC
message.append('max microstructures: {}'.format(np.max(self.microstructure)))
return '\n'.join(message)
def add_comment(self,comment):
if not isinstance(comment,list):
self.comments = [str(comment)] + self.comments
def set_origin(self,origin):
if origin is not None:
if len(origin) != 3:
raise ValueError('Invalid origin {}'.format(*origin))
else:
self.comments = [str(c) for c in comment] + self.comments
self.origin = np.array(origin)
def set_microstructure(self,microstructure):
self.microstructure = np.copy(microstructure)
def set_size(self,size):
self.size = np.array(size)
def set_homogenization(self,homogenization):
if homogenization is not None:
if not isinstance(homogenization,int) or homogenization < 1:
raise TypeError('Invalid homogenization {}'.format(homogenization))
else:
self.homogenization = homogenization
def get_microstructure(self):
@ -113,6 +116,9 @@ class Geom():
def get_size(self):
return np.copy(self.size)
def get_origin(self):
return np.copy(self.origin)
def get_grid(self):
return np.array(self.microstructure.shape)
@ -122,42 +128,44 @@ class Geom():
def get_comments(self):
return self.comments[:]
def get_header(self):
header = ['{} header'.format(len(self.comments)+4)] + self.comments
header.append('grid a {} b {} c {}'.format(*self.get_grid()))
header.append('size x {} y {} z {}'.format(*self.get_size()))
header.append('origin x {} y {} z {}'.format(*self.get_origin()))
header.append('homogenization {}'.format(self.get_homogenization()))
return header
@classmethod
def from_file(cls,fname):
"""Reads from *.geom file"""
if isinstance(fname,str):
f = open(fname)
header_length,keyword = f.readline().split()
if not keyword.startswith('head') or int(header_length) < 3:
"""Reads a geom file"""
with (open(fname) if isinstance(fname,str) else fname) as f:
f.seek(0)
header_length,keyword = f.readline().split()[:2]
header_length = int(header_length)
content = f.readlines()
if not keyword.startswith('head') or header_length < 3:
raise TypeError('Header length information missing or invalid')
comments_old = [f.readline() for i in range(int(header_length))]
else:
fname.seek(0)
header_length,keyword = fname.readline().split()
if not keyword.startswith('head') or int(header_length) < 3:
raise TypeError('Header length information missing or invalid')
comments_old = [fname.readline() for i in range(int(header_length))]
comments = []
for i,line in enumerate(comments_old):
if line.lower().strip().startswith('grid'):
grid = np.array([int(line.split()[j]) for j in [2,4,6]]) # assume correct order (a,b,c)
elif line.lower().strip().startswith('size'):
size = np.array([float(line.split()[j]) for j in [2,4,6]]) # assume correct order (x,y,z)
elif line.lower().strip().startswith('homogenization'):
homogenization = int(line.split()[1])
for i,line in enumerate(content[:header_length]):
items = line.lower().strip().split()
key = items[0] if len(items) > 0 else ''
if key == 'grid':
grid = np.array([ int(dict(zip(items[1::2],items[2::2]))[i]) for i in ['a','b','c']])
elif key == 'size':
size = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']])
elif key == 'origin':
origin = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']])
elif key == 'homogenization':
homogenization = int(items[1])
else:
comments.append(line.rstrip().strip())
if isinstance(fname,str):
raw = f.readlines()
f.close()
else:
raw = fname.readlines()
comments.append(line.strip())
microstructure = np.empty(grid.prod()) # initialize as flat array
i = 0
for line in raw:
for line in content[header_length:]:
items = line.split()
if len(items) == 3:
if items[1].lower() == 'of':
@ -175,28 +183,19 @@ class Geom():
raise TypeError('Invalid file: expected {} entries,found {}'.format(grid.prod(),i))
microstructure = microstructure.reshape(grid,order='F')
if '.' in raw[0]: # contains float values
pass
else: # assume int values
if not np.any(np.mod(microstructure.flatten(),1) != 0.0): # no float present
microstructure = microstructure.astype('int')
return cls(microstructure.reshape(grid),size,homogenization,comments)
return cls(microstructure.reshape(grid),size,origin,homogenization,comments)
def to_file(self,fname):
"""Saves to file"""
"""Writes to file"""
header = self.get_header()
grid = self.get_grid()
header = ['{} header'.format(len(self.comments)+3)]
header += self.comments
header.append('grid a {} b {} c {}'.format(*grid))
header.append('size x {} y {} z {}'.format(*self.size))
header.append('homogenization {}'.format(self.get_homogenization()))
if self.microstructure.dtype == 'int':
format_string='%{}i'.format(int(math.floor(math.log10(self.microstructure.max())+1)))
else:
format_string='%.18e'
np.savetxt(fname, self.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T,
format_string = '%{}i'.format(int(math.floor(math.log10(self.microstructure.max())+1))) if self.microstructure.dtype == int \
else '%g'
np.savetxt(fname,
self.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T,
header='\n'.join(header), fmt=format_string, comments='')
def show(self):

View File

@ -85,6 +85,11 @@ def delete(what):
"""Dims string"""
return bcolors.DIM+srepr(what)+bcolors.ENDC
# -----------------------------
def strikeout(what):
"""Dims string"""
return bcolors.CROSSOUT+srepr(what)+bcolors.ENDC
# -----------------------------
def execute(cmd,
streamIn = None,

211
test.log Normal file
View File

@ -0,0 +1,211 @@
2019-05-27 22:44:00,700 - INFO:
++++++++++++++++++++++++++++++++++++++++
----------------------------------------
| Check geom-modifying scripts
----------------------------------------
2019-05-27 22:44:00,707 - INFO:
geom_addPrimitive -c 0.3 0.5 0.2 -a 1.0 0.8 0.9 0.4 -d 0.10 0.13 0.08 geom_addPrimitive.geom
2019-05-27 22:44:00,899 - INFO:
geom_addPrimitive: geom_addPrimitive.geom
grid a b c: 32 x 35 x 12
size x y z: 0.914285714286 x 1.0 x 0.342857142857
origin x y z: 0.0 x 1.0 x 2.0
homogenization: 1
# microstructures: 20
max microstructure: 26
2019-05-27 22:44:00,899 - DEBUG:
2019-05-27 22:44:00,899 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_addPrimitive_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_addPrimitive.geom
2019-05-27 22:44:00,920 - INFO:
geom_canvas -g 40 35 20 -f 90 geom_canvas.geom
2019-05-27 22:44:01,103 - INFO:
geom_canvas: geom_canvas.geom
grid a b c: 32 x 35 x 12
size x y z: 0.914285714286 x 1.0 x 0.342857142857
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 20
max microstructures: 20
2019-05-27 22:44:01,103 - DEBUG:
2019-05-27 22:44:01,104 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_canvas_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_canvas.geom
2019-05-27 22:44:01,135 - INFO:
geom_clean -s 2 geom_clean.geom
2019-05-27 22:44:03,219 - INFO:
geom_clean: geom_clean.geom
grid a b c: 53 x 52 x 52
size x y z: 1.0 x 0.981132075472 x 0.981132075472
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 23
max microstructure: 23
2019-05-27 22:44:03,219 - DEBUG:
2019-05-27 22:44:03,219 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_clean_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_clean.geom
2019-05-27 22:44:03,378 - INFO:
geom_grainGrowth -N2 -i 4 -d 2 geom_grainGrowth.geom
2019-05-27 22:44:04,065 - INFO:
geom_grainGrowth: geom_grainGrowth.geom
grid a b c: 40 x 40 x 40
size x y z: 1.0 x 1.0 x 1.0
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 15
max microstructures: 15
grid a b c: 40 x 40 x 40
size x y z: 1.0 x 1.0 x 1.0
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 15
max microstructure: 15
2019-05-27 22:44:04,065 - DEBUG:
2019-05-27 22:44:04,065 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_grainGrowth_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_grainGrowth.geom
2019-05-27 22:44:04,131 - INFO:
geom_mirror -d x,y,z --double geom_mirror.geom
2019-05-27 22:44:04,330 - INFO:
geom_mirror: geom_mirror.geom
grid a b c: 32 x 35 x 12
grid a b c: 64 x 70 x 24
size x y z: 0.914285714286 x 1.0 x 0.342857142857
size x y z: 2.0 x 2.0 x 2.0
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 20
max microstructure: 20
2019-05-27 22:44:04,331 - DEBUG:
2019-05-27 22:44:04,331 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_mirror_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_mirror.geom
2019-05-27 22:44:04,447 - INFO:
geom_renumber geom_renumber.geom
2019-05-27 22:44:04,688 - INFO:
geom_renumber: geom_renumber.geom
grid a b c: 53 x 52 x 52
size x y z: 1.0 x 0.981132075472 x 0.981132075472
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 23
max microstructure: 42
max microstructure: 23
2019-05-27 22:44:04,688 - DEBUG:
2019-05-27 22:44:04,688 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_renumber_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_renumber.geom
2019-05-27 22:44:04,864 - INFO:
geom_rescale -g 20 22 20 -s 0.1 0.2 0.3 geom_rescale.geom
2019-05-27 22:44:05,109 - INFO:
geom_rescale: geom_rescale.geom
grid a b c: 32 x 35 x 12
grid a b c: 20 x 22 x 20
size x y z: 0.914285714286 x 1.0 x 0.342857142857
size x y z: 0.1 x 0.2 x 0.3
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 20
max microstructure: 20
2019-05-27 22:44:05,109 - DEBUG:
2019-05-27 22:44:05,109 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_rescale_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_rescale.geom
2019-05-27 22:44:05,122 - INFO:
geom_rotate -d -e 45 45 0 geom_rotate.geom
2019-05-27 22:44:05,529 - INFO:
geom_rotate: geom_rotate.geom
grid a b c: 53 x 52 x 52
grid a b c: 90 x 90 x 74
size x y z: 1.0 x 0.981132075472 x 0.981132075472
size x y z: 1.6981132075471699 x 1.7307692307692308 x 1.4230769230769231
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 23
# microstructures: 24
max microstructure: 23
max microstructure: 24
2019-05-27 22:44:05,530 - DEBUG:
2019-05-27 22:44:05,530 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_rotate_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_rotate.geom
2019-05-27 22:44:06,282 - INFO:
geom_translate -o 0 1 2 -m 6 geom_translate.geom
2019-05-27 22:44:06,469 - INFO:
geom_translate: geom_translate.geom
grid a b c: 32 x 35 x 12
size x y z: 0.914285714286 x 1.0 x 0.342857142857
origin x y z: 0.0 x 0.0 x 0.0
origin x y z: 0.0 x 1.0 x 2.0
homogenization: 1
# microstructures: 20
max microstructure: 20
max microstructure: 26
2019-05-27 22:44:06,469 - DEBUG:
2019-05-27 22:44:06,469 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_translate_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_translate.geom
2019-05-27 22:44:06,486 - INFO:
geom_vicinityOffset -v 2 geom_vicinityOffset.geom
2019-05-27 22:44:07,005 - INFO:
geom_vicinityOffset: geom_vicinityOffset.geom
grid a b c: 40 x 40 x 40
size x y z: 1.0 x 1.0 x 1.0
origin x y z: 0.0 x 0.0 x 0.0
homogenization: 1
# microstructures: 5
# microstructures: 10
max microstructure: 5
max microstructure: 10
2019-05-27 22:44:07,005 - DEBUG:
2019-05-27 22:44:07,005 - INFO:
comparing
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/reference/geom_vicinityOffset_reference.geom
/Users/philip/Documents/DAMASK/PRIVATE/testing/PreProcessing_GeomModification/current/geom_vicinityOffset.geom
2019-05-27 22:44:07,076 - CRITICAL:
****************************************
All 10 tests passed.
****************************************