removed Geom.get_X() methods in favor of direct property access

This commit is contained in:
Philip Eisenlohr 2020-09-21 11:13:53 -04:00
parent ca2f3f9493
commit 188905766f
4 changed files with 60 additions and 89 deletions

View File

@ -42,7 +42,7 @@ def output(cmds,locals,dest):
else: else:
outFile(str(cmd),locals,dest) outFile(str(cmd),locals,dest)
#------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------
def init(): def init():
return [ return [
@ -114,7 +114,7 @@ def material():
"*add_geometry_elements", "*add_geometry_elements",
"all_existing", "all_existing",
] ]
#------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------
def geometry(): def geometry():
@ -127,14 +127,14 @@ def geometry():
"*element_type 7", "*element_type 7",
"all_existing", "all_existing",
] ]
#------------------------------------------------------------------------------------------------- #-------------------------------------------------------------------------------------------------
def initial_conditions(microstructures): def initial_conditions(microstructures):
elements = [] elements = []
element = 0 element = 0
for id in microstructures: for id in microstructures:
element += 1 element += 1
if len(elements) < id: if len(elements) < id:
for i in range(id-len(elements)): for i in range(id-len(elements)):
elements.append([]) elements.append([])
@ -195,9 +195,9 @@ if filenames == []: filenames = [None]
for name in filenames: for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure().flatten(order='F') microstructure = geom.microstructure.flatten(order='F')
cmds = [\ cmds = [\
init(), init(),
@ -210,7 +210,7 @@ for name in filenames:
'*redraw', '*redraw',
'*draw_automatic', '*draw_automatic',
] ]
outputLocals = {} outputLocals = {}
if options.port: if options.port:
py_mentat.py_connect('',options.port) py_mentat.py_connect('',options.port)

View File

