Merge branch 'python-polishing' into 'development'

python polishing

See merge request damask/DAMASK!528
This commit is contained in:
Philip Eisenlohr 2022-02-17 20:23:54 +00:00
commit 41389963a7
9 changed files with 63 additions and 60 deletions

View File

@ -144,10 +144,9 @@ class Config(dict):
Configuration from file.
"""
if isinstance(fname, (str, Path)):
fhandle = open(fname)
else:
fhandle = fname
fhandle = open(fname) if isinstance(fname, (str, Path)) else \
fname
return cls(yaml.safe_load(fhandle))
def save(self,
@ -164,10 +163,8 @@ class Config(dict):
Keyword arguments parsed to yaml.dump.
"""
if isinstance(fname, (str, Path)):
fhandle = open(fname,'w',newline='\n')
else:
fhandle = fname
fhandle = open(fname,'w',newline='\n') if isinstance(fname, (str, Path)) else \
fname
if 'width' not in kwargs:
kwargs['width'] = 256

View File

@ -334,10 +334,10 @@ class Crystal():
"""
if (direction is not None) ^ (plane is None):
raise KeyError('specify either "direction" or "plane"')
axis,basis = (np.array(direction),self.basis_reciprocal.T) \
if plane is None else \
(np.array(plane),self.basis_real.T)
return np.einsum('il,...l',basis,axis)
basis,axis = (self.basis_reciprocal,np.array(direction)) \
if plane is None else \
(self.basis_real,np.array(plane))
return np.einsum('li,...l',basis,axis)
def to_frame(self, *,
@ -359,9 +359,9 @@ class Crystal():
"""
if (uvw is not None) ^ (hkl is None):
raise KeyError('specify either "uvw" or "hkl"')
axis,basis = (np.array(uvw),self.basis_real) \
if hkl is None else \
(np.array(hkl),self.basis_reciprocal)
basis,axis = (self.basis_real,np.array(uvw)) \
if hkl is None else \
(self.basis_reciprocal,np.array(hkl))
return np.einsum('il,...l',basis,axis)

View File

