4 space indents are common practice

This commit is contained in:
Martin Diehl 2019-11-22 20:52:36 +01:00
parent fad679a9a5
commit c00af5c402
1 changed files with 362 additions and 364 deletions

View File

@ -10,380 +10,378 @@ from . import version
class Geom(): class Geom():
"""Geometry definition for grid solvers.""" """Geometry definition for grid solvers."""
def __init__(self,microstructure,size,origin=[0.0,0.0,0.0],homogenization=1,comments=[]): def __init__(self,microstructure,size,origin=[0.0,0.0,0.0],homogenization=1,comments=[]):
""" """
New geometry definition from array of microstructures and size. New geometry definition from array of microstructures and size.
Parameters Parameters
---------- ----------
microstructure : numpy.ndarray microstructure : numpy.ndarray
microstructure array (3D) microstructure array (3D)
size : list or numpy.ndarray size : list or numpy.ndarray
physical size of the microstructure in meter. physical size of the microstructure in meter.
origin : list or numpy.ndarray, optional origin : list or numpy.ndarray, optional
physical origin of the microstructure in meter. physical origin of the microstructure in meter.
homogenization : integer, optional homogenization : integer, optional
homogenization index. homogenization index.
comments : list of str, optional comments : list of str, optional
comments lines. comments lines.
""" """
self.__transforms__ = \ self.__transforms__ = \
self.set_microstructure(microstructure) self.set_microstructure(microstructure)
self.set_size(size) self.set_size(size)
self.set_origin(origin) self.set_origin(origin)
self.set_homogenization(homogenization) self.set_homogenization(homogenization)
self.set_comments(comments) self.set_comments(comments)
def __repr__(self): def __repr__(self):
"""Basic information on geometry definition.""" """Basic information on geometry definition."""
return util.srepr([ return util.srepr([
'grid a b c: {}'.format(' x '.join(map(str,self.get_grid ()))), 'grid a b c: {}'.format(' x '.join(map(str,self.get_grid ()))),
'size x y z: {}'.format(' x '.join(map(str,self.get_size ()))), 'size x y z: {}'.format(' x '.join(map(str,self.get_size ()))),
'origin x y z: {}'.format(' '.join(map(str,self.get_origin()))), 'origin x y z: {}'.format(' '.join(map(str,self.get_origin()))),
'homogenization: {}'.format(self.get_homogenization()), 'homogenization: {}'.format(self.get_homogenization()),
'# microstructures: {}'.format(len(np.unique(self.microstructure))), '# microstructures: {}'.format(len(np.unique(self.microstructure))),
'max microstructure: {}'.format(np.nanmax(self.microstructure)), 'max microstructure: {}'.format(np.nanmax(self.microstructure)),
]) ])
def update(self,microstructure=None,size=None,origin=None,rescale=False): def update(self,microstructure=None,size=None,origin=None,rescale=False):
""" """
Updates microstructure and size. Updates microstructure and size.
Parameters Parameters
---------- ----------
microstructure : numpy.ndarray, optional microstructure : numpy.ndarray, optional
microstructure array (3D). microstructure array (3D).
size : list or numpy.ndarray, optional size : list or numpy.ndarray, optional
physical size of the microstructure in meter. physical size of the microstructure in meter.
origin : list or numpy.ndarray, optional origin : list or numpy.ndarray, optional
physical origin of the microstructure in meter. physical origin of the microstructure in meter.
rescale : bool, optional rescale : bool, optional
ignore size parameter and rescale according to change of grid points. ignore size parameter and rescale according to change of grid points.
""" """
grid_old = self.get_grid() grid_old = self.get_grid()
size_old = self.get_size() size_old = self.get_size()
origin_old = self.get_origin() origin_old = self.get_origin()
unique_old = len(np.unique(self.microstructure)) unique_old = len(np.unique(self.microstructure))
max_old = np.nanmax(self.microstructure) max_old = np.nanmax(self.microstructure)
if size is not None and rescale: if size is not None and rescale:
raise ValueError('Either set size explicitly or rescale automatically') raise ValueError('Either set size explicitly or rescale automatically')
self.set_microstructure(microstructure) self.set_microstructure(microstructure)
self.set_origin(origin) self.set_origin(origin)
if size is not None: if size is not None:
self.set_size(size) self.set_size(size)
elif rescale: elif rescale:
self.set_size(self.get_grid()/grid_old*self.size) self.set_size(self.get_grid()/grid_old*self.size)
message = ['grid a b c: {}'.format(' x '.join(map(str,grid_old)))] message = ['grid a b c: {}'.format(' x '.join(map(str,grid_old)))]
if np.any(grid_old != self.get_grid()): if np.any(grid_old != self.get_grid()):
message[-1] = util.delete(message[-1]) message[-1] = util.delete(message[-1])
message.append(util.emph('grid a b c: {}'.format(' x '.join(map(str,self.get_grid()))))) message.append(util.emph('grid a b c: {}'.format(' x '.join(map(str,self.get_grid())))))
message.append('size x y z: {}'.format(' x '.join(map(str,size_old)))) message.append('size x y z: {}'.format(' x '.join(map(str,size_old))))
if np.any(size_old != self.get_size()): if np.any(size_old != self.get_size()):
message[-1] = util.delete(message[-1]) message[-1] = util.delete(message[-1])
message.append(util.emph('size x y z: {}'.format(' x '.join(map(str,self.get_size()))))) message.append(util.emph('size x y z: {}'.format(' x '.join(map(str,self.get_size())))))
message.append('origin x y z: {}'.format(' '.join(map(str,origin_old)))) message.append('origin x y z: {}'.format(' '.join(map(str,origin_old))))
if np.any(origin_old != self.get_origin()): if np.any(origin_old != self.get_origin()):
message[-1] = util.delete(message[-1]) message[-1] = util.delete(message[-1])
message.append(util.emph('origin x y z: {}'.format(' '.join(map(str,self.get_origin()))))) message.append(util.emph('origin x y z: {}'.format(' '.join(map(str,self.get_origin())))))
message.append('homogenization: {}'.format(self.get_homogenization())) message.append('homogenization: {}'.format(self.get_homogenization()))
message.append('# microstructures: {}'.format(unique_old)) message.append('# microstructures: {}'.format(unique_old))
if unique_old != len(np.unique(self.microstructure)): if unique_old != len(np.unique(self.microstructure)):
message[-1] = util.delete(message[-1]) message[-1] = util.delete(message[-1])
message.append(util.emph('# microstructures: {}'.format(len(np.unique(self.microstructure))))) message.append(util.emph('# microstructures: {}'.format(len(np.unique(self.microstructure)))))
message.append('max microstructure: {}'.format(max_old)) message.append('max microstructure: {}'.format(max_old))
if max_old != np.nanmax(self.microstructure): if max_old != np.nanmax(self.microstructure):
message[-1] = util.delete(message[-1]) message[-1] = util.delete(message[-1])
message.append(util.emph('max microstructure: {}'.format(np.nanmax(self.microstructure)))) message.append(util.emph('max microstructure: {}'.format(np.nanmax(self.microstructure))))
return util.return_message(message) return util.return_message(message)
def set_comments(self,comments): def set_comments(self,comments):
""" """
Replaces all existing comments. Replaces all existing comments.
Parameters Parameters
---------- ----------
comments : list of str comments : list of str
new comments. new comments.
""" """
self.comments = [] self.comments = []
self.add_comments(comments) self.add_comments(comments)
def add_comments(self,comments): def add_comments(self,comments):
""" """
Appends comments to existing comments. Appends comments to existing comments.
Parameters Parameters
---------- ----------
comments : list of str comments : list of str
new comments. new comments.
""" """
self.comments += [str(c) for c in comments] if isinstance(comments,list) else [str(comments)] self.comments += [str(c) for c in comments] if isinstance(comments,list) else [str(comments)]
def set_microstructure(self,microstructure): def set_microstructure(self,microstructure):
""" """
Replaces the existing microstructure representation. Replaces the existing microstructure representation.
Parameters Parameters
---------- ----------
microstructure : numpy.ndarray microstructure : numpy.ndarray
microstructure array (3D). microstructure array (3D).
""" """
if microstructure is not None: if microstructure is not None:
if len(microstructure.shape) != 3: if len(microstructure.shape) != 3:
raise ValueError('Invalid microstructure shape {}'.format(*microstructure.shape)) raise ValueError('Invalid microstructure shape {}'.format(*microstructure.shape))
elif microstructure.dtype not in np.sctypes['float'] + np.sctypes['int']: elif microstructure.dtype not in np.sctypes['float'] + np.sctypes['int']:
raise TypeError('Invalid data type {} for microstructure'.format(microstructure.dtype)) raise TypeError('Invalid data type {} for microstructure'.format(microstructure.dtype))
else: else:
self.microstructure = np.copy(microstructure) self.microstructure = np.copy(microstructure)
def set_size(self,size): def set_size(self,size):
""" """
Replaces the existing size information. Replaces the existing size information.
Parameters Parameters
---------- ----------
size : list or numpy.ndarray size : list or numpy.ndarray
physical size of the microstructure in meter. physical size of the microstructure in meter.
""" """
if size is None: if size is None:
grid = np.asarray(self.microstructure.shape) grid = np.asarray(self.microstructure.shape)
self.size = grid/np.max(grid) self.size = grid/np.max(grid)
else: else:
if len(size) != 3 or any(np.array(size)<=0): if len(size) != 3 or any(np.array(size)<=0):
raise ValueError('Invalid size {}'.format(*size)) raise ValueError('Invalid size {}'.format(*size))
else: else:
self.size = np.array(size) self.size = np.array(size)
def set_origin(self,origin): def set_origin(self,origin):
""" """
Replaces the existing origin information. Replaces the existing origin information.
Parameters Parameters
---------- ----------
origin : list or numpy.ndarray origin : list or numpy.ndarray
physical origin of the microstructure in meter physical origin of the microstructure in meter
""" """
if origin is not None: if origin is not None:
if len(origin) != 3: if len(origin) != 3:
raise ValueError('Invalid origin {}'.format(*origin)) raise ValueError('Invalid origin {}'.format(*origin))
else: else:
self.origin = np.array(origin) self.origin = np.array(origin)
def set_homogenization(self,homogenization): def set_homogenization(self,homogenization):
""" """
Replaces the existing homogenization index. Replaces the existing homogenization index.
Parameters Parameters
---------- ----------
homogenization : integer homogenization : integer
homogenization index homogenization index
""" """
if homogenization is not None: if homogenization is not None:
if not isinstance(homogenization,int) or homogenization < 1: if not isinstance(homogenization,int) or homogenization < 1:
raise TypeError('Invalid homogenization {}'.format(homogenization)) raise TypeError('Invalid homogenization {}'.format(homogenization))
else: else:
self.homogenization = homogenization self.homogenization = homogenization
def get_microstructure(self): def get_microstructure(self):
"""Return the microstructure representation.""" """Return the microstructure representation."""
return np.copy(self.microstructure) return np.copy(self.microstructure)
def get_size(self): def get_size(self):
"""Return the physical size in meter.""" """Return the physical size in meter."""
return np.copy(self.size) return np.copy(self.size)
def get_origin(self): def get_origin(self):
"""Return the origin in meter.""" """Return the origin in meter."""
return np.copy(self.origin) return np.copy(self.origin)
def get_grid(self): def get_grid(self):
"""Return the grid discretization.""" """Return the grid discretization."""
return np.array(self.microstructure.shape) return np.array(self.microstructure.shape)
def get_homogenization(self): def get_homogenization(self):
"""Return the homogenization index.""" """Return the homogenization index."""
return self.homogenization return self.homogenization
def get_comments(self): def get_comments(self):
"""Return the comments.""" """Return the comments."""
return self.comments[:] return self.comments[:]
def get_header(self): def get_header(self):
"""Return the full header (grid, size, origin, homogenization, comments).""" """Return the full header (grid, size, origin, homogenization, comments)."""
header = ['{} header'.format(len(self.comments)+4)] + self.comments header = ['{} header'.format(len(self.comments)+4)] + self.comments
header.append('grid a {} b {} c {}'.format(*self.get_grid())) header.append('grid a {} b {} c {}'.format(*self.get_grid()))
header.append('size x {} y {} z {}'.format(*self.get_size())) header.append('size x {} y {} z {}'.format(*self.get_size()))
header.append('origin x {} y {} z {}'.format(*self.get_origin())) header.append('origin x {} y {} z {}'.format(*self.get_origin()))
header.append('homogenization {}'.format(self.get_homogenization())) header.append('homogenization {}'.format(self.get_homogenization()))
return header return header
@classmethod @classmethod
def from_file(cls,fname): def from_file(cls,fname):
""" """
Reads a geom file. Reads a geom file.
Parameters Parameters
---------- ----------
fname : str or file handle fname : str or file handle
geometry file to read. geometry file to read.
""" """
with (open(fname) if isinstance(fname,str) else fname) as f: with (open(fname) if isinstance(fname,str) else fname) as f:
f.seek(0) f.seek(0)
header_length,keyword = f.readline().split()[:2] header_length,keyword = f.readline().split()[:2]
header_length = int(header_length) header_length = int(header_length)
content = f.readlines() content = f.readlines()
if not keyword.startswith('head') or header_length < 3: if not keyword.startswith('head') or header_length < 3:
raise TypeError('Header length information missing or invalid') raise TypeError('Header length information missing or invalid')
comments = [] comments = []
for i,line in enumerate(content[:header_length]): for i,line in enumerate(content[:header_length]):
items = line.lower().strip().split() items = line.lower().strip().split()
key = items[0] if len(items) > 0 else '' key = items[0] if len(items) > 0 else ''
if key == 'grid': if key == 'grid':
grid = np.array([ int(dict(zip(items[1::2],items[2::2]))[i]) for i in ['a','b','c']]) grid = np.array([ int(dict(zip(items[1::2],items[2::2]))[i]) for i in ['a','b','c']])
elif key == 'size': elif key == 'size':
size = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']]) size = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']])
elif key == 'origin': elif key == 'origin':
origin = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']]) origin = np.array([float(dict(zip(items[1::2],items[2::2]))[i]) for i in ['x','y','z']])
elif key == 'homogenization': elif key == 'homogenization':
homogenization = int(items[1]) homogenization = int(items[1])
else: else:
comments.append(line.strip()) comments.append(line.strip())
microstructure = np.empty(grid.prod()) # initialize as flat array microstructure = np.empty(grid.prod()) # initialize as flat array
i = 0 i = 0
for line in content[header_length:]: for line in content[header_length:]:
items = line.split() items = line.split()
if len(items) == 3: if len(items) == 3:
if items[1].lower() == 'of': if items[1].lower() == 'of':
items = np.ones(int(items[0]))*float(items[2]) items = np.ones(int(items[0]))*float(items[2])
elif items[1].lower() == 'to': elif items[1].lower() == 'to':
items = np.linspace(int(items[0]),int(items[2]), items = np.linspace(int(items[0]),int(items[2]),
abs(int(items[2])-int(items[0]))+1,dtype=float) abs(int(items[2])-int(items[0]))+1,dtype=float)
else: items = list(map(float,items)) else: items = list(map(float,items))
else: items = list(map(float,items)) else: items = list(map(float,items))
microstructure[i:i+len(items)] = items
microstructure[i:i+len(items)] = items i += len(items)
i += len(items)
if i != grid.prod():
if i != grid.prod(): raise TypeError('Invalid file: expected {} entries,found {}'.format(grid.prod(),i))
raise TypeError('Invalid file: expected {} entries,found {}'.format(grid.prod(),i))
microstructure = microstructure.reshape(grid,order='F')
microstructure = microstructure.reshape(grid,order='F') if not np.any(np.mod(microstructure.flatten(),1) != 0.0): # no float present
if not np.any(np.mod(microstructure.flatten(),1) != 0.0): # no float present microstructure = microstructure.astype('int')
microstructure = microstructure.astype('int')
return cls(microstructure.reshape(grid),size,origin,homogenization,comments)
return cls(microstructure.reshape(grid),size,origin,homogenization,comments)
def to_file(self,fname): def to_file(self,fname):
""" """
Writes a geom file. Writes a geom file.
Parameters Parameters
---------- ----------
fname : str or file handle fname : str or file handle
geometry file to write. geometry file to write.
""" """
header = self.get_header() header = self.get_header()
grid = self.get_grid() grid = self.get_grid()
format_string = '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(self.microstructure))))) if self.microstructure.dtype == int \ format_string = '%{}i'.format(1+int(np.floor(np.log10(np.nanmax(self.microstructure))))) if self.microstructure.dtype == int \
else '%g' else '%g'
np.savetxt(fname, np.savetxt(fname,
self.microstructure.reshape([grid[0],np.prod(grid[1:])],order='F').T, 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 to_vtk(self,fname=None):
"""
def to_vtk(self,fname=None): Generates vtk file.
"""
Generates vtk file. Parameters
----------
Parameters fname : str, optional
---------- vtk file to write. If no file is given, a string is returned.
fname : str, optional
vtk file to write. If no file is given, a string is returned. """
grid = self.get_grid() + np.ones(3,dtype=int)
""" size = self.get_size()
grid = self.get_grid() + np.ones(3,dtype=int) origin = self.get_origin()
size = self.get_size()
origin = self.get_origin() coords = [
np.linspace(0,size[0],grid[0]) + origin[0],
coords = [ np.linspace(0,size[1],grid[1]) + origin[1],
np.linspace(0,size[0],grid[0]) + origin[0], np.linspace(0,size[2],grid[2]) + origin[2]
np.linspace(0,size[1],grid[1]) + origin[1], ]
np.linspace(0,size[2],grid[2]) + origin[2]
] rGrid = vtk.vtkRectilinearGrid()
coordArray = [vtk.vtkDoubleArray(),vtk.vtkDoubleArray(),vtk.vtkDoubleArray()]
rGrid = vtk.vtkRectilinearGrid()
coordArray = [vtk.vtkDoubleArray(),vtk.vtkDoubleArray(),vtk.vtkDoubleArray()] rGrid.SetDimensions(*grid)
for d,coord in enumerate(coords):
rGrid.SetDimensions(*grid) for c in coord:
for d,coord in enumerate(coords): coordArray[d].InsertNextValue(c)
for c in coord:
coordArray[d].InsertNextValue(c) rGrid.SetXCoordinates(coordArray[0])
rGrid.SetYCoordinates(coordArray[1])
rGrid.SetXCoordinates(coordArray[0]) rGrid.SetZCoordinates(coordArray[2])
rGrid.SetYCoordinates(coordArray[1])
rGrid.SetZCoordinates(coordArray[2]) ms = numpy_support.numpy_to_vtk(num_array=self.microstructure.flatten(order='F'),
array_type=vtk.VTK_INT if self.microstructure.dtype == int else vtk.VTK_FLOAT)
ms = numpy_support.numpy_to_vtk(num_array=self.microstructure.flatten(order='F'), ms.SetName('microstructure')
array_type=vtk.VTK_INT if self.microstructure.dtype == int else vtk.VTK_FLOAT) rGrid.GetCellData().AddArray(ms)
ms.SetName('microstructure')
rGrid.GetCellData().AddArray(ms)
if fname is None:
writer = vtk.vtkDataSetWriter()
if fname is None: writer.SetHeader('damask.Geom '+version)
writer = vtk.vtkDataSetWriter() writer.WriteToOutputStringOn()
writer.SetHeader('damask.Geom '+version) else:
writer.WriteToOutputStringOn() writer = vtk.vtkXMLRectilinearGridWriter()
else: writer.SetCompressorTypeToZLib()
writer = vtk.vtkXMLRectilinearGridWriter() writer.SetDataModeToBinary()
writer.SetCompressorTypeToZLib()
writer.SetDataModeToBinary() ext = os.path.splitext(fname)[1]
if ext == '':
ext = os.path.splitext(fname)[1] name = fname + '.' + writer.GetDefaultFileExtension()
if ext == '': elif ext == writer.GetDefaultFileExtension():
name = fname + '.' + writer.GetDefaultFileExtension() name = fname
elif ext == writer.GetDefaultFileExtension(): else:
name = fname raise ValueError("unknown extension {}".format(ext))
else: writer.SetFileName(name)
raise ValueError("unknown extension {}".format(ext))
writer.SetFileName(name) writer.SetInputData(rGrid)
writer.Write()
writer.SetInputData(rGrid)
writer.Write() if fname is None: return writer.GetOutputString()
if fname is None: return writer.GetOutputString()
def show(self):
"""Show raw content (as in file)."""
def show(self): f=StringIO()
"""Show raw content (as in file).""" self.to_file(f)
f=StringIO() f.seek(0)
self.to_file(f) return ''.join(f.readlines())
f.seek(0)
return ''.join(f.readlines())