after the rename of "grid" to "cell", the name cell should not be used
for the coordinates of the cell centers. In agreement with the names
x_p/u_p for point positions/displacements, now the "point" is used to
refer to the materialpoints (i.e. cell centers)

Additionally, "_node"/"_point" are now suffixes to
"coordinates"/"displacements".

Finally, "coords" is renamed to "coordinates"
This commit is contained in:
Martin Diehl 2020-12-03 23:00:49 +01:00
parent ac0a20696c
commit 0fdefa5e78
18 changed files with 161 additions and 159 deletions

View File

@ -33,12 +33,12 @@ for filename in options.filenames:
results = damask.Result(filename) results = damask.Result(filename)
if not results.structured: continue if not results.structured: continue
coords = damask.grid_filters.cell_coord0(results.grid,results.size,results.origin).reshape(-1,3,order='F') coords = damask.grid_filters.coordinates0_point(results.cells,results.size,results.origin).reshape(-1,3,order='F')
N_digits = int(np.floor(np.log10(int(results.increments[-1][3:]))))+1 N_digits = int(np.floor(np.log10(int(results.increments[-1][3:]))))+1
N_digits = 5 # hack to keep test intact N_digits = 5 # hack to keep test intact
for inc in damask.util.show_progress(results.iterate('increments'),len(results.increments)): for inc in damask.util.show_progress(results.iterate('increments'),len(results.increments)):
table = damask.Table(np.ones(np.product(results.grid),dtype=int)*int(inc[3:]),{'inc':(1,)})\ table = damask.Table(np.ones(np.product(results.cells),dtype=int)*int(inc[3:]),{'inc':(1,)})\
.add('pos',coords.reshape(-1,3)) .add('pos',coords.reshape(-1,3))
results.pick('homogenizations',False) results.pick('homogenizations',False)
@ -46,14 +46,14 @@ for filename in options.filenames:
for label in options.con: for label in options.con:
x = results.get_dataset_location(label) x = results.get_dataset_location(label)
if len(x) != 0: if len(x) != 0:
table = table.add(label,results.read_dataset(x,0,plain=True).reshape(results.grid.prod(),-1)) table = table.add(label,results.read_dataset(x,0,plain=True).reshape(results.cells.prod(),-1))
results.pick('phases',False) results.pick('phases',False)
results.pick('homogenizations',True) results.pick('homogenizations',True)
for label in options.mat: for label in options.mat:
x = results.get_dataset_location(label) x = results.get_dataset_location(label)
if len(x) != 0: if len(x) != 0:
table = table.add(label,results.read_dataset(x,0,plain=True).reshape(results.grid.prod(),-1)) table = table.add(label,results.read_dataset(x,0,plain=True).reshape(results.cells.prod(),-1))
dirname = os.path.abspath(os.path.join(os.path.dirname(filename),options.dir)) dirname = os.path.abspath(os.path.join(os.path.dirname(filename),options.dir))
if not os.path.isdir(dirname): if not os.path.isdir(dirname):

View File

@ -71,13 +71,13 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) grid,size,origin = damask.grid_filters.cellSizeOrigin_coordinates0_point(table.get(options.pos))
F = table.get(options.defgrad).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3)) F = table.get(options.defgrad).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3))
nodes = damask.grid_filters.node_coord(size,F) nodes = damask.grid_filters.coordinates_node(size,F)
if options.shape: if options.shape:
centers = damask.grid_filters.cell_coord(size,F) centers = damask.grid_filters.coordinates_point(size,F)
shapeMismatch = shapeMismatch(size,F,nodes,centers) shapeMismatch = shapeMismatch(size,F,nodes,centers)
table = table.add('shapeMismatch(({}))'.format(options.defgrad), table = table.add('shapeMismatch(({}))'.format(options.defgrad),
shapeMismatch.reshape(-1,1,order='F'), shapeMismatch.reshape(-1,1,order='F'),

View File

@ -44,7 +44,7 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) grid,size,origin = damask.grid_filters.cellSizeOrigin_coordinates0_point(table.get(options.pos))
for label in options.labels: for label in options.labels:
field = table.get(label) field = table.get(label)

View File

@ -48,24 +48,24 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) grid,size,origin = damask.grid_filters.cellSizeOrigin_coordinates0_point(table.get(options.pos))
F = table.get(options.f).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3)) F = table.get(options.f).reshape(tuple(grid)+(-1,),order='F').reshape(tuple(grid)+(3,3))
if options.nodal: if options.nodal:
damask.Table(damask.grid_filters.node_coord0(grid,size).reshape(-1,3,order='F'), damask.Table(damask.grid_filters.coordinates0_node(grid,size).reshape(-1,3,order='F'),
{'pos':(3,)})\ {'pos':(3,)})\
.add('avg({}).{}'.format(options.f,options.pos), .add('avg({}).{}'.format(options.f,options.pos),
damask.grid_filters.node_displacement_avg(size,F).reshape(-1,3,order='F'), damask.grid_filters.displacement_avg_node(size,F).reshape(-1,3,order='F'),
scriptID+' '+' '.join(sys.argv[1:]))\ scriptID+' '+' '.join(sys.argv[1:]))\
.add('fluct({}).{}'.format(options.f,options.pos), .add('fluct({}).{}'.format(options.f,options.pos),
damask.grid_filters.node_displacement_fluct(size,F).reshape(-1,3,order='F'), damask.grid_filters.displacement_fluct_node(size,F).reshape(-1,3,order='F'),
scriptID+' '+' '.join(sys.argv[1:]))\ scriptID+' '+' '.join(sys.argv[1:]))\
.save((sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt')) .save((sys.stdout if name is None else os.path.splitext(name)[0]+'_nodal.txt'))
else: else:
table.add('avg({}).{}'.format(options.f,options.pos), table.add('avg({}).{}'.format(options.f,options.pos),
damask.grid_filters.cell_displacement_avg(size,F).reshape(-1,3,order='F'), damask.grid_filters.displacement_avg_point(size,F).reshape(-1,3,order='F'),
scriptID+' '+' '.join(sys.argv[1:]))\ scriptID+' '+' '.join(sys.argv[1:]))\
.add('fluct({}).{}'.format(options.f,options.pos), .add('fluct({}).{}'.format(options.f,options.pos),
damask.grid_filters.cell_displacement_fluct(size,F).reshape(-1,3,order='F'), damask.grid_filters.displacement_fluct_point(size,F).reshape(-1,3,order='F'),
scriptID+' '+' '.join(sys.argv[1:]))\ scriptID+' '+' '.join(sys.argv[1:]))\
.save((sys.stdout if name is None else name)) .save((sys.stdout if name is None else name))

View File

@ -44,7 +44,7 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) grid,size,origin = damask.grid_filters.cellSizeOrigin_coordinates0_point(table.get(options.pos))
for label in options.labels: for label in options.labels:
field = table.get(label) field = table.get(label)

View File

@ -143,7 +143,7 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) grid,size,origin = damask.grid_filters.cellSizeOrigin_coordinates0_point(table.get(options.pos))
neighborhood = neighborhoods[options.neighborhood] neighborhood = neighborhoods[options.neighborhood]
diffToNeighbor = np.empty(list(grid+2)+[len(neighborhood)],'i') diffToNeighbor = np.empty(list(grid+2)+[len(neighborhood)],'i')