@ -63,8 +63,8 @@ class Grid:
mat_N = self.N_materials
return util.srepr([
f'cells: {util.srepr(self.cells, " × ")}',
f'size: {util.srepr(self.size, " × ")} / ',
f'origin: {util.srepr(self.origin," ")} / m',
f'size: {util.srepr(self.size, " × ")} ',
f'origin: {util.srepr(self.origin," ")} m',
f'# materials: {mat_N}' + ('' if mat_min == 0 and mat_max+1 == mat_N else
f' (min: {mat_min}, max: {mat_max})')
])
@ -182,7 +182,7 @@ class Grid:
Grid-based geometry from file.
"""
v = VTK.load(fname if str(fname).endswith(('.vti','.vtr')) else str(fname)+'.vti') # compatibility hack
v = VTK.load(fname if str(fname).endswith('.vti') else str(fname)+'.vti')
comments = v.get_comments()
cells = np.array(v.vtk_data.GetDimensions())-1
bbox = np.array(v.vtk_data.GetBounds()).reshape(3,2).T
@ -603,8 +603,8 @@ class Grid:
>>> import damask
>>> damask.Grid.from_minimal_surface([64]*3,np.ones(3)*1.e-4,'Gyroid')
cells : 64 x 64 x 64
size : 0.0001 x 0.0001 x 0.0001 /
origin: 0.0 0.0 0.0 / m
size : 0.0001 x 0.0001 x 0.0001
origin: 0.0 0.0 0.0 m
# materials: 2
Minimal surface of 'Neovius' type. non-default material IDs.
@ -614,8 +614,8 @@ class Grid:
>>> damask.Grid.from_minimal_surface([80]*3,np.ones(3)*5.e-4,
... 'Neovius',materials=(1,5))
cells : 80 x 80 x 80
size : 0.0005 x 0.0005 x 0.0005 /
origin: 0.0 0.0 0.0 / m
size : 0.0005 x 0.0005 x 0.0005
origin: 0.0 0.0 0.0 m
# materials: 2 (min: 1, max: 5)
"""
@ -735,8 +735,8 @@ class Grid:
>>> g = damask.Grid(np.zeros([64]*3,int), np.ones(3)*1e-4)
>>> g.add_primitive(np.ones(3)*5e-5,np.ones(3)*5e-5,1)
cells : 64 x 64 x 64
size : 0.0001 x 0.0001 x 0.0001 /
origin: 0.0 0.0 0.0 / m
size : 0.0001 x 0.0001 x 0.0001
origin: 0.0 0.0 0.0 m
# materials: 2
Add a cube at the origin.
@ -746,8 +746,8 @@ class Grid:
>>> g = damask.Grid(np.zeros([64]*3,int), np.ones(3)*1e-4)
>>> g.add_primitive(np.ones(3,int)*32,np.zeros(3),np.inf)
cells : 64 x 64 x 64
size : 0.0001 x 0.0001 x 0.0001 /
origin: 0.0 0.0 0.0 / m
size : 0.0001 x 0.0001 x 0.0001
origin: 0.0 0.0 0.0 m
# materials: 2
"""
@ -805,8 +805,8 @@ class Grid:
>>> g = damask.Grid(np.zeros([32]*3,int), np.ones(3)*1e-4)
>>> g.mirror('xy',True)
cells : 64 x 64 x 32
size : 0.0002 x 0.0002 x 0.0001 /
origin: 0.0 0.0 0.0 / m
size : 0.0002 x 0.0002 x 0.0001
origin: 0.0 0.0 0.0 m
# materials: 1
"""
@ -886,8 +886,8 @@ class Grid:
>>> g = damask.Grid(np.zeros([32]*3,int),np.ones(3)*1e-4)
>>> g.scale(g.cells*2)
cells : 64 x 64 x 64
size : 0.0001 x 0.0001 x 0.0001 /
origin: 0.0 0.0 0.0 / m
size : 0.0001 x 0.0001 x 0.0001
origin: 0.0 0.0 0.0 m
# materials: 1
"""
@ -1036,8 +1036,8 @@ class Grid:
>>> g = damask.Grid(np.zeros([32]*3,int),np.ones(3)*1e-4)
>>> g.canvas([32,32,16])
cells : 33 x 32 x 16
size : 0.0001 x 0.0001 x 5e-05 /
origin: 0.0 0.0 0.0 / m
size : 0.0001 x 0.0001 x 5e-05
origin: 0.0 0.0 0.0 m
# materials: 1
"""

View File

@ -168,17 +168,21 @@ class Result:
def __repr__(self):
"""Show summary of file content."""
with h5py.File(self.fname,'r') as f:
header = [f'Created by {f.attrs["creator"]}',
f' on {f.attrs["created"]}',
f' executing "{f.attrs["call"]}"']
visible_increments = self.visible['increments']
first = self.view(increments=visible_increments[0:1]).list_data()
last = '' if len(visible_increments) < 2 else \
last = [] if len(visible_increments) < 2 else \
self.view(increments=visible_increments[-1:]).list_data()
in_between = '' if len(visible_increments) < 3 else \
''.join([f'\n{inc}\n ...\n' for inc in visible_increments[1:-1]])
in_between = [] if len(visible_increments) < 3 else \
[f'\n{inc}\n ...' for inc in visible_increments[1:-1]]
return util.srepr(first + in_between + last)
return util.srepr([util.deemph(header)] + first + in_between + last)
def _manage_view(self,action,what,datasets):
@ -537,24 +541,32 @@ class Result:
def list_data(self):
"""Return information on all active datasets in the file."""
msg = ''
"""
Collect information on all active datasets in the file.
Returns
-------
data : list of str
Line-formatted information about active datasets.
"""
msg = []
with h5py.File(self.fname,'r') as f:
for inc in self.visible['increments']:
msg = ''.join([msg,f'\n{inc} ({self.times[self.increments.index(inc)]}s)\n'])
msg += [f'\n{inc} ({self.times[self.increments.index(inc)]} s)']
for ty in ['phase','homogenization']:
msg = ' '.join([msg,f'{ty}\n'])
msg += [f' {ty}']
for label in self.visible[ty+'s']:
msg = ' '.join([msg,f'{label}\n'])
msg += [f' {label}']
for field in _match(self.visible['fields'],f['/'.join([inc,ty,label])].keys()):
msg = ' '.join([msg,f'{field}\n'])
msg += [f' {field}']
for d in f['/'.join([inc,ty,label,field])].keys():
dataset = f['/'.join([inc,ty,label,field,d])]
unit = f' / {dataset.attrs["unit"]}' if h5py3 else \
f' / {dataset.attrs["unit"].decode()}'
unit = dataset.attrs["unit"] if h5py3 else \
dataset.attrs["unit"].decode()
description = dataset.attrs['description'] if h5py3 else \
dataset.attrs['description'].decode()
msg = ' '.join([msg,f'{d}{unit}: {description}\n'])
msg += [f' {d} / {unit}: {description}']
return msg