@ -47,7 +47,7 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name) geom = damask.Geom.from_file(StringIO(''.join(sys.stdin.read())) if name is None else name)
microstructure = geom.get_microstructure().reshape((-1,1),order='F') microstructure = geom.microstructure.reshape((-1,1),order='F')
mask = np.logical_and(np.in1d(microstructure,options.whitelist,invert=False) if options.whitelist else \ mask = np.logical_and(np.in1d(microstructure,options.whitelist,invert=False) if options.whitelist else \
np.full(geom.grid.prod(),True,dtype=bool), np.full(geom.grid.prod(),True,dtype=bool),

View File

@ -45,9 +45,9 @@ class Geom:
def __repr__(self): def __repr__(self):
"""Basic information on geometry definition.""" """Basic information on geometry definition."""
return util.srepr([ return util.srepr([
f'grid a b c: {util.srepr(self.get_grid ()," x ")}', f'grid a b c: {util.srepr(self.grid, " x ")}',
f'size x y z: {util.srepr(self.get_size ()," x ")}', f'size x y z: {util.srepr(self.size, " x ")}',
f'origin x y z: {util.srepr(self.get_origin()," ")}', f'origin x y z: {util.srepr(self.origin," ")}',
f'# materialpoints: {self.N_microstructure}', f'# materialpoints: {self.N_microstructure}',
f'max materialpoint: {np.nanmax(self.microstructure)}', f'max materialpoint: {np.nanmax(self.microstructure)}',
]) ])
@ -84,7 +84,7 @@ class Geom:
if size is not None and autosize: if size is not None and autosize:
raise ValueError('Auto-sizing conflicts with explicit size parameter.') raise ValueError('Auto-sizing conflicts with explicit size parameter.')
grid_old = self.get_grid() grid_old = self.grid
dup = self.set_microstructure(microstructure)\ dup = self.set_microstructure(microstructure)\
.set_origin(origin) .set_origin(origin)
@ -94,7 +94,7 @@ class Geom:
if size is not None: if size is not None:
dup.set_size(size,inplace=True) dup.set_size(size,inplace=True)
elif autosize: elif autosize:
dup.set_size(dup.get_grid()/grid_old*self.get_size(),inplace=True) dup.set_size(dup.grid/grid_old*self.size,inplace=True)
return dup return dup
@ -110,17 +110,17 @@ class Geom:
""" """
message = [] message = []
if np.any(other.get_grid() != self.get_grid()): if np.any(other.grid != self.grid):
message.append(util.delete(f'grid a b c: {util.srepr(other.get_grid()," x ")}')) message.append(util.delete(f'grid a b c: {util.srepr(other.grid," x ")}'))
message.append(util.emph( f'grid a b c: {util.srepr( self.get_grid()," x ")}')) message.append(util.emph( f'grid a b c: {util.srepr( self.grid," x ")}'))
if np.any(other.get_size() != self.get_size()): if np.any(other.size != self.size):
message.append(util.delete(f'size x y z: {util.srepr(other.get_size()," x ")}')) message.append(util.delete(f'size x y z: {util.srepr(other.size," x ")}'))
message.append(util.emph( f'size x y z: {util.srepr( self.get_size()," x ")}')) message.append(util.emph( f'size x y z: {util.srepr( self.size," x ")}'))
if np.any(other.get_origin() != self.get_origin()): if np.any(other.origin != self.origin):
message.append(util.delete(f'origin x y z: {util.srepr(other.get_origin()," ")}')) message.append(util.delete(f'origin x y z: {util.srepr(other.origin," ")}'))
message.append(util.emph( f'origin x y z: {util.srepr( self.get_origin()," ")}')) message.append(util.emph( f'origin x y z: {util.srepr( self.origin," ")}'))
if other.N_microstructure != self.N_microstructure: if other.N_microstructure != self.N_microstructure:
message.append(util.delete(f'# materialpoints: {other.N_microstructure}')) message.append(util.delete(f'# materialpoints: {other.N_microstructure}'))
@ -256,7 +256,7 @@ class Geom:
@property @property
def grid(self): def grid(self):
return self.get_grid() return np.asarray(self.microstructure.shape)
@property @property
@ -264,36 +264,6 @@ class Geom:
return np.unique(self.microstructure).size return np.unique(self.microstructure).size
def get_microstructure(self):
"""Return the microstructure representation."""
return np.copy(self.microstructure)
def get_size(self):
"""Return the physical size in meter."""
return np.copy(self.size)
def get_origin(self):
"""Return the origin in meter."""
return np.copy(self.origin)
def get_grid(self):
"""Return the grid discretization."""
return np.asarray(self.microstructure.shape)
def get_homogenization(self):
"""Return the homogenization index."""
return self.homogenization
def get_comments(self):
"""Return the comments."""
return self.comments[:]
@staticmethod @staticmethod
def from_file(fname): def from_file(fname):
""" """
@ -488,13 +458,14 @@ class Geom:
Compress geometry with 'x of y' and 'a to b'. Compress geometry with 'x of y' and 'a to b'.
""" """
header = [f'{len(geom.comments)+4} header'] + geom.comments header = [f'{len(geom.comments)+4} header'] + geom.comments \
header.append('grid a {} b {} c {}'.format(*geom.get_grid())) +[ 'grid a {} b {} c {}'.format(*geom.grid),
header.append('size x {} y {} z {}'.format(*geom.get_size())) 'size x {} y {} z {}'.format(*geom.size),
header.append('origin x {} y {} z {}'.format(*geom.get_origin())) 'origin x {} y {} z {}'.format(*geom.origin),
header.append(f'homogenization {geom.get_homogenization()}') f'homogenization {geom.homogenization}',
]
grid = geom.get_grid() grid = geom.grid
if pack is None: if pack is None:
plain = grid.prod()/geom.N_microstructure < 250 plain = grid.prod()/geom.N_microstructure < 250
@ -634,7 +605,7 @@ class Geom:
ms = np.ma.MaskedArray(fill_,np.logical_not(mask) if inverse else mask) ms = np.ma.MaskedArray(fill_,np.logical_not(mask) if inverse else mask)
return self.duplicate(ms, return self.duplicate(ms,
comments=self.get_comments()+[util.execution_stamp('Geom','add_primitive')], comments=self.comments+[util.execution_stamp('Geom','add_primitive')],
) )
@ -656,7 +627,7 @@ class Geom:
raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.') raise ValueError(f'Invalid direction {set(directions).difference(valid)} specified.')
limits = [None,None] if reflect else [-2,0] limits = [None,None] if reflect else [-2,0]
ms = self.get_microstructure() ms = self.microstructure.copy()
if 'z' in directions: if 'z' in directions:
ms = np.concatenate([ms,ms[:,:,limits[0]:limits[1]:-1]],2) ms = np.concatenate([ms,ms[:,:,limits[0]:limits[1]:-1]],2)
@ -666,7 +637,7 @@ class Geom:
ms = np.concatenate([ms,ms[limits[0]:limits[1]:-1,:,:]],0) ms = np.concatenate([ms,ms[limits[0]:limits[1]:-1,:,:]],0)
return self.duplicate(ms, return self.duplicate(ms,
comments=self.get_comments()+[util.execution_stamp('Geom','mirror')], comments=self.comments+[util.execution_stamp('Geom','mirror')],
autosize=True) autosize=True)
@ -688,7 +659,7 @@ class Geom:
ms = np.flip(self.microstructure, (valid.index(d) for d in directions if d in valid)) ms = np.flip(self.microstructure, (valid.index(d) for d in directions if d in valid))
return self.duplicate(ms, return self.duplicate(ms,
comments=self.get_comments()+[util.execution_stamp('Geom','flip')], comments=self.comments+[util.execution_stamp('Geom','flip')],
) )
@ -706,13 +677,13 @@ class Geom:
""" """
return self.duplicate(ndimage.interpolation.zoom( return self.duplicate(ndimage.interpolation.zoom(
self.microstructure, self.microstructure,
grid/self.get_grid(), grid/self.grid,
output=self.microstructure.dtype, output=self.microstructure.dtype,
order=0, order=0,
mode=('wrap' if periodic else 'nearest'), mode=('wrap' if periodic else 'nearest'),
prefilter=False prefilter=False
), ),
comments=self.get_comments()+[util.execution_stamp('Geom','scale')], comments=self.comments+[util.execution_stamp('Geom','scale')],
) )
@ -745,18 +716,18 @@ class Geom:
mode=('wrap' if periodic else 'nearest'), mode=('wrap' if periodic else 'nearest'),
extra_keywords=dict(selection=selection), extra_keywords=dict(selection=selection),
).astype(self.microstructure.dtype), ).astype(self.microstructure.dtype),
comments=self.get_comments()+[util.execution_stamp('Geom','clean')], comments=self.comments+[util.execution_stamp('Geom','clean')],
) )
def renumber(self): def renumber(self):
"""Renumber sorted microstructure indices to 1,...,N.""" """Renumber sorted microstructure indices to 1,...,N."""
renumbered = np.empty(self.get_grid(),dtype=self.microstructure.dtype) renumbered = np.empty(self.grid,dtype=self.microstructure.dtype)
for i, oldID in enumerate(np.unique(self.microstructure)): for i, oldID in enumerate(np.unique(self.microstructure)):
renumbered = np.where(self.microstructure == oldID, i+1, renumbered) renumbered = np.where(self.microstructure == oldID, i+1, renumbered)
return self.duplicate(renumbered, return self.duplicate(renumbered,
comments=self.get_comments()+[util.execution_stamp('Geom','renumber')], comments=self.comments+[util.execution_stamp('Geom','renumber')],
) )
@ -776,7 +747,7 @@ class Geom:
dtype = float if np.isnan(fill) or int(fill) != fill or self.microstructure.dtype==np.float else int dtype = float if np.isnan(fill) or int(fill) != fill or self.microstructure.dtype==np.float else int
Eulers = R.as_Eulers(degrees=True) Eulers = R.as_Eulers(degrees=True)
microstructure_in = self.get_microstructure() microstructure_in = self.microstructure.copy()
# These rotations are always applied in the reference coordinate system, i.e. (z,x,z) not (z,x',z'') # These rotations are always applied in the reference coordinate system, i.e. (z,x,z) not (z,x',z'')
# see https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf # see https://www.cs.utexas.edu/~theshark/courses/cs354/lectures/cs354-14.pdf
@ -793,7 +764,7 @@ class Geom:
return self.duplicate(microstructure_in, return self.duplicate(microstructure_in,
origin=origin, origin=origin,
comments=self.get_comments()+[util.execution_stamp('Geom','rotate')], comments=self.comments+[util.execution_stamp('Geom','rotate')],
autosize=True, autosize=True,
) )
@ -827,7 +798,7 @@ class Geom:
return self.duplicate(canvas, return self.duplicate(canvas,
origin=self.origin+offset*self.size/self.grid, origin=self.origin+offset*self.size/self.grid,
comments=self.get_comments()+[util.execution_stamp('Geom','canvas')], comments=self.comments+[util.execution_stamp('Geom','canvas')],
autosize=True, autosize=True,
) )
@ -844,12 +815,12 @@ class Geom:
New microstructure indices. New microstructure indices.
""" """
substituted = self.get_microstructure() substituted = self.microstructure.copy()
for from_ms,to_ms in zip(from_microstructure,to_microstructure): for from_ms,to_ms in zip(from_microstructure,to_microstructure):
substituted[self.microstructure==from_ms] = to_ms substituted[self.microstructure==from_ms] = to_ms
return self.duplicate(substituted, return self.duplicate(substituted,
comments=self.get_comments()+[util.execution_stamp('Geom','substitute')], comments=self.comments+[util.execution_stamp('Geom','substitute')],
) )
@ -896,5 +867,5 @@ class Geom:
microstructure = np.ma.MaskedArray(self.microstructure + offset_, np.logical_not(mask)) microstructure = np.ma.MaskedArray(self.microstructure + offset_, np.logical_not(mask))
return self.duplicate(microstructure, return self.duplicate(microstructure,
comments=self.get_comments()+[util.execution_stamp('Geom','vicinity_offset')], comments=self.comments+[util.execution_stamp('Geom','vicinity_offset')],
) )