View File

@ -44,7 +44,7 @@ for name in filenames:
damask.util.report(scriptName,name) damask.util.report(scriptName,name)
table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name) table = damask.Table.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
grid,size,origin = damask.grid_filters.cell_coord0_gridSizeOrigin(table.get(options.pos)) grid,size,origin = damask.grid_filters.cellSizeOrigin_coordinates0_point(table.get(options.pos))
for label in options.labels: for label in options.labels:
field = table.get(label) field = table.get(label)

View File

@ -302,7 +302,7 @@ class Geom:
Each unique combintation of values results in one material ID. Each unique combintation of values results in one material ID.
""" """
cells,size,origin = grid_filters.cell_coord0_gridSizeOrigin(table.get(coordinates)) cells,size,origin = grid_filters.cellSizeOrigin_coordinates0_point(table.get(coordinates))
labels_ = [labels] if isinstance(labels,str) else labels labels_ = [labels] if isinstance(labels,str) else labels
unique,unique_inverse = np.unique(np.hstack([table.get(l) for l in labels_]),return_inverse=True,axis=0) unique,unique_inverse = np.unique(np.hstack([table.get(l) for l in labels_]),return_inverse=True,axis=0)
@ -344,11 +344,11 @@ class Geom:
seeds_p = np.vstack((seeds -np.array([size[0],0.,0.]),seeds, seeds +np.array([size[0],0.,0.]))) seeds_p = np.vstack((seeds -np.array([size[0],0.,0.]),seeds, seeds +np.array([size[0],0.,0.])))
seeds_p = np.vstack((seeds_p-np.array([0.,size[1],0.]),seeds_p,seeds_p+np.array([0.,size[1],0.]))) seeds_p = np.vstack((seeds_p-np.array([0.,size[1],0.]),seeds_p,seeds_p+np.array([0.,size[1],0.])))
seeds_p = np.vstack((seeds_p-np.array([0.,0.,size[2]]),seeds_p,seeds_p+np.array([0.,0.,size[2]]))) seeds_p = np.vstack((seeds_p-np.array([0.,0.,size[2]]),seeds_p,seeds_p+np.array([0.,0.,size[2]])))
coords = grid_filters.cell_coord0(cells*3,size*3,-size).reshape(-1,3) coords = grid_filters.coordinates0_point(cells*3,size*3,-size).reshape(-1,3)
else: else:
weights_p = weights weights_p = weights
seeds_p = seeds seeds_p = seeds
coords = grid_filters.cell_coord0(cells,size).reshape(-1,3) coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3)
pool = mp.Pool(processes = int(environment.options['DAMASK_NUM_THREADS'])) pool = mp.Pool(processes = int(environment.options['DAMASK_NUM_THREADS']))
result = pool.map_async(partial(Geom._find_closest_seed,seeds_p,weights_p), [coord for coord in coords]) result = pool.map_async(partial(Geom._find_closest_seed,seeds_p,weights_p), [coord for coord in coords])
@ -388,7 +388,7 @@ class Geom:
Perform a periodic tessellation. Defaults to True. Perform a periodic tessellation. Defaults to True.
""" """
coords = grid_filters.cell_coord0(cells,size).reshape(-1,3) coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3)
KDTree = spatial.cKDTree(seeds,boxsize=size) if periodic else spatial.cKDTree(seeds) KDTree = spatial.cKDTree(seeds,boxsize=size) if periodic else spatial.cKDTree(seeds)
devNull,material_ = KDTree.query(coords) devNull,material_ = KDTree.query(coords)
@ -592,7 +592,7 @@ class Geom:
c = (np.array(center) + .5)*self.size/self.cells if np.array(center).dtype in np.sctypes['int'] else \ c = (np.array(center) + .5)*self.size/self.cells if np.array(center).dtype in np.sctypes['int'] else \
(np.array(center) - self.origin) (np.array(center) - self.origin)
coords = grid_filters.cell_coord0(self.cells,self.size, coords = grid_filters.coordinates0_point(self.cells,self.size,
-(0.5*(self.size + (self.size/self.cells -(0.5*(self.size + (self.size/self.cells
if np.array(center).dtype in np.sctypes['int'] else if np.array(center).dtype in np.sctypes['int'] else
0)) if periodic else c)) 0)) if periodic else c))
@ -932,5 +932,5 @@ class Geom:
base_nodes = np.argwhere(mask.flatten(order='F')).reshape(-1,1) base_nodes = np.argwhere(mask.flatten(order='F')).reshape(-1,1)
connectivity.append(np.block([base_nodes + o[i][k] for k in range(4)])) connectivity.append(np.block([base_nodes + o[i][k] for k in range(4)]))
coords = grid_filters.node_coord0(self.cells,self.size,self.origin).reshape(-1,3,order='F') coords = grid_filters.coordinates0_node(self.cells,self.size,self.origin).reshape(-1,3,order='F')
return VTK.from_unstructured_grid(coords,np.vstack(connectivity),'QUAD') return VTK.from_unstructured_grid(coords,np.vstack(connectivity),'QUAD')

View File

@ -562,19 +562,19 @@ class Result:
return dataset return dataset
@property @property
def cell_coordinates(self): def coordinates0_point(self):
"""Return initial coordinates of the cell centers.""" """Return initial coordinates of the cell centers."""
if self.structured: if self.structured:
return grid_filters.cell_coord0(self.cells,self.size,self.origin).reshape(-1,3,order='F') return grid_filters.coordinates0_point(self.cells,self.size,self.origin).reshape(-1,3,order='F')
else: else:
with h5py.File(self.fname,'r') as f: with h5py.File(self.fname,'r') as f:
return f['geometry/x_c'][()] return f['geometry/x_c'][()]
@property @property
def node_coordinates(self): def coordinates0_node(self):
"""Return initial coordinates of the cell centers.""" """Return initial coordinates of the cell centers."""
if self.structured: if self.structured:
return grid_filters.node_coord0(self.cells,self.size,self.origin).reshape(-1,3,order='F') return grid_filters.coordinates0_node(self.cells,self.size,self.origin).reshape(-1,3,order='F')
else: else:
with h5py.File(self.fname,'r') as f: with h5py.File(self.fname,'r') as f:
return f['geometry/x_n'][()] return f['geometry/x_n'][()]
@ -1303,7 +1303,7 @@ class Result:
f['/geometry/T_c'].attrs['VTK_TYPE'] if h5py3 else \ f['/geometry/T_c'].attrs['VTK_TYPE'] if h5py3 else \
f['/geometry/T_c'].attrs['VTK_TYPE'].decode()) f['/geometry/T_c'].attrs['VTK_TYPE'].decode())
elif mode.lower()=='point': elif mode.lower()=='point':
v = VTK.from_poly_data(self.cell_coordinates) v = VTK.from_poly_data(self.coordinates0_point)
N_digits = int(np.floor(np.log10(max(1,int(self.increments[-1][3:])))))+1 N_digits = int(np.floor(np.log10(max(1,int(self.increments[-1][3:])))))+1

View File

@ -763,7 +763,7 @@ class Rotation:
def _dg(eu,deg): def _dg(eu,deg):
"""Return infinitesimal Euler space volume of bin(s).""" """Return infinitesimal Euler space volume of bin(s)."""
phi_sorted = eu[np.lexsort((eu[:,0],eu[:,1],eu[:,2]))] phi_sorted = eu[np.lexsort((eu[:,0],eu[:,1],eu[:,2]))]
steps,size,_ = grid_filters.cell_coord0_gridSizeOrigin(phi_sorted) steps,size,_ = grid_filters.cellSizeOrigin_coordinates0_point(phi_sorted)
delta = np.radians(size/steps) if deg else size/steps delta = np.radians(size/steps) if deg else size/steps
return delta[0]*2.0*np.sin(delta[1]/2.0)*delta[2] / 8.0 / np.pi**2 * np.sin(np.radians(eu[:,1]) if deg else eu[:,1]) return delta[0]*2.0*np.sin(delta[1]/2.0)*delta[2] / 8.0 / np.pi**2 * np.sin(np.radians(eu[:,1]) if deg else eu[:,1])

View File

@ -22,11 +22,11 @@ def _ks(size,cells,first_order=False):
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
cells : numpy.ndarray of shape (3) cells : numpy.ndarray of shape (3)
number of cells. Number of cells.
first_order : bool, optional first_order : bool, optional
correction for first order derivatives, defaults to False. Correction for first order derivatives, defaults to False.
""" """
k_sk = _np.where(_np.arange(cells[0])>cells[0]//2,_np.arange(cells[0])-cells[0],_np.arange(cells[0]))/size[0] k_sk = _np.where(_np.arange(cells[0])>cells[0]//2,_np.arange(cells[0])-cells[0],_np.arange(cells[0]))/size[0]
@ -47,9 +47,9 @@ def curl(size,field):
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
field : numpy.ndarray of shape (:,:,:,3) or (:,:,:,3,3) field : numpy.ndarray of shape (:,:,:,3) or (:,:,:,3,3)
periodic field of which the curl is calculated. Periodic field of which the curl is calculated.
""" """
n = _np.prod(field.shape[3:]) n = _np.prod(field.shape[3:])
@ -73,9 +73,9 @@ def divergence(size,field):
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
field : numpy.ndarray of shape (:,:,:,3) or (:,:,:,3,3) field : numpy.ndarray of shape (:,:,:,3) or (:,:,:,3,3)
periodic field of which the divergence is calculated. Periodic field of which the divergence is calculated.
""" """
n = _np.prod(field.shape[3:]) n = _np.prod(field.shape[3:])
@ -95,9 +95,9 @@ def gradient(size,field):
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
field : numpy.ndarray of shape (:,:,:,1) or (:,:,:,3) field : numpy.ndarray of shape (:,:,:,1) or (:,:,:,3)
periodic field of which the gradient is calculated. Periodic field of which the gradient is calculated.
""" """
n = _np.prod(field.shape[3:]) n = _np.prod(field.shape[3:])
@ -110,18 +110,18 @@ def gradient(size,field):
return _np.fft.irfftn(grad_,axes=(0,1,2),s=field.shape[:3]) return _np.fft.irfftn(grad_,axes=(0,1,2),s=field.shape[:3])
def cell_coord0(cells,size,origin=_np.zeros(3)): def coordinates0_point(cells,size,origin=_np.zeros(3)):
""" """
Cell center positions (undeformed). Cell center positions (undeformed).
Parameters Parameters
---------- ----------
cells : numpy.ndarray of shape (3) cells : numpy.ndarray of shape (3)
number of cells. Number of cells.
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
origin : numpy.ndarray, optional origin : numpy.ndarray, optional
physical origin of the periodic field. Defaults to [0.0,0.0,0.0]. Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].
""" """
start = origin + size/cells*.5 start = origin + size/cells*.5
@ -133,16 +133,16 @@ def cell_coord0(cells,size,origin=_np.zeros(3)):
axis = -1) axis = -1)
def cell_displacement_fluct(size,F): def displacement_fluct_point(size,F):
""" """
Cell center displacement field from fluctuation part of the deformation gradient field. Cell center displacement field from fluctuation part of the deformation gradient field.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
""" """
integrator = 0.5j*size/_np.pi integrator = 0.5j*size/_np.pi
@ -160,67 +160,67 @@ def cell_displacement_fluct(size,F):
return _np.fft.irfftn(displacement,axes=(0,1,2),s=F.shape[:3]) return _np.fft.irfftn(displacement,axes=(0,1,2),s=F.shape[:3])
def cell_displacement_avg(size,F): def displacement_avg_point(size,F):
""" """
Cell center displacement field from average part of the deformation gradient field. Cell center displacement field from average part of the deformation gradient field.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
""" """
F_avg = _np.average(F,axis=(0,1,2)) F_avg = _np.average(F,axis=(0,1,2))
return _np.einsum('ml,ijkl->ijkm',F_avg - _np.eye(3),cell_coord0(F.shape[:3],size)) return _np.einsum('ml,ijkl->ijkm',F_avg - _np.eye(3),coordinates0_point(F.shape[:3],size))
def cell_displacement(size,F): def displacement_point(size,F):
""" """
Cell center displacement field from deformation gradient field. Cell center displacement field from deformation gradient field.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
""" """
return cell_displacement_avg(size,F) + cell_displacement_fluct(size,F) return displacement_avg_point(size,F) + displacement_fluct_point(size,F)
def cell_coord(size,F,origin=_np.zeros(3)): def coordinates_point(size,F,origin=_np.zeros(3)):
""" """
Cell center positions. Cell center positions.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
origin : numpy.ndarray of shape (3), optional origin : numpy.ndarray of shape (3), optional
physical origin of the periodic field. Defaults to [0.0,0.0,0.0]. Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].
""" """
return cell_coord0(F.shape[:3],size,origin) + cell_displacement(size,F) return coordinates0_point(F.shape[:3],size,origin) + displacement_point(size,F)
def cell_coord0_gridSizeOrigin(coord0,ordered=True): def cellSizeOrigin_coordinates0_point(coordinates0,ordered=True):
""" """
Return grid 'DNA', i.e. cells, size, and origin from 1D array of cell positions. Return grid 'DNA', i.e. cells, size, and origin from 1D array of point positions.
Parameters Parameters
---------- ----------
coord0 : numpy.ndarray of shape (:,3) coordinates0 : numpy.ndarray of shape (:,3)
undeformed cell coordinates. Undeformed cell coordinates.
ordered : bool, optional ordered : bool, optional
expect coord0 data to be ordered (x fast, z slow). Expect coordinates0 data to be ordered (x fast, z slow).
""" """
coords = [_np.unique(coord0[:,i]) for i in range(3)] coords = [_np.unique(coordinates0[:,i]) for i in range(3)]
mincorner = _np.array(list(map(min,coords))) mincorner = _np.array(list(map(min,coords)))
maxcorner = _np.array(list(map(max,coords))) maxcorner = _np.array(list(map(max,coords)))
cells = _np.array(list(map(len,coords)),'i') cells = _np.array(list(map(len,coords)),'i')
@ -232,8 +232,8 @@ def cell_coord0_gridSizeOrigin(coord0,ordered=True):
size [_np.where(cells==1)] = origin[_np.where(cells==1)]*2. size [_np.where(cells==1)] = origin[_np.where(cells==1)]*2.
origin[_np.where(cells==1)] = 0.0 origin[_np.where(cells==1)] = 0.0
if cells.prod() != len(coord0): if cells.prod() != len(coordinates0):
raise ValueError('Data count {len(coord0)} does not match cells {cells}.') raise ValueError('Data count {len(coordinates0)} does not match cells {cells}.')
start = origin + delta*.5 start = origin + delta*.5
end = origin - delta*.5 + size end = origin - delta*.5 + size
@ -244,37 +244,38 @@ def cell_coord0_gridSizeOrigin(coord0,ordered=True):
_np.allclose(coords[2],_np.linspace(start[2],end[2],cells[2]),atol=atol)): _np.allclose(coords[2],_np.linspace(start[2],end[2],cells[2]),atol=atol)):
raise ValueError('Regular cells spacing violated.') raise ValueError('Regular cells spacing violated.')
if ordered and not _np.allclose(coord0.reshape(tuple(cells)+(3,),order='F'),cell_coord0(cells,size,origin),atol=atol): if ordered and not _np.allclose(coordinates0.reshape(tuple(cells)+(3,),order='F'),
coordinates0_point(cells,size,origin),atol=atol):
raise ValueError('Input data is not ordered (x fast, z slow).') raise ValueError('Input data is not ordered (x fast, z slow).')
return (cells,size,origin) return (cells,size,origin)
def coord0_check(coord0): def coordinates0_check(coordinates0):
""" """
Check whether coordinates lie on a regular grid. Check whether coordinates lie on a regular grid.
Parameters Parameters
---------- ----------
coord0 : numpy.ndarray coordinates0 : numpy.ndarray
array of undeformed cell coordinates. Array of undeformed cell coordinates.
""" """
cell_coord0_gridSizeOrigin(coord0,ordered=True) cellSizeOrigin_coordinates0_point(coordinates0,ordered=True)
def node_coord0(cells,size,origin=_np.zeros(3)): def coordinates0_node(cells,size,origin=_np.zeros(3)):
""" """
Nodal positions (undeformed). Nodal positions (undeformed).
Parameters Parameters
---------- ----------
cells : numpy.ndarray of shape (3) cells : numpy.ndarray of shape (3)
number of cells. Number of cells.
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
origin : numpy.ndarray of shape (3), optional origin : numpy.ndarray of shape (3), optional
physical origin of the periodic field. Defaults to [0.0,0.0,0.0]. Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].
""" """
return _np.stack(_np.meshgrid(_np.linspace(origin[0],size[0]+origin[0],cells[0]+1), return _np.stack(_np.meshgrid(_np.linspace(origin[0],size[0]+origin[0],cells[0]+1),
@ -283,71 +284,71 @@ def node_coord0(cells,size,origin=_np.zeros(3)):
axis = -1) axis = -1)
def node_displacement_fluct(size,F): def displacement_fluct_node(size,F):
""" """
Nodal displacement field from fluctuation part of the deformation gradient field. Nodal displacement field from fluctuation part of the deformation gradient field.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
""" """
return cell_2_node(cell_displacement_fluct(size,F)) return point_2_node(displacement_fluct_point(size,F))
def node_displacement_avg(size,F): def displacement_avg_node(size,F):
""" """
Nodal displacement field from average part of the deformation gradient field. Nodal displacement field from average part of the deformation gradient field.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
""" """
F_avg = _np.average(F,axis=(0,1,2)) F_avg = _np.average(F,axis=(0,1,2))
return _np.einsum('ml,ijkl->ijkm',F_avg - _np.eye(3),node_coord0(F.shape[:3],size)) return _np.einsum('ml,ijkl->ijkm',F_avg - _np.eye(3),coordinates0_node(F.shape[:3],size))
def node_displacement(size,F): def displacement_node(size,F):
""" """
Nodal displacement field from deformation gradient field. Nodal displacement field from deformation gradient field.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
""" """
return node_displacement_avg(size,F) + node_displacement_fluct(size,F) return displacement_avg_node(size,F) + displacement_fluct_node(size,F)
def node_coord(size,F,origin=_np.zeros(3)): def coordinates_node(size,F,origin=_np.zeros(3)):
""" """
Nodal positions. Nodal positions.
Parameters Parameters
---------- ----------
size : numpy.ndarray of shape (3) size : numpy.ndarray of shape (3)
physical size of the periodic field. Physical size of the periodic field.
F : numpy.ndarray F : numpy.ndarray
deformation gradient field. Deformation gradient field.
origin : numpy.ndarray of shape (3), optional origin : numpy.ndarray of shape (3), optional
physical origin of the periodic field. Defaults to [0.0,0.0,0.0]. Physical origin of the periodic field. Defaults to [0.0,0.0,0.0].
""" """
return node_coord0(F.shape[:3],size,origin) + node_displacement(size,F) return coordinates0_node(F.shape[:3],size,origin) + displacement_node(size,F)
def cell_2_node(cell_data): def point_2_node(cell_data):
"""Interpolate periodic cell data to nodal data.""" """Interpolate periodic point data to nodal data."""
n = ( cell_data + _np.roll(cell_data,1,(0,1,2)) n = ( cell_data + _np.roll(cell_data,1,(0,1,2))
+ _np.roll(cell_data,1,(0,)) + _np.roll(cell_data,1,(1,)) + _np.roll(cell_data,1,(2,)) + _np.roll(cell_data,1,(0,)) + _np.roll(cell_data,1,(1,)) + _np.roll(cell_data,1,(2,))
+ _np.roll(cell_data,1,(0,1)) + _np.roll(cell_data,1,(1,2)) + _np.roll(cell_data,1,(2,0)))*0.125 + _np.roll(cell_data,1,(0,1)) + _np.roll(cell_data,1,(1,2)) + _np.roll(cell_data,1,(2,0)))*0.125
@ -355,8 +356,8 @@ def cell_2_node(cell_data):
return _np.pad(n,((0,1),(0,1),(0,1))+((0,0),)*len(cell_data.shape[3:]),mode='wrap') return _np.pad(n,((0,1),(0,1),(0,1))+((0,0),)*len(cell_data.shape[3:]),mode='wrap')
def node_2_cell(node_data): def node_2_point(node_data):
"""Interpolate periodic nodal data to cell data.""" """Interpolate periodic nodal data to point data."""
c = ( node_data + _np.roll(node_data,1,(0,1,2)) c = ( node_data + _np.roll(node_data,1,(0,1,2))
+ _np.roll(node_data,1,(0,)) + _np.roll(node_data,1,(1,)) + _np.roll(node_data,1,(2,)) + _np.roll(node_data,1,(0,)) + _np.roll(node_data,1,(1,)) + _np.roll(node_data,1,(2,))
+ _np.roll(node_data,1,(0,1)) + _np.roll(node_data,1,(1,2)) + _np.roll(node_data,1,(2,0)))*0.125 + _np.roll(node_data,1,(0,1)) + _np.roll(node_data,1,(1,2)) + _np.roll(node_data,1,(2,0)))*0.125
@ -364,27 +365,27 @@ def node_2_cell(node_data):
return c[1:,1:,1:] return c[1:,1:,1:]
def node_coord0_gridSizeOrigin(coord0,ordered=True): def cellSizeOrigin_coordinates0_node(coordinates0,ordered=True):
""" """
Return grid 'DNA', i.e. cells, size, and origin from 1D array of nodal positions. Return grid 'DNA', i.e. cells, size, and origin from 1D array of nodal positions.
Parameters Parameters
---------- ----------
coord0 : numpy.ndarray of shape (:,3) coordinates0 : numpy.ndarray of shape (:,3)
undeformed nodal coordinates. Undeformed nodal coordinates.
ordered : bool, optional ordered : bool, optional
expect coord0 data to be ordered (x fast, z slow). Expect coordinates0 data to be ordered (x fast, z slow).
""" """
coords = [_np.unique(coord0[:,i]) for i in range(3)] coords = [_np.unique(coordinates0[:,i]) for i in range(3)]
mincorner = _np.array(list(map(min,coords))) mincorner = _np.array(list(map(min,coords)))
maxcorner = _np.array(list(map(max,coords))) maxcorner = _np.array(list(map(max,coords)))
cells = _np.array(list(map(len,coords)),'i') - 1 cells = _np.array(list(map(len,coords)),'i') - 1
size = maxcorner-mincorner size = maxcorner-mincorner
origin = mincorner origin = mincorner
if (cells+1).prod() != len(coord0): if (cells+1).prod() != len(coordinates0):
raise ValueError('Data count {len(coord0)} does not match cells {cells}.') raise ValueError('Data count {len(coordinates0)} does not match cells {cells}.')
atol = _np.max(size)*5e-2 atol = _np.max(size)*5e-2
if not (_np.allclose(coords[0],_np.linspace(mincorner[0],maxcorner[0],cells[0]+1),atol=atol) and \ if not (_np.allclose(coords[0],_np.linspace(mincorner[0],maxcorner[0],cells[0]+1),atol=atol) and \
@ -392,7 +393,8 @@ def node_coord0_gridSizeOrigin(coord0,ordered=True):
_np.allclose(coords[2],_np.linspace(mincorner[2],maxcorner[2],cells[2]+1),atol=atol)): _np.allclose(coords[2],_np.linspace(mincorner[2],maxcorner[2],cells[2]+1),atol=atol)):
raise ValueError('Regular cells spacing violated.') raise ValueError('Regular cells spacing violated.')
if ordered and not _np.allclose(coord0.reshape(tuple(cells+1)+(3,),order='F'),node_coord0(cells,size,origin),atol=atol): if ordered and not _np.allclose(coordinates0.reshape(tuple(cells+1)+(3,),order='F'),
coordinates0_node(cells,size,origin),atol=atol):
raise ValueError('Input data is not ordered (x fast, z slow).') raise ValueError('Input data is not ordered (x fast, z slow).')
return (cells,size,origin) return (cells,size,origin)
@ -412,9 +414,9 @@ def regrid(size,F,cells_new):
New cells for undeformed coordinates. New cells for undeformed coordinates.
""" """
c = cell_coord0(F.shape[:3],size) \ c = coordinates0_point(F.shape[:3],size) \
+ cell_displacement_avg(size,F) \ + displacement_avg_point(size,F) \
+ cell_displacement_fluct(size,F) + displacement_fluct_point(size,F)
outer = _np.dot(_np.average(F,axis=(0,1,2)),size) outer = _np.dot(_np.average(F,axis=(0,1,2)),size)
for d in range(3): for d in range(3):
@ -422,4 +424,4 @@ def regrid(size,F,cells_new):
c[_np.where(c[:,:,:,d]>outer[d])] -= outer[d] c[_np.where(c[:,:,:,d]>outer[d])] -= outer[d]
tree = _spatial.cKDTree(c.reshape(-1,3),boxsize=outer) tree = _spatial.cKDTree(c.reshape(-1,3),boxsize=outer)
return tree.query(cell_coord0(cells_new,outer))[1].flatten() return tree.query(coordinates0_point(cells_new,outer))[1].flatten()

View File

@ -29,7 +29,7 @@ def from_random(size,N_seeds,cells=None,rng_seed=None):
if cells is None: if cells is None:
coords = rng.random((N_seeds,3)) * size coords = rng.random((N_seeds,3)) * size
else: else:
grid_coords = grid_filters.cell_coord0(cells,size).reshape(-1,3,order='F') grid_coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3,order='F')
coords = grid_coords[rng.choice(_np.prod(cells),N_seeds, replace=False)] \ coords = grid_coords[rng.choice(_np.prod(cells),N_seeds, replace=False)] \
+ _np.broadcast_to(size/cells,(N_seeds,3))*(rng.random((N_seeds,3))*.5-.25) # wobble without leaving cells + _np.broadcast_to(size/cells,(N_seeds,3))*(rng.random((N_seeds,3))*.5-.25) # wobble without leaving cells
@ -98,7 +98,7 @@ def from_geom(geom,selection=None,invert=False,average=False,periodic=True):
material = geom.material.reshape((-1,1),order='F') material = geom.material.reshape((-1,1),order='F')
mask = _np.full(geom.cells.prod(),True,dtype=bool) if selection is None else \ mask = _np.full(geom.cells.prod(),True,dtype=bool) if selection is None else \
_np.isin(material,selection,invert=invert).flatten() _np.isin(material,selection,invert=invert).flatten()
coords = grid_filters.cell_coord0(geom.cells,geom.size).reshape(-1,3,order='F') coords = grid_filters.coordinates0_point(geom.cells,geom.size).reshape(-1,3,order='F')
if not average: if not average:
return (coords[mask],material[mask]) return (coords[mask],material[mask])

View File

@ -394,7 +394,7 @@ class TestGeom:
def test_from_table(self): def test_from_table(self):
cells = np.random.randint(60,100,3) cells = np.random.randint(60,100,3)
size = np.ones(3)+np.random.rand(3) size = np.ones(3)+np.random.rand(3)
coords = grid_filters.cell_coord0(cells,size).reshape(-1,3,order='F') coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3,order='F')
z=np.ones(cells.prod()) z=np.ones(cells.prod())
z[cells[:2].prod()*int(cells[2]/2):]=0 z[cells[:2].prod()*int(cells[2]/2):]=0
t = Table(np.column_stack((coords,z)),{'coords':3,'z':1}) t = Table(np.column_stack((coords,z)),{'coords':3,'z':1})
@ -407,7 +407,7 @@ class TestGeom:
size = np.ones(3)+np.random.rand(3) size = np.ones(3)+np.random.rand(3)
s = seeds.from_random(size,np.random.randint(60,100)) s = seeds.from_random(size,np.random.randint(60,100))
geom = Geom.from_Voronoi_tessellation(cells,size,s) geom = Geom.from_Voronoi_tessellation(cells,size,s)
coords = grid_filters.cell_coord0(cells,size) coords = grid_filters.coordinates0_point(cells,size)
t = Table(np.column_stack((coords.reshape(-1,3,order='F'),geom.material.flatten(order='F'))),{'c':3,'m':1}) t = Table(np.column_stack((coords.reshape(-1,3,order='F'),geom.material.flatten(order='F'))),{'c':3,'m':1})
assert geom_equal(geom.sort().renumber(),Geom.from_table(t,'c',['m'])) assert geom_equal(geom.sort().renumber(),Geom.from_table(t,'c',['m']))

