same style

This commit is contained in:
Martin Diehl 2019-05-25 10:14:53 +02:00
parent 17eb0d1b20
commit 875643c363
8 changed files with 82 additions and 181 deletions

View File

@ -73,7 +73,6 @@ parser.set_defaults(type = minimal_surfaces[0],
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
X = options.periods*2.0*math.pi*(np.arange(options.grid[0])+0.5)/options.grid[0] 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, geom=damask.Geom(options.size,microstructure,options.homogenization,
comments=[scriptID + ' ' + ' '.join(sys.argv[1:])]) comments=[scriptID + ' ' + ' '.join(sys.argv[1:])])
damask.util.croak('\n'.join(geom.info())) damask.util.croak(geom)
if name is None: if name is None:
sys.stdout.write(str(geom)) sys.stdout.write(str(geom.show()))
else: else:
geom.to_file(name) geom.to_file(name)

View File

@ -4,8 +4,9 @@
import os import os
import sys import sys
import numpy as np import numpy as np
import damask
from optparse import OptionParser from optparse import OptionParser
from io import StringIO
import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptName = os.path.splitext(os.path.basename(__file__))[0]
scriptID = ' '.join([scriptName,damask.version]) scriptID = ' '.join([scriptName,damask.version])

View File

@ -1,10 +1,12 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,sys,math import os
import sys
import numpy as np import numpy as np
import damask
from optparse import OptionParser from optparse import OptionParser
from io import StringIO
import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptName = os.path.splitext(os.path.basename(__file__))[0]
scriptID = ' '.join([scriptName,damask.version]) scriptID = ' '.join([scriptName,damask.version])
@ -25,36 +27,14 @@ renumber sorted microstructure indices to 1,...,N.
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
try: table = damask.ASCIItable(name = name,
buffered = False,
labeled = False)
except: continue
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
# --- interpret header --------------------------------------------------------------------------- if name is None:
virt_file = StringIO(''.join(sys.stdin.read()))
table.head_read() geom = damask.Geom.from_file(virt_file)
info,extra_header = table.head_getGeom() else:
damask.util.report_geom(info) geom = damask.Geom.from_file(name)
microstructure = geom.microstructure
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,
}
grainIDs = np.unique(microstructure) grainIDs = np.unique(microstructure)
renumbered = np.copy(microstructure) renumbered = np.copy(microstructure)
@ -62,35 +42,11 @@ for name in filenames:
for i, oldID in enumerate(grainIDs): for i, oldID in enumerate(grainIDs):
renumbered = np.where(microstructure == oldID, i+1, renumbered) renumbered = np.where(microstructure == oldID, i+1, renumbered)
newInfo['microstructures'] = len(grainIDs) geom.microstructure = renumbered
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
# --- report -------------------------------------------------------------------------------------
damask.util.croak(geom)
remarks = [] if name is None:
if ( newInfo['microstructures'] != info['microstructures']): sys.stdout.write(str(geom.show()))
remarks.append('--> microstructures: %i'%newInfo['microstructures']) else:
if remarks != []: damask.util.croak(remarks) geom.to_file(name)
# --- 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

View File

@ -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: if options.quaternion is not None:
eulers = damask.Rotation.fromQuaternion(np.array(options.quaternion)).asEulers(degrees=True) eulers = damask.Rotation.fromQuaternion(np.array(options.quaternion)).asEulers(degrees=True)
if options.rotation is not None: 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: if options.matrix is not None:
eulers = damask.Rotation.fromMatrix(np.array(options.Matrix)).asEulers(degrees=True) eulers = damask.Rotation.fromMatrix(np.array(options.Matrix)).asEulers(degrees=True)
if options.eulers is not None: 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 ------------------------------------------------------------------------- # --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
damask.util.report(scriptName,name)
if name is None: if name is None:
virt_file = StringIO(''.join(sys.stdin.read())) virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file) geom = damask.Geom.from_file(virt_file)
else: else:
geom = damask.Geom.from_file(name) geom = damask.Geom.from_file(name)
damask.util.report(scriptName,name)
microstructure = geom.microstructure microstructure = geom.microstructure
spacing = geom.get_size()/geom.get_grid() spacing = geom.get_size()/geom.get_grid()
newGrainID = options.fill if options.fill is not None else np.nanmax(microstructure)+1 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.set_size(microstructure.shape*spacing)
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak('\n'.join(geom.info())) damask.util.croak(geom)
if name is None: if name is None:
sys.stdout.write(str(geom)) sys.stdout.write(str(geom.show()))
else: else:
geom.to_file(name) geom.to_file(name)

View File

