From 99da46fda8137a5e031265b4941599ead04742a4 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sun, 26 May 2019 20:36:41 +0200 Subject: [PATCH] polished --- PRIVATE | 2 +- processing/pre/geom_addPrimitive.py | 94 +++++++------- processing/pre/geom_canvas.py | 173 +++++++------------------- processing/pre/geom_clean.py | 6 +- processing/pre/geom_grainGrowth.py | 118 +++++------------- processing/pre/geom_renumber.py | 6 +- processing/pre/geom_rescale.py | 4 +- processing/pre/geom_translate.py | 29 +++-- processing/pre/geom_vicinityOffset.py | 34 ++--- 9 files changed, 172 insertions(+), 294 deletions(-) diff --git a/PRIVATE b/PRIVATE index d326605a4..d59698231 160000 --- a/PRIVATE +++ b/PRIVATE @@ -1 +1 @@ -Subproject commit d326605a49b90dfdf3352f1a6a4ae8dd36507a13 +Subproject commit d596982319b5e8bbded6c14a5724df6c9de2a0fd diff --git a/processing/pre/geom_addPrimitive.py b/processing/pre/geom_addPrimitive.py index ec7a84ec6..72f5019e6 100755 --- a/processing/pre/geom_addPrimitive.py +++ b/processing/pre/geom_addPrimitive.py @@ -1,60 +1,72 @@ #!/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 option [geomfile(s)]', description = """ -Positions a geometric object within the (three-dimensional) canvas of a spectral geometry description. +parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [geomfile(s)]', description = """ +Inserts a primitive geometric object at a given position. Depending on the sign of the dimension parameters, these objects can be boxes, cylinders, or ellipsoids. """, version = scriptID) -parser.add_option('-c', '--center', dest='center', +parser.add_option('-c', '--center', + dest='center', type='float', nargs = 3, metavar=' '.join(['float']*3), help='a,b,c origin of primitive %default') -parser.add_option('-d', '--dimension', dest='dimension', +parser.add_option('-d', '--dimension', + dest='dimension', type='float', nargs = 3, metavar=' '.join(['float']*3), - help='a,b,c extension of hexahedral box; negative values are diameters') -parser.add_option('-e', '--exponent', dest='exponent', + help='a,b,c extension of hexahedral box') +parser.add_option('-e', '--exponent', + dest='exponent', type='float', nargs = 3, metavar=' '.join(['float']*3), help='i,j,k exponents for axes - 0 gives octahedron (|x|^(2^0) + |y|^(2^0) + |z|^(2^0) < 1), \ 1 gives a sphere (|x|^(2^1) + |y|^(2^1) + |z|^(2^1) < 1), \ - large values produce boxes, negative turns concave.') -parser.add_option('-f', '--fill', dest='fill', - type='float', metavar = 'float', - help='grain index to fill primitive. "0" selects maximum microstructure index + 1 [%default]') -parser.add_option('-q', '--quaternion', dest='quaternion', + large values produce boxes, negative turn concave.') +parser.add_option('-f', '--fill', + dest='fill', + type='float', metavar = 'int', + help='microstructure index to fill primitive, defaults to max microstructure index + 1') +parser.add_option('-q', '--quaternion', + dest='quaternion', type='float', nargs = 4, metavar=' '.join(['float']*4), help = 'rotation of primitive as quaternion') -parser.add_option('-a', '--angleaxis', dest='angleaxis', type=float, - nargs = 4, metavar=' '.join(['float']*4), +parser.add_option('-a', '--angleaxis', + dest='angleaxis', + type=float, nargs = 4, metavar=' '.join(['float']*4), help = 'axis and angle to rotate primitive') -parser.add_option( '--degrees', dest='degrees', +parser.add_option( '--degrees', + dest='degrees', action='store_true', - help = 'angle is given in degrees [%default]') -parser.add_option( '--nonperiodic', dest='periodic', + help = 'angle is given in degrees') +parser.add_option( '--nonperiodic', + dest='periodic', action='store_false', - help = 'wrap around edges [%default]') -parser.add_option( '--realspace', dest='realspace', + help = 'wrap around edges') +parser.add_option( '--realspace', + dest='realspace', action='store_true', help = '-c and -d span [origin,origin+size] instead of [0,grid] coordinates') -parser.add_option( '--invert', dest='inside', +parser.add_option( '--invert', + dest='inside', action='store_false', help = 'invert the volume filled by the primitive (inside/outside)') + parser.set_defaults(center = (.0,.0,.0), - fill = 0.0, degrees = False, exponent = (20,20,20), # box shape by default periodic = True, @@ -65,7 +77,10 @@ parser.set_defaults(center = (.0,.0,.0), (options, filenames) = parser.parse_args() if options.dimension is None: - parser.error('no dimension specified.') + parser.error('no dimension specified.') +if [options.angleaxis,options.quaternion].count(None) == 2: + parser.error('more than one rotation specified.') + if options.angleaxis is not None: rotation = damask.Rotation.fromAxisAngle(np.array(options.angleaxis),options.degrees,normalise=True) elif options.quaternion is not None: @@ -73,22 +88,11 @@ elif options.quaternion is not None: else: rotation = damask.Rotation() -options.center = np.array(options.center) +options.center = np.array(options.center) options.dimension = np.array(options.dimension) # undo logarithmic sense of exponent and generate ellipsoids for negative dimensions (backward compatibility) -options.exponent = np.where(np.array(options.dimension) > 0, np.power(2,options.exponent), 2) +options.exponent = np.where(np.array(options.dimension) > 0, np.power(2,options.exponent), 2) -# --- loop over input files ------------------------------------------------------------------------- -if filenames == []: filenames = [None] - -for name in filenames: - try: table = damask.ASCIItable(name = name, - buffered = False, - labeled = False) - except: continue - damask.util.report(scriptName,name) - -# --- loop over input files ------------------------------------------------------------------------- if filenames == []: filenames = [None] @@ -100,9 +104,10 @@ for name in filenames: geom = damask.Geom.from_file(virt_file) else: geom = damask.Geom.from_file(name) - microstructure = geom.microstructure + damask.util.croak(geom) + microstructure = geom.get_microstructure() - options.fill = np.nanmax(microstructure)+1 if options.fill == 0 else options.fill + 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): @@ -176,20 +181,19 @@ for name in filenames: grid[2] * k : grid[2] * (k+1)])**options.exponent[2] <= 1.0) microstructure = np.where(inside, - options.fill if options.inside else microstructure, - microstructure if options.inside else options.fill) + fill if options.inside else microstructure, + microstructure if options.inside else fill) else: # nonperiodic, much lighter on resources microstructure = np.where(np.abs(X)**options.exponent[0] + np.abs(Y)**options.exponent[1] + np.abs(Z)**options.exponent[2] <= 1.0, - options.fill if options.inside else microstructure, - microstructure if options.inside else options.fill) + fill if options.inside else microstructure, + microstructure if options.inside else fill) - geom.microstructure = microstructure + damask.util.croak(geom.update(microstructure)) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - damask.util.croak(geom) if name is None: sys.stdout.write(str(geom.show())) else: diff --git a/processing/pre/geom_canvas.py b/processing/pre/geom_canvas.py index a3f1b7f3b..7998c42c5 100755 --- a/processing/pre/geom_canvas.py +++ b/processing/pre/geom_canvas.py @@ -1,160 +1,83 @@ #!/usr/bin/env python3 -# -*- coding: UTF-8 no BOM -*- -import os,sys,math -import numpy as np +import os +import sys +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 option(s) [geomfile(s)]', description = """ -Changes the (three-dimensional) canvas of a spectral geometry description. +parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [geomfile(s)]', description = """ +Increases or decreases the (three-dimensional) canvas. 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. [auto]') -parser.add_option('-o', - '--offset', + help = 'a,b,c grid of hexahedral box') +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 = 'int', metavar = 'int', - help = '(background) canvas grain index. "0" selects maximum microstructure index + 1 [%default]') + type = 'float', metavar = 'int', + help = 'background microstructure index, defaults to max microstructure index + 1') -parser.set_defaults(grid = ('0','0','0'), - offset = (0,0,0), - ) +parser.set_defaults(offset = (0,0,0)) (options, filenames) = parser.parse_args() -datatype = 'i' - if filenames == []: filenames = [None] for name in filenames: - try: table = damask.ASCIItable(name = name, - buffered = False, - labeled = False) - except: continue damask.util.report(scriptName,name) - - if True: - -# --- interpret header ---------------------------------------------------------------------------- - - table.head_read() - info,extra_header = table.head_getGeom() - damask.util.report_geom(info) - - errors = [] - if np.any(info['grid'] < 1): errors.append('invalid grid a b c.') - if np.any(info['size'] <= 0.0): errors.append('invalid size x y z.') - if errors != []: - damask.util.croak(errors) - table.close(dismiss = True) - continue - -# --- read data ------------------------------------------------------------------------------------ - - microstructure = table.microstructure_read(info['grid'],datatype).reshape(info['grid'],order='F') # read microstructure - -# --- do work ------------------------------------------------------------------------------------ - - newInfo = { - 'grid': np.zeros(3,'i'), - 'origin': np.zeros(3,'d'), - 'microstructures': 0, - } - - newInfo['grid'] = np.array([int(o*float(n.translate(None,'xX'))) if n[-1].lower() == 'x'\ - else int(n) for o,n in zip(info['grid'],options.grid)],'i') - newInfo['grid'] = np.where(newInfo['grid'] > 0, newInfo['grid'],info['grid']) - - microstructure_cropped = np.zeros(newInfo['grid'],datatype) - microstructure_cropped.fill(options.fill if options.fill is not None else np.nanmax(microstructure)+1) - if True: - xindex = np.arange(max(options.offset[0],0),min(options.offset[0]+newInfo['grid'][0],info['grid'][0])) - yindex = np.arange(max(options.offset[1],0),min(options.offset[1]+newInfo['grid'][1],info['grid'][1])) - zindex = np.arange(max(options.offset[2],0),min(options.offset[2]+newInfo['grid'][2],info['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.') - table.close(dismiss = True) - 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] + 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) + microstructure = geom.get_microstructure() + + 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]) - newInfo['size'] = info['size']/info['grid']*newInfo['grid'] if np.all(info['grid'] > 0) else newInfo['grid'] - newInfo['origin'] = info['origin']+(info['size']/info['grid'] if np.all(info['grid'] > 0) \ - else newInfo['size']/newInfo['grid'])*options.offset - newInfo['microstructures'] = len(np.unique(microstructure_cropped)) + new = np.full(grid,options.fill if options.fill is not None else np.nanmax(microstructure)+1, + microstructure.dtype) + + 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] -# --- report --------------------------------------------------------------------------------------- + damask.util.croak(geom.update(new,rescale=True)) + geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - remarks = [] - errors = [] - - if (any(newInfo['grid'] != info['grid'])): - remarks.append('--> grid a b c: {}'.format(' x '.join(map(str,newInfo['grid'])))) - if (any(newInfo['size'] != info['size'])): - remarks.append('--> size x y z: {}'.format(' x '.join(map(str,newInfo['size'])))) - if (any(newInfo['origin'] != info['origin'])): - remarks.append('--> origin x y z: {}'.format(' : '.join(map(str,newInfo['origin'])))) - if ( newInfo['microstructures'] != info['microstructures']): - remarks.append('--> microstructures: {}'.format(newInfo['microstructures'])) - - if np.any(newInfo['grid'] < 1): errors.append('invalid new grid a b c.') - if np.any(newInfo['size'] <= 0.0): errors.append('invalid new size x y z.') - - if remarks != []: damask.util.croak(remarks) - if errors != []: - damask.util.croak(errors) - table.close(dismiss = True) - continue - -# --- write header --------------------------------------------------------------------------------- - - table.info_clear() - table.info_append(extra_header+[ - scriptID + ' ' + ' '.join(sys.argv[1:]), - "grid\ta {}\tb {}\tc {}".format(*newInfo['grid']), - "size\tx {}\ty {}\tz {}".format(*newInfo['size']), - "origin\tx {}\ty {}\tz {}".format(*newInfo['origin']), - "homogenization\t{}".format(info['homogenization']), - "microstructures\t{}".format(newInfo['microstructures']), - ]) - table.labels_clear() - table.head_write() - table.output_flush() - -# --- write microstructure information ------------------------------------------------------------ - - format = '%{}i'.format(int(math.floor(math.log10(np.nanmax(microstructure_cropped))+1))) - table.data = microstructure_cropped.reshape((newInfo['grid'][0],newInfo['grid'][1]*newInfo['grid'][2]),order='F').transpose() - table.data_writeArray(format,delimiter=' ') - -# --- output finalization -------------------------------------------------------------------------- - - table.close() # close ASCII table + if name is None: + sys.stdout.write(str(geom.show())) + else: + geom.to_file(name) diff --git a/processing/pre/geom_clean.py b/processing/pre/geom_clean.py index 4d7b0a0e5..9ed8e88b4 100755 --- a/processing/pre/geom_clean.py +++ b/processing/pre/geom_clean.py @@ -49,15 +49,15 @@ for name in filenames: geom = damask.Geom.from_file(virt_file) else: geom = damask.Geom.from_file(name) + damask.util.croak(geom) microstructure = geom.get_microstructure() microstructure = ndimage.filters.generic_filter(microstructure,mostFrequent, size=(options.stencil,)*3).astype(microstructure.dtype) - geom.set_microstructure(microstructure) + damask.util.croak(geom.update(microstructure)) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - - damask.util.croak(geom) + if name is None: sys.stdout.write(str(geom.show())) else: diff --git a/processing/pre/geom_grainGrowth.py b/processing/pre/geom_grainGrowth.py index f7c50c2e5..2403fd410 100755 --- a/processing/pre/geom_grainGrowth.py +++ b/processing/pre/geom_grainGrowth.py @@ -1,21 +1,28 @@ #!/usr/bin/env python3 -# -*- coding: UTF-8 no BOM -*- -import os,sys,math -import numpy as np +import os +import sys from optparse import OptionParser + +import numpy as np from scipy import ndimage + import damask scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptID = ' '.join([scriptName,damask.version]) + +getInterfaceEnergy = lambda A,B: np.float32((A*B != 0)*(A != B)*1.0) # 1.0 if A & B are distinct & nonzero, 0.0 otherwise +struc = ndimage.generate_binary_structure(3,1) # 3D von Neumann neighborhood + + #-------------------------------------------------------------------------------------------------- # MAIN #-------------------------------------------------------------------------------------------------- -parser = OptionParser(option_class=damask.extendableOption, usage='%prog [option(s)] [geomfile(s)]', description = """ -Smoothens out interface roughness by simulated curvature flow. +parser = OptionParser(option_class=damask.extendableOption, usage='%prog option(s) [geomfile(s)]', description = """ +Smoothen interface roughness by simulated curvature flow. This is achieved by the diffusion of each initially sharply bounded grain volume within the periodic domain up to a given distance 'd' voxels. The final geometry is assembled by selecting at each voxel that grain index for which the concentration remains largest. @@ -33,55 +40,33 @@ parser.add_option('-N', '--iterations', parser.add_option('-i', '--immutable', action = 'extend', dest = 'immutable', metavar = '', help = 'list of immutable microstructure indices') -parser.add_option('-r', '--renumber', - dest = 'renumber', action='store_true', - help = 'output consecutive microstructure indices') parser.add_option('--ndimage', dest = 'ndimage', action='store_true', help = 'use ndimage.gaussian_filter in lieu of explicit FFT') parser.set_defaults(d = 1, N = 1, - immutable = [], - renumber = False, - ndimage = False, + immutable = [], + ndimage = False, ) (options, filenames) = parser.parse_args() options.immutable = list(map(int,options.immutable)) -getInterfaceEnergy = lambda A,B: np.float32((A*B != 0)*(A != B)*1.0) # 1.0 if A & B are distinct & nonzero, 0.0 otherwise -struc = ndimage.generate_binary_structure(3,1) # 3D von Neumann neighborhood - -# --- loop over input files ----------------------------------------------------------------------- - -if filenames == []: filenames = [None] for name in filenames: - try: table = damask.ASCIItable(name = name, - buffered = False, - labeled = False) - except: continue damask.util.report(scriptName,name) - -# --- interpret header ---------------------------------------------------------------------------- - - table.head_read() - info,extra_header = table.head_getGeom() - damask.util.report_geom(info) - - errors = [] - if np.any(info['grid'] < 1): errors.append('invalid grid a b c.') - if np.any(info['size'] <= 0.0): errors.append('invalid size x y z.') - if errors != []: - damask.util.croak(errors) - table.close(dismiss = True) - continue - -# --- read data ----------------------------------------------------------------------------------- - microstructure = np.tile(table.microstructure_read(info['grid']).reshape(info['grid'],order='F'), - np.where(info['grid'] == 1, 2,1)) # make one copy along dimensions with grid == 1 + + 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) + + grid_original = geom.get_grid() + microstructure = np.tile(geom.get_microstructure(),np.where(grid_original == 1, 2,1)) # make one copy along dimensions with grid == 1 grid = np.array(microstructure.shape) # --- initialize support data --------------------------------------------------------------------- @@ -94,7 +79,7 @@ for name in filenames: # Calculates gaussian weights for simulating 3d diffusion gauss = np.exp(-(X*X + Y*Y + Z*Z)/(2.0*options.d*options.d),dtype=np.float32) \ - /np.power(2.0*np.pi*options.d*options.d,(3.0 - np.count_nonzero(info['grid'] == 1))/2.,dtype=np.float32) + /np.power(2.0*np.pi*options.d*options.d,(3.0 - np.count_nonzero(grid_original == 1))/2.,dtype=np.float32) gauss[:,:,:grid[2]//2:-1] = gauss[:,:,1:(grid[2]+1)//2] # trying to cope with uneven (odd) grid size gauss[:,:grid[1]//2:-1,:] = gauss[:,1:(grid[1]+1)//2,:] @@ -156,7 +141,7 @@ for name in filenames: # transform voxels close to interface region index = ndimage.morphology.distance_transform_edt(periodic_diffusedEnergy >= 0.95*np.amax(periodic_diffusedEnergy), return_distances = False, - return_indices = True) # want index of closest bulk grain + return_indices = True) # want index of closest bulk grain periodic_microstructure = np.tile(microstructure,(3,3,3))[grid[0]//2:-grid[0]//2, grid[1]//2:-grid[1]//2, @@ -184,49 +169,10 @@ for name in filenames: # undo any changes involving immutable microstructures microstructure = np.where(immutable, microstructure_original,microstructure) -# --- renumber to sequence 1...Ngrains if requested ----------------------------------------------- -# http://stackoverflow.com/questions/10741346/np-frequency-counts-for-unique-values-in-an-array + 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:])) - if options.renumber: - newID = 0 - for microstructureID,count in enumerate(np.bincount(microstructure.flatten())): - if count != 0: - newID += 1 - microstructure = np.where(microstructure == microstructureID, newID, microstructure) - - newInfo = {'microstructures': len(np.unique(microstructure)),} - -# --- report -------------------------------------------------------------------------------------- - - remarks = [] - if newInfo['microstructures'] != info['microstructures']: - remarks.append('--> microstructures: {}'.format(newInfo['microstructures'])) - if remarks != []: damask.util.croak(remarks) - -# --- write header -------------------------------------------------------------------------------- - - table.labels_clear() - table.info_clear() - table.info_append(extra_header+[ - scriptID + ' ' + ' '.join(sys.argv[1:]), - "grid\ta {grid[0]}\tb {grid[1]}\tc {grid[2]}".format(grid=info['grid']), - "size\tx {size[0]}\ty {size[1]}\tz {size[2]}".format(size=info['size']), - "origin\tx {origin[0]}\ty {origin[1]}\tz {origin[2]}".format(origin=info['origin']), - "homogenization\t{homog}".format(homog=info['homogenization']), - "microstructures\t{microstructures}".format(microstructures=newInfo['microstructures']), - ]) - table.head_write() - -# --- write microstructure information ------------------------------------------------------------ - - formatwidth = int(math.floor(math.log10(np.nanmax(microstructure))+1)) - table.data = microstructure[::1 if info['grid'][0]>1 else 2, - ::1 if info['grid'][1]>1 else 2, - ::1 if info['grid'][2]>1 else 2,].\ - reshape((info['grid'][0],info['grid'][1]*info['grid'][2]),order='F').transpose() - table.data_writeArray('%{}i'.format(formatwidth),delimiter = ' ') - -# --- output finalization -------------------------------------------------------------------------- - - table.close() - \ No newline at end of file + if name is None: + sys.stdout.write(str(geom.show())) + else: + geom.to_file(name) diff --git a/processing/pre/geom_renumber.py b/processing/pre/geom_renumber.py index e46296555..25f67bd50 100755 --- a/processing/pre/geom_renumber.py +++ b/processing/pre/geom_renumber.py @@ -18,7 +18,7 @@ scriptID = ' '.join([scriptName,damask.version]) # MAIN #-------------------------------------------------------------------------------------------------- -parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [geomfile(s)]', description = """ +parser = OptionParser(option_class=damask.extendableOption, usage='%prog [geomfile(s)]', description = """ Renumber sorted microstructure indices to 1,...,N. """, version=scriptID) @@ -36,16 +36,16 @@ for name in filenames: geom = damask.Geom.from_file(virt_file) else: geom = damask.Geom.from_file(name) + damask.util.croak(geom) microstructure = geom.get_microstructure() renumbered = np.copy(microstructure) for i, oldID in enumerate(np.unique(microstructure)): renumbered = np.where(microstructure == oldID, i+1, renumbered) - geom.set_microstructure(renumbered) + damask.util.croak(geom.update(renumbered)) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - damask.util.croak(geom) if name is None: sys.stdout.write(str(geom.show())) else: diff --git a/processing/pre/geom_rescale.py b/processing/pre/geom_rescale.py index e39a9d0d6..c1ca091a4 100755 --- a/processing/pre/geom_rescale.py +++ b/processing/pre/geom_rescale.py @@ -53,13 +53,13 @@ for name in filenames: 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] + else float(options.grid[i])/scale[i] 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] + else options.size[i] microstructure = ndimage.interpolation.zoom(microstructure, scale, output=microstructure.dtype, order=0, mode='nearest', prefilter=False) diff --git a/processing/pre/geom_translate.py b/processing/pre/geom_translate.py index 63fa1d421..cffde28a7 100755 --- a/processing/pre/geom_translate.py +++ b/processing/pre/geom_translate.py @@ -1,22 +1,25 @@ #!/usr/bin/env python3 -# -*- coding: UTF-8 no BOM -*- import os import sys -import numpy as np from optparse import OptionParser from io import StringIO + +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 [file[s]]', description = """ -translate microstructure indices (shift or substitute) and/or geometry origin. +parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [geomfile(s)]', description = """ +Translate microstructure indices (shift or substitute) and/or geometry origin. """, version=scriptID) @@ -27,7 +30,7 @@ parser.add_option('-o', '--origin', parser.add_option('-m', '--microstructure', dest = 'microstructure', type = 'int', metavar = 'int', - help = 'offset from old to new microstructure indices') + help = 'offset from old to new microstructure indices (after substitution)') parser.add_option('-s', '--substitute', dest = 'substitute', action = 'extend', metavar = '', @@ -44,7 +47,6 @@ 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]) -# --- loop over input files ------------------------------------------------------------------------- if filenames == []: filenames = [None] @@ -56,11 +58,13 @@ for name in filenames: geom = damask.Geom.from_file(virt_file) else: geom = damask.Geom.from_file(name) - microstructure = geom.microstructure + damask.util.croak(geom) + microstructure = geom.get_microstructure() + new = np.copy(microstructure) - for k, v in sub.items(): microstructure[geom.microstructure==k] = v # substitute microstructure indices - - microstructure += options.microstructure # shift microstructure indices + for k, v in sub.items(): new[microstructure==k] = v # substitute microstructure indices and shift + + microstructure += options.microstructure # constant shift for i,line in enumerate(geom.comments): if line.lower().strip().startswith('origin'): @@ -68,10 +72,9 @@ for name in filenames: origin += np.array(origin) geom.comments[i] = 'origin x {} y {} z {}'.format(*origin) - geom.microstructure = microstructure + damask.util.croak(geom.update(microstructure)) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - - damask.util.croak(geom) + if name is None: sys.stdout.write(str(geom.show())) else: diff --git a/processing/pre/geom_vicinityOffset.py b/processing/pre/geom_vicinityOffset.py index 535650244..f058e9424 100755 --- a/processing/pre/geom_vicinityOffset.py +++ b/processing/pre/geom_vicinityOffset.py @@ -1,17 +1,20 @@ #!/usr/bin/env python3 -# -*- coding: UTF-8 no BOM -*- import os import sys -import numpy as np -from scipy import ndimage -from optparse import OptionParser from io import StringIO +from optparse import OptionParser + +from scipy import ndimage +import numpy as np + import damask + scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptID = ' '.join([scriptName,damask.version]) + def taintedNeighborhood(stencil,trigger=[],size=1): me = stencil[stencil.shape[0]//2] @@ -23,11 +26,12 @@ def taintedNeighborhood(stencil,trigger=[],size=1): trigger = list(trigger) return np.any(np.in1d(stencil,np.array(trigger))) + #-------------------------------------------------------------------------------------------------- # MAIN #-------------------------------------------------------------------------------------------------- -parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [file[s]]', description = """ +parser = OptionParser(option_class=damask.extendableOption, usage='%prog options [geomfile(s)]', description = """ Offset microstructure index for points which see a microstructure different from themselves (or listed as triggers) within a given (cubic) vicinity, i.e. within the region close to a grain/phase boundary. @@ -40,10 +44,10 @@ parser.add_option('-v', '--vicinity', parser.add_option('-m', '--microstructureoffset', dest='offset', type = 'int', metavar = 'int', - help = 'offset (positive or negative) for tagged microstructure indices. '+ - '"0" selects maximum microstructure index [%default]') + help='offset (positive or negative) to tag microstructure indices, defaults to max microstructure index + 1') parser.add_option('-t', '--trigger', - action = 'extend', dest = 'trigger', metavar = '', + dest = 'trigger', + action = 'extend', metavar = '', help = 'list of microstructure indices triggering a change') parser.add_option('-n', '--nonperiodic', dest = 'mode', @@ -51,17 +55,15 @@ parser.add_option('-n', '--nonperiodic', help = 'assume geometry to be non-periodic') parser.set_defaults(vicinity = 1, - offset = 0, trigger = [], mode = 'wrap', ) (options, filenames) = parser.parse_args() + options.trigger = np.array(options.trigger, dtype=int) -# --- loop over input files ------------------------------------------------------------------------- - if filenames == []: filenames = [None] for name in filenames: @@ -72,21 +74,21 @@ for name in filenames: geom = damask.Geom.from_file(virt_file) else: geom = damask.Geom.from_file(name) - microstructure = geom.microstructure + damask.util.croak(geom) + microstructure = geom.get_microstructure() - if options.offset == 0: options.offset = microstructure.max() + offset = options.offset if options.offset is not None else np.nanmax(microstructure) microstructure = np.where(ndimage.filters.generic_filter(microstructure, taintedNeighborhood, size=1+2*options.vicinity,mode=options.mode, extra_arguments=(), extra_keywords={"trigger":options.trigger,"size":1+2*options.vicinity}), - microstructure + options.offset,microstructure) + microstructure + offset,microstructure) - geom.microstructure = microstructure + damask.util.croak(geom.update(microstructure)) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - damask.util.croak(geom) if name is None: sys.stdout.write(str(geom.show())) else: