use new class

This commit is contained in:
Martin Diehl 2019-05-24 22:31:34 +02:00
parent f20c8fcffd
commit 420abfa162
3 changed files with 48 additions and 129 deletions

View File

@ -1,7 +1,9 @@
#!/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 math
import numpy as np import numpy as np
from optparse import OptionParser from optparse import OptionParser
import damask import damask
@ -71,60 +73,25 @@ parser.set_defaults(type = minimal_surfaces[0],
if filenames == []: filenames = [None] if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
try:
table = damask.ASCIItable(outname = name,
buffered = False, labeled = False)
except: continue
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
# ------------------------------------------ make grid -------------------------------------
info = {
'grid': np.array(options.grid),
'size': np.array(options.size),
'origin': np.zeros(3,'d'),
'microstructures': max(options.microstructure),
'homogenization': options.homogenization
}
#--- report ---------------------------------------------------------------------------------------
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
#--- write header ---------------------------------------------------------------------------------
table.labels_clear()
table.info_clear()
table.info_append([
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=info['microstructures']),
])
table.head_write()
#--- write data -----------------------------------------------------------------------------------
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]
Y = options.periods*2.0*math.pi*(np.arange(options.grid[1])+0.5)/options.grid[1] Y = options.periods*2.0*math.pi*(np.arange(options.grid[1])+0.5)/options.grid[1]
Z = options.periods*2.0*math.pi*(np.arange(options.grid[2])+0.5)/options.grid[2] Z = options.periods*2.0*math.pi*(np.arange(options.grid[2])+0.5)/options.grid[2]
microstructure = np.empty(options.grid,dtype='int')
for z in range(options.grid[2]): for z in range(options.grid[2]):
for y in range(options.grid[1]): for y in range(options.grid[1]):
table.data_clear()
for x in range(options.grid[0]): for x in range(options.grid[0]):
table.data_append(options.microstructure[options.threshold < surface[options.type](X[x],Y[y],Z[z])]) microstructure[x,y,z]=options.microstructure[options.threshold < surface[options.type](X[x],Y[y],Z[z])]
table.data_write()
table.close() geom=damask.Geom(options.size,microstructure,options.homogenization,
comments=[scriptID + ' ' + ' '.join(sys.argv[1:])])
damask.util.croak('\n'.join(geom.info()))
if name is None:
sys.stdout.write(str(geom))
else:
geom.to_file(name)

View File

@ -1,9 +1,11 @@
#!/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 import damask
from io import StringIO
from scipy import ndimage from scipy import ndimage
from optparse import OptionParser from optparse import OptionParser
@ -42,15 +44,9 @@ parser.add_option('-q', '--quaternion',
parser.add_option('-f', '--fill', parser.add_option('-f', '--fill',
dest = 'fill', dest = 'fill',
type = 'int', metavar = 'int', type = 'int', metavar = 'int',
help = 'background grain index. "0" selects maximum microstructure index + 1 [%default]') help = 'background grain index, defaults to max + 1')
parser.add_option('--float',
dest = 'float',
action = 'store_true',
help = 'use float input')
parser.set_defaults(degrees = False, parser.set_defaults(degrees = False,
fill = 0,
float = False,
) )
(options, filenames) = parser.parse_args() (options, filenames) = parser.parse_args()
@ -67,82 +63,38 @@ if options.matrix is not None:
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=True).asEulers(degrees=True)
datatype = 'f' if options.float else 'i'
# --- 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: if name is None:
table = damask.ASCIItable(name = name, virt_file = StringIO(''.join(sys.stdin.read()))
buffered = False, geom = damask.Geom.from_file(virt_file)
labeled = False) else:
except: continue try: # really needed? Why not simply fail if file does not exists etc.
geom = damask.Geom.from_file(name)
except: continue
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
# --- interpret header ---------------------------------------------------------------------------- microstructure = geom.microstructure
spacing = geom.get_size()/geom.get_grid()
table.head_read() newGrainID = options.fill if options.fill is not None else np.nanmax(microstructure)+1
info,extra_header = table.head_getGeom() microstructure = ndimage.rotate(microstructure,eulers[2],(0,1),order=0,
damask.util.report_geom(info) prefilter=False,output=microstructure.dtype,cval=newGrainID) # rotation around Z
microstructure = ndimage.rotate(microstructure,eulers[1],(1,2),order=0,
prefilter=False,output=microstructure.dtype,cval=newGrainID) # rotation around X
microstructure = ndimage.rotate(microstructure,eulers[0],(0,1),order=0,
prefilter=False,output=microstructure.dtype,cval=newGrainID) # rotation around Z
errors = [] geom.microstructure = microstructure
if np.any(info['grid'] < 1): errors.append('invalid grid a b c.') geom.set_size(microstructure.shape*spacing)
if np.any(info['size'] <= 0.0): errors.append('invalid size x y z.') geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
if errors != []:
damask.util.croak(errors)
table.close(dismiss = True)
continue
# --- read data ------------------------------------------------------------------------------------ damask.util.croak('\n'.join(geom.info()))
microstructure = table.microstructure_read(info['grid'],datatype).reshape(info['grid'],order='F') # read microstructure if name is None:
sys.stdout.write(str(geom))
newGrainID = options.fill if options.fill != 0 else np.nanmax(microstructure)+1 else:
microstructure = ndimage.rotate(microstructure,eulers[2],(0,1),order=0,prefilter=False,output=int,cval=newGrainID) # rotation around Z geom.to_file(name)
microstructure = ndimage.rotate(microstructure,eulers[1],(1,2),order=0,prefilter=False,output=int,cval=newGrainID) # rotation around X
microstructure = ndimage.rotate(microstructure,eulers[0],(0,1),order=0,prefilter=False,output=int,cval=newGrainID) # rotation around Z
# --- do work ------------------------------------------------------------------------------------
newInfo = {
'size': microstructure.shape*info['size']/info['grid'],
'grid': microstructure.shape,
'microstructures': len(np.unique(microstructure)),
}
# --- report ---------------------------------------------------------------------------------------
remarks = []
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 ( 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=newInfo['grid']),
"size\tx {size[0]}\ty {size[1]}\tz {size[2]}".format(size=newInfo['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 = '%g' if options.float else '%{}i'.format(int(math.floor(math.log10(np.nanmax(microstructure))+1)))
table.data = microstructure.reshape((newInfo['grid'][0],np.prod(newInfo['grid'][1:])),order='F').transpose()
table.data_writeArray(format,delimiter=' ')
# --- output finalization --------------------------------------------------------------------------
table.close() # close ASCII table

View File

@ -4,10 +4,9 @@ from io import StringIO
import io import io
class Geom(): class Geom():
"""Geometry definition for grid solvers"""
def __init__(self,size,microstructure,homogenization=1,comments=[]): def __init__(self,size,microstructure,homogenization=1,comments=[]):
"""Geometry definition for grid solvers"""
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:
@ -29,6 +28,7 @@ class Geom():
self.comments = [str(comment) for comment in comments] self.comments = [str(comment) for comment in comments]
def __repr__(self): def __repr__(self):
"""Readable string"""
f=StringIO() f=StringIO()
self.to_file(f) self.to_file(f)
f.seek(0) f.seek(0)