View File

@ -356,11 +356,11 @@ class TestResult:
@pytest.mark.parametrize('mode',['cell','node']) @pytest.mark.parametrize('mode',['cell','node'])
def test_coordinates(self,default,mode): def test_coordinates(self,default,mode):
if mode == 'cell': if mode == 'cell':
a = grid_filters.cell_coord0(default.cells,default.size,default.origin) a = grid_filters.coordinates0_point(default.cells,default.size,default.origin)
b = default.cell_coordinates.reshape(tuple(default.cells)+(3,),order='F') b = default.coordinates0_point.reshape(tuple(default.cells)+(3,),order='F')
elif mode == 'node': elif mode == 'node':
a = grid_filters.node_coord0(default.cells,default.size,default.origin) a = grid_filters.coordinates0_node(default.cells,default.size,default.origin)
b = default.node_coordinates.reshape(tuple(default.cells+1)+(3,),order='F') b = default.coordinates0_node.reshape(tuple(default.cells+1)+(3,),order='F')
assert np.allclose(a,b) assert np.allclose(a,b)
@pytest.mark.parametrize('output',['F',[],['F','P']]) @pytest.mark.parametrize('output',['F',[],['F','P']])

View File

@ -1022,7 +1022,7 @@ class TestRotation:
rng = tuple(zip(np.zeros(3),limits)) rng = tuple(zip(np.zeros(3),limits))
weights = Table.load(ref_path/'ODF_experimental_cell.txt').get('intensity').flatten() weights = Table.load(ref_path/'ODF_experimental_cell.txt').get('intensity').flatten()
Eulers = grid_filters.cell_coord0(steps,limits) Eulers = grid_filters.coordinates0_point(steps,limits)
Eulers = np.radians(Eulers) if not degrees else Eulers Eulers = np.radians(Eulers) if not degrees else Eulers
Eulers_r = Rotation.from_ODF(weights,Eulers.reshape(-1,3,order='F'),N,degrees,fractions).as_Euler_angles(True) Eulers_r = Rotation.from_ODF(weights,Eulers.reshape(-1,3,order='F'),N,degrees,fractions).as_Euler_angles(True)
@ -1040,7 +1040,7 @@ class TestRotation:
weights = Table.load(ref_path/'ODF_experimental.txt').get('intensity') weights = Table.load(ref_path/'ODF_experimental.txt').get('intensity')
weights = weights.reshape(steps+1,order='F')[:-1,:-1,:-1].reshape(-1,order='F') weights = weights.reshape(steps+1,order='F')[:-1,:-1,:-1].reshape(-1,order='F')
Eulers = grid_filters.node_coord0(steps,limits)[:-1,:-1,:-1] Eulers = grid_filters.coordinates0_node(steps,limits)[:-1,:-1,:-1]
Eulers = np.radians(Eulers) if not degrees else Eulers Eulers = np.radians(Eulers) if not degrees else Eulers
Eulers_r = Rotation.from_ODF(weights,Eulers.reshape(-1,3,order='F'),N,degrees).as_Euler_angles(True) Eulers_r = Rotation.from_ODF(weights,Eulers.reshape(-1,3,order='F'),N,degrees).as_Euler_angles(True)

