self-reporting functionality for updating

This commit is contained in:
Martin Diehl 2019-05-26 17:48:59 +02:00
parent 34f7bbe2a0
commit feb2340935
3 changed files with 67 additions and 23 deletions

View File

@ -1,22 +1,25 @@
#!/usr/bin/env python3
# -*- coding: UTF-8 no BOM -*-
import os
import sys
from io import StringIO
from optparse import OptionParser
from scipy import ndimage
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 = """
Scales a geometry description independently in x, y, and z direction in terms of grid and/or size.
Scales independently in x, y, and z direction in terms of grid and/or size.
Either absolute values or relative factors (like "0.25x") can be used.
""", version = scriptID)
@ -24,15 +27,14 @@ Either absolute values or relative factors (like "0.25x") can be used.
parser.add_option('-g', '--grid',
dest = 'grid',
type = 'string', nargs = 3, metavar = 'string string string',
help = 'a,b,c grid of hexahedral box [unchanged]')
help = 'a,b,c grid of hexahedral box')
parser.add_option('-s', '--size',
dest = 'size',
type = 'string', nargs = 3, metavar = 'string string string',
help = 'x,y,z size of hexahedral box [unchanged]')
help = 'x,y,z size of hexahedral box')
(options, filenames) = parser.parse_args()
# --- loop over input files -------------------------------------------------------------------------
if filenames == []: filenames = [None]
@ -44,28 +46,27 @@ 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()
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().startswith('x') \
scale[i] = scale[i]*float(g.lower().replace('x','')) if g.lower().endswith('x') \
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().startswith('x') \
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,
order=0, mode='nearest', prefilter=False)
geom.microstructure = microstructure
geom.set_size(size)
damask.util.croak(geom.update(microstructure,size))
geom.add_comment(scriptID + ' ' + ' '.join(sys.argv[1:]))
damask.util.croak(geom)
if name is None:
sys.stdout.write(str(geom.show()))
else:

View File

@ -7,12 +7,8 @@ import numpy as np
class Geom():
"""Geometry definition for grid solvers"""
def __init__(self,size,microstructure,homogenization=1,comments=[]):
def __init__(self,microstructure,size,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 {}'.format(*size))
else:
self.size = np.array(size)
if len(microstructure.shape) != 3:
raise ValueError('Invalid microstructure shape {}'.format(*microstructure.shape))
@ -20,7 +16,12 @@ class Geom():
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:
@ -34,11 +35,52 @@ class Geom():
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()) + \
'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.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
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 = ''
if np.any(grid_old != self.get_grid()):
message += 'grid a b c: {}\n'.format(' x '.join(map(str,self.get_grid())))
if np.any(size_old != self.get_size()):
message += 'size x y z: {}\n'.format(' x '.join(map(str,self.size)))
if unique_old != len(np.unique(self.microstructure)):
message += '# microstructures: {}\n'.format(len(np.unique(self.microstructure)))
if max_old != np.max(self.microstructure):
message += 'max microstructures: {}\n'.format(np.max(self.microstructure))
if message != '': return message
def add_comment(self,comment):
if not isinstance(comment,list):
self.comments += [str(comment)]
@ -124,7 +166,7 @@ class Geom():
else:
microstructure = microstructure.astype('int')
return cls(size,microstructure.reshape(grid),homogenization,comments)
return cls(microstructure.reshape(grid),size,homogenization,comments)
def to_file(self,fname):
"""Saves to file"""
@ -132,7 +174,7 @@ class Geom():
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.get_size()))
header.append('size x {} y {} z {}'.format(*self.size))
header.append('homogenization {}'.format(self.get_homogenization()))
if self.microstructure.dtype == 'int':

View File

@ -44,7 +44,8 @@ def srepr(arg,glue = '\n'):
# -----------------------------
def croak(what, newline = True):
"""Writes formated to stderr"""
sys.stderr.write(srepr(what,glue = '\n') + ('\n' if newline else ''))
if what is not None:
sys.stderr.write(srepr(what,glue = '\n') + ('\n' if newline else ''))
sys.stderr.flush()
# -----------------------------