View File

@ -1567,11 +1567,7 @@ class Rotation:
+0.000059719705868660826, -0.00001980756723965647,
+0.000003953714684212874, -0.00000036555001439719544])
hmag_squared = np.sum(ho**2.,axis=-1,keepdims=True)
hm = hmag_squared.copy()
s = tfit[0] + tfit[1] * hmag_squared
for i in range(2,16):
hm *= hmag_squared
s += tfit[i] * hm
s = np.sum(tfit*hmag_squared**np.arange(len(tfit)),axis=-1,keepdims=True)
with np.errstate(invalid='ignore'):
ax = np.where(np.broadcast_to(np.abs(hmag_squared)<1.e-8,ho.shape[:-1]+(4,)),
[ 0.0, 0.0, 1.0, 0.0 ],

View File

@ -263,10 +263,8 @@ class Table:
f.seek(0)
comments = []
line = f.readline().strip()
while line.startswith('#'):
while (line := f.readline().strip()).startswith('#'):
comments.append(line.lstrip('#').strip())
line = f.readline().strip()
labels = line.split()
shapes = {}

View File

@ -763,7 +763,7 @@ class ProgressBar:
fraction = (iteration+1) / self.total
if filled_length := int(self.bar_length * fraction) > int(self.bar_length * self.fraction_last) or \
if (filled_length := int(self.bar_length * fraction)) > int(self.bar_length * self.fraction_last) or \
datetime.datetime.now() - self.time_last_update > datetime.timedelta(seconds=10):
self.time_last_update = datetime.datetime.now()
bar = '' * filled_length + '' * (self.bar_length - filled_length)

View File

@ -313,13 +313,13 @@ def ho2ax(ho):
if iszero(hmag_squared):
ax = np.array([ 0.0, 0.0, 1.0, 0.0 ])
else:
hm = hmag_squared
hm = np.ones_like(hmag_squared)
# convert the magnitude to the rotation angle
s = tfit[0] + tfit[1] * hmag_squared
for i in range(2,16):
s = 0.0
for t in tfit:
s += t * hm
hm *= hmag_squared
s += tfit[i] * hm
ax = np.append(ho/np.sqrt(hmag_squared),2.0*np.arccos(np.clip(s,-1.0,1.0)))
return ax

View File

@ -97,8 +97,8 @@ subroutine discretization_grid_init(restart)
if (err_MPI /= 0_MPI_INTEGER_KIND) error stop 'MPI error'
print'(/,1x,a,i0,a,i0,a,i0)', 'cells: ', cells(1), ' × ', cells(2), ' × ', cells(3)
print '(1x,a,es8.2,a,es8.2,a,es8.2,a)', 'size: ', geomSize(1), ' × ', geomSize(2), ' × ', geomSize(3), ' / m³'
print '(1x,a,es8.2,a,es8.2,a,es8.2,a)', 'origin: ', origin(1), ' ', origin(2), ' ', origin(3), ' / m'
print '(1x,a,es8.2,a,es8.2,a,es8.2,a)', 'size: ', geomSize(1), ' × ', geomSize(2), ' × ', geomSize(3), ' m³'
print '(1x,a,es8.2,a,es8.2,a,es8.2,a)', 'origin: ', origin(1), ' ', origin(2), ' ', origin(3), ' m'
if (worldsize>cells(3)) call IO_error(894, ext_msg='number of processes exceeds cells(3)')