View File

@ -155,8 +155,8 @@ class TestVTK:
cells = np.array([5,6,7],int) cells = np.array([5,6,7],int)
size = np.array([.6,1.,.5]) size = np.array([.6,1.,.5])
rectilinearGrid = VTK.from_rectilinear_grid(cells,size) rectilinearGrid = VTK.from_rectilinear_grid(cells,size)
c = grid_filters.cell_coord0(cells,size).reshape(-1,3,order='F') c = grid_filters.coordinates0_point(cells,size).reshape(-1,3,order='F')
n = grid_filters.node_coord0(cells,size).reshape(-1,3,order='F') n = grid_filters.coordinates0_node(cells,size).reshape(-1,3,order='F')
rectilinearGrid.add(c,'cell') rectilinearGrid.add(c,'cell')
rectilinearGrid.add(n,'node') rectilinearGrid.add(n,'node')
if update: if update:

View File

@ -5,33 +5,33 @@ from damask import grid_filters
class TestGridFilters: class TestGridFilters:
def test_cell_coord0(self): def test_coordinates0_point(self):
size = np.random.random(3) size = np.random.random(3)
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
coord = grid_filters.cell_coord0(cells,size) coord = grid_filters.coordinates0_point(cells,size)
assert np.allclose(coord[0,0,0],size/cells*.5) and coord.shape == tuple(cells) + (3,) assert np.allclose(coord[0,0,0],size/cells*.5) and coord.shape == tuple(cells) + (3,)
def test_node_coord0(self): def test_coordinates0_node(self):
size = np.random.random(3) size = np.random.random(3)
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
coord = grid_filters.node_coord0(cells,size) coord = grid_filters.coordinates0_node(cells,size)
assert np.allclose(coord[-1,-1,-1],size) and coord.shape == tuple(cells+1) + (3,) assert np.allclose(coord[-1,-1,-1],size) and coord.shape == tuple(cells+1) + (3,)
def test_coord0(self): def test_coord0(self):
size = np.random.random(3) size = np.random.random(3)
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
c = grid_filters.cell_coord0(cells+1,size+size/cells) c = grid_filters.coordinates0_point(cells+1,size+size/cells)
n = grid_filters.node_coord0(cells,size) + size/cells*.5 n = grid_filters.coordinates0_node(cells,size) + size/cells*.5
assert np.allclose(c,n) assert np.allclose(c,n)
@pytest.mark.parametrize('mode',['cell','node']) @pytest.mark.parametrize('mode',['point','node'])
def test_grid_DNA(self,mode): def test_grid_DNA(self,mode):
"""Ensure that xx_coord0_gridSizeOrigin is the inverse of xx_coord0.""" """Ensure that cellSizeOrigin_coordinates0_xx is the inverse of coordinates0_xx."""
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
size = np.random.random(3) size = np.random.random(3)
origin = np.random.random(3) origin = np.random.random(3)
coord0 = eval(f'grid_filters.{mode}_coord0(cells,size,origin)') # noqa coord0 = eval(f'grid_filters.coordinates0_{mode}(cells,size,origin)') # noqa
_cells,_size,_origin = eval(f'grid_filters.{mode}_coord0_gridSizeOrigin(coord0.reshape(-1,3,order="F"))') _cells,_size,_origin = eval(f'grid_filters.cellSizeOrigin_coordinates0_{mode}(coord0.reshape(-1,3,order="F"))')
assert np.allclose(cells,_cells) and np.allclose(size,_size) and np.allclose(origin,_origin) assert np.allclose(cells,_cells) and np.allclose(size,_size) and np.allclose(origin,_origin)
def test_displacement_fluct_equivalence(self): def test_displacement_fluct_equivalence(self):
@ -39,43 +39,43 @@ class TestGridFilters:
size = np.random.random(3) size = np.random.random(3)
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
F = np.random.random(tuple(cells)+(3,3)) F = np.random.random(tuple(cells)+(3,3))
assert np.allclose(grid_filters.node_displacement_fluct(size,F), assert np.allclose(grid_filters.displacement_fluct_node(size,F),
grid_filters.cell_2_node(grid_filters.cell_displacement_fluct(size,F))) grid_filters.point_2_node(grid_filters.displacement_fluct_point(size,F)))
def test_interpolation_to_node(self): def test_interpolation_to_node(self):
size = np.random.random(3) size = np.random.random(3)
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
F = np.random.random(tuple(cells)+(3,3)) F = np.random.random(tuple(cells)+(3,3))
assert np.allclose(grid_filters.node_coord(size,F) [1:-1,1:-1,1:-1], assert np.allclose(grid_filters.coordinates_node(size,F) [1:-1,1:-1,1:-1],
grid_filters.cell_2_node(grid_filters.cell_coord(size,F))[1:-1,1:-1,1:-1]) grid_filters.point_2_node(grid_filters.coordinates_point(size,F))[1:-1,1:-1,1:-1])
def test_interpolation_to_cell(self): def test_interpolation_to_cell(self):
cells = np.random.randint(1,30,(3)) cells = np.random.randint(1,30,(3))
node_coord_x = np.linspace(0,np.pi*2,num=cells[0]+1) coordinates_node_x = np.linspace(0,np.pi*2,num=cells[0]+1)
node_field_x = np.cos(node_coord_x) node_field_x = np.cos(coordinates_node_x)
node_field = np.broadcast_to(node_field_x.reshape(-1,1,1),cells+1) node_field = np.broadcast_to(node_field_x.reshape(-1,1,1),cells+1)
cell_coord_x = node_coord_x[:-1]+node_coord_x[1]*.5 coordinates0_point_x = coordinates_node_x[:-1]+coordinates_node_x[1]*.5
cell_field_x = np.interp(cell_coord_x,node_coord_x,node_field_x,period=np.pi*2.) cell_field_x = np.interp(coordinates0_point_x,coordinates_node_x,node_field_x,period=np.pi*2.)
cell_field = np.broadcast_to(cell_field_x.reshape(-1,1,1),cells) cell_field = np.broadcast_to(cell_field_x.reshape(-1,1,1),cells)
assert np.allclose(cell_field,grid_filters.node_2_cell(node_field)) assert np.allclose(cell_field,grid_filters.node_2_point(node_field))
@pytest.mark.parametrize('mode',['cell','node']) @pytest.mark.parametrize('mode',['point','node'])
def test_coord0_origin(self,mode): def test_coordinates0_origin(self,mode):
origin= np.random.random(3) origin= np.random.random(3)
size = np.random.random(3) # noqa size = np.random.random(3) # noqa
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
shifted = eval(f'grid_filters.{mode}_coord0(cells,size,origin)') shifted = eval(f'grid_filters.coordinates0_{mode}(cells,size,origin)')
unshifted = eval(f'grid_filters.{mode}_coord0(cells,size)') unshifted = eval(f'grid_filters.coordinates0_{mode}(cells,size)')
if mode == 'cell': if mode == 'cell':
assert np.allclose(shifted,unshifted+np.broadcast_to(origin,tuple(cells) +(3,))) assert np.allclose(shifted,unshifted+np.broadcast_to(origin,tuple(cells) +(3,)))
elif mode == 'node': elif mode == 'node':
assert np.allclose(shifted,unshifted+np.broadcast_to(origin,tuple(cells+1)+(3,))) assert np.allclose(shifted,unshifted+np.broadcast_to(origin,tuple(cells+1)+(3,)))
@pytest.mark.parametrize('function',[grid_filters.cell_displacement_avg, @pytest.mark.parametrize('function',[grid_filters.displacement_avg_point,
grid_filters.node_displacement_avg]) grid_filters.displacement_avg_node])
def test_displacement_avg_vanishes(self,function): def test_displacement_avg_vanishes(self,function):
"""Ensure that random fluctuations in F do not result in average displacement.""" """Ensure that random fluctuations in F do not result in average displacement."""
size = np.random.random(3) size = np.random.random(3)
@ -84,8 +84,8 @@ class TestGridFilters:
F += np.eye(3) - np.average(F,axis=(0,1,2)) F += np.eye(3) - np.average(F,axis=(0,1,2))
assert np.allclose(function(size,F),0.0) assert np.allclose(function(size,F),0.0)
@pytest.mark.parametrize('function',[grid_filters.cell_displacement_fluct, @pytest.mark.parametrize('function',[grid_filters.displacement_fluct_point,
grid_filters.node_displacement_fluct]) grid_filters.displacement_fluct_node])
def test_displacement_fluct_vanishes(self,function): def test_displacement_fluct_vanishes(self,function):
"""Ensure that constant F does not result in fluctuating displacement.""" """Ensure that constant F does not result in fluctuating displacement."""
size = np.random.random(3) size = np.random.random(3)
@ -93,16 +93,16 @@ class TestGridFilters:
F = np.broadcast_to(np.random.random((3,3)), tuple(cells)+(3,3)) F = np.broadcast_to(np.random.random((3,3)), tuple(cells)+(3,3))
assert np.allclose(function(size,F),0.0) assert np.allclose(function(size,F),0.0)
@pytest.mark.parametrize('function',[grid_filters.coord0_check, @pytest.mark.parametrize('function',[grid_filters.coordinates0_check,
grid_filters.node_coord0_gridSizeOrigin, grid_filters.cellSizeOrigin_coordinates0_node,
grid_filters.cell_coord0_gridSizeOrigin]) grid_filters.cellSizeOrigin_coordinates0_point])
def test_invalid_coordinates(self,function): def test_invalid_coordinates(self,function):
invalid_coordinates = np.random.random((np.random.randint(12,52),3)) invalid_coordinates = np.random.random((np.random.randint(12,52),3))
with pytest.raises(ValueError): with pytest.raises(ValueError):
function(invalid_coordinates) function(invalid_coordinates)
@pytest.mark.parametrize('function',[grid_filters.node_coord0_gridSizeOrigin, @pytest.mark.parametrize('function',[grid_filters.cellSizeOrigin_coordinates0_node,
grid_filters.cell_coord0_gridSizeOrigin]) grid_filters.cellSizeOrigin_coordinates0_point])
def test_uneven_spaced_coordinates(self,function): def test_uneven_spaced_coordinates(self,function):
start = np.random.random(3) start = np.random.random(3)
end = np.random.random(3)*10. + start end = np.random.random(3)*10. + start
@ -116,13 +116,13 @@ class TestGridFilters:
@pytest.mark.parametrize('mode',[True,False]) @pytest.mark.parametrize('mode',[True,False])
@pytest.mark.parametrize('function',[grid_filters.node_coord0_gridSizeOrigin, @pytest.mark.parametrize('function',[grid_filters.cellSizeOrigin_coordinates0_node,
grid_filters.cell_coord0_gridSizeOrigin]) grid_filters.cellSizeOrigin_coordinates0_point])
def test_unordered_coordinates(self,function,mode): def test_unordered_coordinates(self,function,mode):
origin = np.random.random(3) origin = np.random.random(3)
size = np.random.random(3)*10.+origin size = np.random.random(3)*10.+origin
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
unordered = grid_filters.node_coord0(cells,size,origin).reshape(-1,3) unordered = grid_filters.coordinates0_node(cells,size,origin).reshape(-1,3)
if mode: if mode:
with pytest.raises(ValueError): with pytest.raises(ValueError):
function(unordered,mode) function(unordered,mode)
@ -192,7 +192,7 @@ class TestGridFilters:
size = np.random.random(3)+1.0 size = np.random.random(3)+1.0
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
nodes = grid_filters.cell_coord0(cells,size) nodes = grid_filters.coordinates0_point(cells,size)
my_locals = locals() # needed for list comprehension my_locals = locals() # needed for list comprehension
field = np.stack([np.broadcast_to(eval(f,globals(),my_locals),cells) for f in field_def],axis=-1) field = np.stack([np.broadcast_to(eval(f,globals(),my_locals),cells) for f in field_def],axis=-1)
@ -252,7 +252,7 @@ class TestGridFilters:
size = np.random.random(3)+1.0 size = np.random.random(3)+1.0
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
nodes = grid_filters.cell_coord0(cells,size) nodes = grid_filters.coordinates0_point(cells,size)
my_locals = locals() # needed for list comprehension my_locals = locals() # needed for list comprehension
field = np.stack([np.broadcast_to(eval(f,globals(),my_locals),cells) for f in field_def],axis=-1) field = np.stack([np.broadcast_to(eval(f,globals(),my_locals),cells) for f in field_def],axis=-1)
@ -305,7 +305,7 @@ class TestGridFilters:
size = np.random.random(3)+1.0 size = np.random.random(3)+1.0
cells = np.random.randint(8,32,(3)) cells = np.random.randint(8,32,(3))
nodes = grid_filters.cell_coord0(cells,size) nodes = grid_filters.coordinates0_point(cells,size)
my_locals = locals() # needed for list comprehension my_locals = locals() # needed for list comprehension
field = np.stack([np.broadcast_to(eval(f,globals(),my_locals),cells) for f in field_def],axis=-1) field = np.stack([np.broadcast_to(eval(f,globals(),my_locals),cells) for f in field_def],axis=-1)

View File

@ -41,7 +41,7 @@ class TestSeeds:
def test_from_geom_grid(self,periodic,average): def test_from_geom_grid(self,periodic,average):
cells = np.random.randint(10,20,3) cells = np.random.randint(10,20,3)
size = np.ones(3) + np.random.random(3) size = np.ones(3) + np.random.random(3)
coords = grid_filters.cell_coord0(cells,size).reshape(-1,3) coords = grid_filters.coordinates0_point(cells,size).reshape(-1,3)
np.random.shuffle(coords) np.random.shuffle(coords)
geom_1 = Geom.from_Voronoi_tessellation(cells,size,coords) geom_1 = Geom.from_Voronoi_tessellation(cells,size,coords)
coords,material = seeds.from_geom(geom_1,average=average,periodic=periodic) coords,material = seeds.from_geom(geom_1,average=average,periodic=periodic)