View File

@ -11,9 +11,9 @@ from damask import util
def geom_equal(a,b): def geom_equal(a,b):
return np.all(a.get_microstructure() == b.get_microstructure()) and \ return np.all(a.microstructure == b.microstructure) and \
np.all(a.get_grid() == b.get_grid()) and \ np.all(a.grid == b.grid) and \
np.allclose(a.get_size(), b.get_size()) and \ np.allclose(a.size, b.size) and \
str(a.diff(b)) == str(b.diff(a)) str(a.diff(b)) == str(b.diff(a))
@pytest.fixture @pytest.fixture
@ -39,9 +39,9 @@ class TestGeom:
modified = default.duplicate() modified = default.duplicate()
elif flavor == 'explicit': elif flavor == 'explicit':
modified = default.duplicate( modified = default.duplicate(
default.get_microstructure(), default.microstructure,
default.get_size(), default.size,
default.get_origin() default.origin
) )
print(modified) print(modified)
assert geom_equal(default,modified) assert geom_equal(default,modified)
@ -57,7 +57,7 @@ class TestGeom:
def test_set_inplace_outofplace_homogenization(self,default): def test_set_inplace_outofplace_homogenization(self,default):
default.set_homogenization(123,inplace=True) default.set_homogenization(123,inplace=True)
outofplace = default.set_homogenization(321,inplace=False) outofplace = default.set_homogenization(321,inplace=False)
assert default.get_homogenization() == 123 and outofplace.get_homogenization() == 321 assert default.homogenization == 123 and outofplace.homogenization == 321
def test_set_inplace_outofplace_microstructure(self,default): def test_set_inplace_outofplace_microstructure(self,default):
@ -69,18 +69,18 @@ class TestGeom:
def test_set_inplace_outofplace_size(self,default): def test_set_inplace_outofplace_size(self,default):
default.set_size(np.array([1,2,3]),inplace=True) default.set_size(np.array([1,2,3]),inplace=True)
outofplace = default.set_size(np.array([3,2,1]),inplace=False) outofplace = default.set_size(np.array([3,2,1]),inplace=False)
assert np.array_equal(default.get_size(),[1,2,3]) and np.array_equal(outofplace.get_size(),[3,2,1]) assert np.array_equal(default.size,[1,2,3]) and np.array_equal(outofplace.size,[3,2,1])
def test_set_inplace_outofplace_comments(self,default): def test_set_inplace_outofplace_comments(self,default):
default.set_comments(['a','and','b'],inplace=True) default.set_comments(['a','and','b'],inplace=True)
outofplace = default.set_comments(['b','or','a'],inplace=False) outofplace = default.set_comments(['b','or','a'],inplace=False)
assert default.get_comments() == ['a','and','b'] and outofplace.get_comments() == ['b','or','a'] assert default.comments == ['a','and','b'] and outofplace.comments == ['b','or','a']
@pytest.mark.parametrize('masked',[True,False]) @pytest.mark.parametrize('masked',[True,False])
def test_set_microstructure(self,default,masked): def test_set_microstructure(self,default,masked):
old = default.get_microstructure() old = default.microstructure
new = np.random.randint(200,size=default.grid) new = np.random.randint(200,size=default.grid)
default.set_microstructure(np.ma.MaskedArray(new,np.full_like(new,masked)),inplace=True) default.set_microstructure(np.ma.MaskedArray(new,np.full_like(new,masked)),inplace=True)
assert np.all(default.microstructure==(old if masked else new)) assert np.all(default.microstructure==(old if masked else new))
@ -249,7 +249,7 @@ class TestGeom:
modified) modified)
def test_renumber(self,default): def test_renumber(self,default):
microstructure = default.get_microstructure() microstructure = default.microstructure.copy()
for m in np.unique(microstructure): for m in np.unique(microstructure):
microstructure[microstructure==m] = microstructure.max() + np.random.randint(1,30) microstructure[microstructure==m] = microstructure.max() + np.random.randint(1,30)
modified = default.duplicate(microstructure) modified = default.duplicate(microstructure)
@ -259,7 +259,7 @@ class TestGeom:
def test_substitute(self,default): def test_substitute(self,default):
offset = np.random.randint(1,500) offset = np.random.randint(1,500)
modified = default.duplicate(default.get_microstructure() + offset) modified = default.duplicate(default.microstructure + offset)
assert not geom_equal(modified,default) assert not geom_equal(modified,default)
assert geom_equal(default, assert geom_equal(default,
modified.substitute(np.arange(default.microstructure.max())+1+offset, modified.substitute(np.arange(default.microstructure.max())+1+offset,
@ -345,9 +345,9 @@ class TestGeom:
@pytest.mark.parametrize('periodic',[True,False]) @pytest.mark.parametrize('periodic',[True,False])
def test_vicinity_offset_invariant(self,default,periodic): def test_vicinity_offset_invariant(self,default,periodic):
old = default.get_microstructure() offset = default.vicinity_offset(trigger=[default.microstructure.max()+1,
default.vicinity_offset(trigger=[old.max()+1,old.min()-1]) default.microstructure.min()-1])
assert np.all(old==default.microstructure) assert np.all(offset.microstructure==default.microstructure)
@pytest.mark.parametrize('periodic',[True,False]) @pytest.mark.parametrize('periodic',[True,False])
def test_tessellation_approaches(self,periodic): def test_tessellation_approaches(self,periodic):