From 875643c363a251fbc5ca6e9585e26329ac2a76d7 Mon Sep 17 00:00:00 2001 From: Martin Diehl Date: Sat, 25 May 2019 10:14:53 +0200 Subject: [PATCH] same style --- processing/pre/geom_fromMinimalSurface.py | 6 +- processing/pre/geom_mirror.py | 3 +- processing/pre/geom_renumber.py | 82 ++++------------ processing/pre/geom_rotate.py | 15 ++- processing/pre/geom_translate.py | 109 ++++++---------------- processing/pre/geom_unpack.py | 12 +-- processing/pre/geom_vicinityOffset.py | 10 +- python/damask/geom.py | 26 +++--- 8 files changed, 82 insertions(+), 181 deletions(-) diff --git a/processing/pre/geom_fromMinimalSurface.py b/processing/pre/geom_fromMinimalSurface.py index 66e26c8e2..37610edd0 100755 --- a/processing/pre/geom_fromMinimalSurface.py +++ b/processing/pre/geom_fromMinimalSurface.py @@ -73,7 +73,6 @@ parser.set_defaults(type = minimal_surfaces[0], if filenames == []: filenames = [None] for name in filenames: - damask.util.report(scriptName,name) X = options.periods*2.0*math.pi*(np.arange(options.grid[0])+0.5)/options.grid[0] @@ -89,9 +88,8 @@ for name in filenames: geom=damask.Geom(options.size,microstructure,options.homogenization, comments=[scriptID + ' ' + ' '.join(sys.argv[1:])]) - damask.util.croak('\n'.join(geom.info())) - + damask.util.croak(geom) if name is None: - sys.stdout.write(str(geom)) + sys.stdout.write(str(geom.show())) else: geom.to_file(name) diff --git a/processing/pre/geom_mirror.py b/processing/pre/geom_mirror.py index 953e10e2d..ded9b373b 100755 --- a/processing/pre/geom_mirror.py +++ b/processing/pre/geom_mirror.py @@ -4,8 +4,9 @@ import os import sys import numpy as np -import damask from optparse import OptionParser +from io import StringIO +import damask scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptID = ' '.join([scriptName,damask.version]) diff --git a/processing/pre/geom_renumber.py b/processing/pre/geom_renumber.py index 3faa7f449..f4570d08c 100755 --- a/processing/pre/geom_renumber.py +++ b/processing/pre/geom_renumber.py @@ -1,10 +1,12 @@ #!/usr/bin/env python3 # -*- coding: UTF-8 no BOM -*- -import os,sys,math +import os +import sys import numpy as np -import damask from optparse import OptionParser +from io import StringIO +import damask scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptID = ' '.join([scriptName,damask.version]) @@ -25,36 +27,14 @@ renumber sorted microstructure indices to 1,...,N. 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 = table.microstructure_read(info['grid']) # read microstructure - -# --- do work ------------------------------------------------------------------------------------ - - newInfo = { - 'origin': np.zeros(3,'d'), - 'microstructures': 0, - } + + 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 grainIDs = np.unique(microstructure) renumbered = np.copy(microstructure) @@ -62,35 +42,11 @@ for name in filenames: for i, oldID in enumerate(grainIDs): renumbered = np.where(microstructure == oldID, i+1, renumbered) - newInfo['microstructures'] = len(grainIDs) - -# --- report ------------------------------------------------------------------------------------- - - remarks = [] - if ( newInfo['microstructures'] != info['microstructures']): - remarks.append('--> microstructures: %i'%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 ----------------------------------------------------------- - - format = '%{}i'.format(int(math.floor(math.log10(np.nanmax(renumbered))+1))) - table.data = renumbered.reshape((info['grid'][0],info['grid'][1]*info['grid'][2]),order='F').transpose() - table.data_writeArray(format,delimiter = ' ') - -# --- output finalization ------------------------------------------------------------------------ - - table.close() # close ASCII table + geom.microstructure = renumbered + geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) + + damask.util.croak(geom) + if name is None: + sys.stdout.write(str(geom.show())) + else: + geom.to_file(name) diff --git a/processing/pre/geom_rotate.py b/processing/pre/geom_rotate.py index c343e2752..98faf1e6b 100755 --- a/processing/pre/geom_rotate.py +++ b/processing/pre/geom_rotate.py @@ -57,26 +57,26 @@ if sum(x is not None for x in [options.rotation,options.eulers,options.matrix,op if options.quaternion is not None: eulers = damask.Rotation.fromQuaternion(np.array(options.quaternion)).asEulers(degrees=True) if options.rotation is not None: - eulers = damask.Rotation.fromAxisAngle(np.array(options.rotation,degrees=True)).asEulers(degrees=True) + eulers = damask.Rotation.fromAxisAngle(np.array(options.rotation,degrees=options.degrees)).asEulers(degrees=True) if options.matrix is not None: eulers = damask.Rotation.fromMatrix(np.array(options.Matrix)).asEulers(degrees=True) if options.eulers is not None: - eulers = damask.Rotation.fromEulers(np.array(options.eulers),degrees=True).asEulers(degrees=True) + eulers = damask.Rotation.fromEulers(np.array(options.eulers),degrees=options.degrees).asEulers(degrees=True) # --- 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) else: geom = damask.Geom.from_file(name) - - damask.util.report(scriptName,name) - microstructure = geom.microstructure + spacing = geom.get_size()/geom.get_grid() newGrainID = options.fill if options.fill is not None else np.nanmax(microstructure)+1 @@ -91,9 +91,8 @@ for name in filenames: geom.set_size(microstructure.shape*spacing) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - damask.util.croak('\n'.join(geom.info())) - + damask.util.croak(geom) if name is None: - sys.stdout.write(str(geom)) + sys.stdout.write(str(geom.show())) else: geom.to_file(name) diff --git a/processing/pre/geom_translate.py b/processing/pre/geom_translate.py index 072c270ea..aa05166f7 100755 --- a/processing/pre/geom_translate.py +++ b/processing/pre/geom_translate.py @@ -1,10 +1,12 @@ #!/usr/bin/env python3 # -*- coding: UTF-8 no BOM -*- -import os,sys,math +import os +import sys import numpy as np -import damask from optparse import OptionParser +from io import StringIO +import damask scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptID = ' '.join([scriptName,damask.version]) @@ -30,98 +32,47 @@ parser.add_option('-s', '--substitute', dest = 'substitute', action = 'extend', metavar = '', help = 'substitutions of microstructure indices from,to,from,to,...') -parser.add_option('--float', - dest = 'float', - action = 'store_true', - help = 'use float input') parser.set_defaults(origin = (0.0,0.0,0.0), microstructure = 0, - substitute = [], - float = False, + substitute = [] ) (options, filenames) = parser.parse_args() -datatype = 'f' if options.float else 'i' - 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 ---------------------------------------------------------------------- +# --- 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) + + 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 + + for k, v in sub.items(): microstructure[geom.microstructure==k] = v # substitute microstructure indices -# --- interpret header --------------------------------------------------------------------------- + microstructure += options.microstructure # shift microstructure indices - 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) # read microstructure - -# --- do work ------------------------------------------------------------------------------------ - - newInfo = { - 'origin': np.zeros(3,'d'), - 'microstructures': 0, - } - - substituted = np.copy(microstructure) - for k, v in sub.items(): substituted[microstructure==k] = v # substitute microstructure indices - - substituted += options.microstructure # shift microstructure indices - - newInfo['origin'] = info['origin'] + options.origin - newInfo['microstructures'] = len(np.unique(substituted)) - -# --- report ------------------------------------------------------------------------------------- - - remarks = [] - 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 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=newInfo['origin']), - "homogenization\t{homog}".format(homog=info['homogenization']), - "microstructures\t{microstructures}".format(microstructures=newInfo['microstructures']), - ]) - table.head_write() - -# --- write microstructure information ----------------------------------------------------------- - - format = '%g' if options.float else '%{}i'.format(int(math.floor(math.log10(np.nanmax(substituted))+1))) - table.data = substituted.reshape((info['grid'][0],info['grid'][1]*info['grid'][2]),order='F').transpose() - table.data_writeArray(format,delimiter = ' ') - -# --- output finalization ------------------------------------------------------------------------ - - table.close() # close ASCII table + 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) + origin += np.array(origin) + geom.comments[i] = 'origin x {} y {} z {}'.format(*origin) + + geom.microstructure = microstructure + geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) + + damask.util.croak(geom) + if name is None: + sys.stdout.write(str(geom.show())) + else: + geom.to_file(name) diff --git a/processing/pre/geom_unpack.py b/processing/pre/geom_unpack.py index fb5b58198..40b6c0e64 100755 --- a/processing/pre/geom_unpack.py +++ b/processing/pre/geom_unpack.py @@ -3,9 +3,8 @@ import os import sys -import math -import numpy as np from optparse import OptionParser +from io import StringIO import damask scriptName = os.path.splitext(os.path.basename(__file__))[0] @@ -35,19 +34,18 @@ parser.set_defaults(oneD = False, 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.report(scriptName,name) - geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - damask.util.croak('\n'.join(geom.info())) - + damask.util.croak(geom) if name is None: - sys.stdout.write(str(geom)) + sys.stdout.write(str(geom.show())) else: geom.to_file(name) diff --git a/processing/pre/geom_vicinityOffset.py b/processing/pre/geom_vicinityOffset.py index e23d905f9..535650244 100755 --- a/processing/pre/geom_vicinityOffset.py +++ b/processing/pre/geom_vicinityOffset.py @@ -65,14 +65,13 @@ options.trigger = np.array(options.trigger, dtype=int) 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.report(scriptName,name) - microstructure = geom.microstructure if options.offset == 0: options.offset = microstructure.max() @@ -87,9 +86,8 @@ for name in filenames: geom.microstructure = microstructure geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) - damask.util.croak('\n'.join(geom.info())) - + damask.util.croak(geom) if name is None: - sys.stdout.write(str(geom)) + sys.stdout.write(str(geom.show())) else: geom.to_file(name) diff --git a/python/damask/geom.py b/python/damask/geom.py index def9e9f0c..ee924f8c0 100644 --- a/python/damask/geom.py +++ b/python/damask/geom.py @@ -6,6 +6,7 @@ class Geom(): """Geometry definition for grid solvers""" def __init__(self,size,microstructure,homogenization=1,comments=[]): + """New geometry definition from array of microstructures and size""" if len(size) != 3 or any(np.array(size)<=0): raise ValueError('invalid size') else: @@ -26,12 +27,13 @@ class Geom(): else: self.comments = [str(comment) for comment in comments] - def __repr__(self): - """Readable string""" - f=StringIO() - self.to_file(f) - f.seek(0) - return ''.join(f.readlines()) + 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()))) + \ + 'homogenization: {}\n'.format(self.get_homogenization()) + \ + '# microstructures: {}\n'.format(len(np.unique(self.microstructure))) + \ + 'max microstructures: {}\n'.format(np.max(self.microstructure)) def add_comment(self,comment): if not isinstance(comment,list): @@ -119,10 +121,8 @@ class Geom(): np.savetxt(fname, self.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T, header='\n'.join(header), fmt=format_string, comments='') - def info(self): - return ['grid a b c: {}'.format(' x '.join(map(str,self.get_grid()))), - 'size x y z: {}'.format(' x '.join(map(str,self.get_size()))), - 'homogenization: {}'.format(self.get_homogenization()), - '# microstructures: {}'.format(len(np.unique(self.microstructure))), - 'max microstructures: {}'.format(np.max(self.microstructure)), - ] + def show(self): + f=StringIO() + self.to_file(f) + f.seek(0) + return ''.join(f.readlines())