@ -1,10 +1,12 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: UTF-8 no BOM -*- # -*- coding: UTF-8 no BOM -*-
import os,sys,math import os
import sys
import numpy as np import numpy as np
import damask
from optparse import OptionParser from optparse import OptionParser
from io import StringIO
import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptName = os.path.splitext(os.path.basename(__file__))[0]
scriptID = ' '.join([scriptName,damask.version]) scriptID = ' '.join([scriptName,damask.version])
@ -30,98 +32,47 @@ parser.add_option('-s', '--substitute',
dest = 'substitute', dest = 'substitute',
action = 'extend', metavar = '<string LIST>', action = 'extend', metavar = '<string LIST>',
help = 'substitutions of microstructure indices from,to,from,to,...') 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), parser.set_defaults(origin = (0.0,0.0,0.0),
microstructure = 0, microstructure = 0,
substitute = [], substitute = []
float = False,
) )
(options, filenames) = parser.parse_args() (options, filenames) = parser.parse_args()
datatype = 'f' if options.float else 'i'
sub = {} sub = {}
for i in range(len(options.substitute)//2): # split substitution list into "from" -> "to" 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[int(options.substitute[i*2])] = int(options.substitute[i*2+1])
# --- loop over input files ---------------------------------------------------------------------- # --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
try: table = damask.ASCIItable(name = name,
buffered = False,
labeled = False)
except: continue
damask.util.report(scriptName,name) 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() for i,line in enumerate(geom.comments):
info,extra_header = table.head_getGeom() if line.lower().strip().startswith('origin'):
damask.util.report_geom(info) origin= np.array([float(line.split()[j]) for j in [2,4,6]]) # assume correct order (x,y,z)
origin += np.array(origin)
errors = [] geom.comments[i] = 'origin x {} y {} z {}'.format(*origin)
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.') geom.microstructure = microstructure
if errors != []: geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak(errors)
table.close(dismiss = True) damask.util.croak(geom)
continue if name is None:
sys.stdout.write(str(geom.show()))
# --- read data ---------------------------------------------------------------------------------- else:
geom.to_file(name)
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

View File

@ -3,9 +3,8 @@
import os import os
import sys import sys
import math
import numpy as np
from optparse import OptionParser from optparse import OptionParser
from io import StringIO
import damask import damask
scriptName = os.path.splitext(os.path.basename(__file__))[0] scriptName = os.path.splitext(os.path.basename(__file__))[0]
@ -35,19 +34,18 @@ parser.set_defaults(oneD = False,
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
damask.util.report(scriptName,name)
if name is None: if name is None:
virt_file = StringIO(''.join(sys.stdin.read())) virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file) geom = damask.Geom.from_file(virt_file)
else: else:
geom = damask.Geom.from_file(name) geom = damask.Geom.from_file(name)
damask.util.report(scriptName,name)
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak('\n'.join(geom.info())) damask.util.croak(geom)
if name is None: if name is None:
sys.stdout.write(str(geom)) sys.stdout.write(str(geom.show()))
else: else:
geom.to_file(name) geom.to_file(name)

View File

@ -65,14 +65,13 @@ options.trigger = np.array(options.trigger, dtype=int)
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
damask.util.report(scriptName,name)
if name is None: if name is None:
virt_file = StringIO(''.join(sys.stdin.read())) virt_file = StringIO(''.join(sys.stdin.read()))
geom = damask.Geom.from_file(virt_file) geom = damask.Geom.from_file(virt_file)
else: else:
geom = damask.Geom.from_file(name) geom = damask.Geom.from_file(name)
damask.util.report(scriptName,name)
microstructure = geom.microstructure microstructure = geom.microstructure
if options.offset == 0: options.offset = microstructure.max() if options.offset == 0: options.offset = microstructure.max()
@ -87,9 +86,8 @@ for name in filenames:
geom.microstructure = microstructure geom.microstructure = microstructure
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:])) geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak('\n'.join(geom.info())) damask.util.croak(geom)
if name is None: if name is None:
sys.stdout.write(str(geom)) sys.stdout.write(str(geom.show()))
else: else:
geom.to_file(name) geom.to_file(name)

View File

@ -6,6 +6,7 @@ class Geom():
"""Geometry definition for grid solvers""" """Geometry definition for grid solvers"""
def __init__(self,size,microstructure,homogenization=1,comments=[]): 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): if len(size) != 3 or any(np.array(size)<=0):
raise ValueError('invalid size') raise ValueError('invalid size')
else: else:
@ -26,12 +27,13 @@ class Geom():
else: else:
self.comments = [str(comment) for comment in comments] self.comments = [str(comment) for comment in comments]
def __repr__(self): def __repr__(self):
"""Readable string""" """Basic information on geometry definition"""
f=StringIO() return 'grid a b c: {}\n'.format(' x '.join(map(str,self.get_grid()))) + \
self.to_file(f) 'size x y z: {}\n'.format(' x '.join(map(str,self.get_size()))) + \
f.seek(0) 'homogenization: {}\n'.format(self.get_homogenization()) + \
return ''.join(f.readlines()) '# microstructures: {}\n'.format(len(np.unique(self.microstructure))) + \
'max microstructures: {}\n'.format(np.max(self.microstructure))
def add_comment(self,comment): def add_comment(self,comment):
if not isinstance(comment,list): 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, np.savetxt(fname, self.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T,
header='\n'.join(header), fmt=format_string, comments='') header='\n'.join(header), fmt=format_string, comments='')
def info(self): def show(self):
return ['grid a b c: {}'.format(' x '.join(map(str,self.get_grid()))), f=StringIO()
'size x y z: {}'.format(' x '.join(map(str,self.get_size()))), self.to_file(f)
'homogenization: {}'.format(self.get_homogenization()), f.seek(0)
'# microstructures: {}'.format(len(np.unique(self.microstructure))), return ''.join(f.readlines())
'max microstructures: {}'.format(np.max(self.microstructure)),
]