[skip ci] changed almost all function definition lines to multiline for colormap, grid, table, vtk and util modules

This commit is contained in:
Daniel Otto de Mentock 2022-01-26 16:25:27 +01:00
parent e8c39077df
commit 0c21b6a8e0
5 changed files with 126 additions and 46 deletions

View File

@ -161,7 +161,8 @@ class Colormap(mpl.colors.ListedColormap):
@staticmethod @staticmethod
def from_predefined(name: str, N: int = 256) -> 'Colormap': def from_predefined(name: str,
N: int = 256) -> 'Colormap':
""" """
Select from a set of predefined colormaps. Select from a set of predefined colormaps.

View File

@ -101,7 +101,8 @@ class Grid:
return self._material return self._material
@material.setter @material.setter
def material(self, material: np.ndarray): def material(self,
material: np.ndarray):
if len(material.shape) != 3: if len(material.shape) != 3:
raise ValueError(f'invalid material shape {material.shape}') raise ValueError(f'invalid material shape {material.shape}')
elif material.dtype not in np.sctypes['float'] and material.dtype not in np.sctypes['int']: elif material.dtype not in np.sctypes['float'] and material.dtype not in np.sctypes['int']:
@ -120,7 +121,8 @@ class Grid:
return self._size return self._size
@size.setter @size.setter
def size(self, size: FloatSequence): def size(self,
size: FloatSequence):
if len(size) != 3 or any(np.array(size) < 0): if len(size) != 3 or any(np.array(size) < 0):
raise ValueError(f'invalid size {size}') raise ValueError(f'invalid size {size}')
else: else:
@ -132,7 +134,8 @@ class Grid:
return self._origin return self._origin
@origin.setter @origin.setter
def origin(self, origin: FloatSequence): def origin(self,
origin: FloatSequence):
if len(origin) != 3: if len(origin) != 3:
raise ValueError(f'invalid origin {origin}') raise ValueError(f'invalid origin {origin}')
else: else:
@ -144,7 +147,8 @@ class Grid:
return self._comments return self._comments
@comments.setter @comments.setter
def comments(self, comments: Union[str, Sequence[str]]): def comments(self,
comments: Union[str, Sequence[str]]):
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)]
@ -387,7 +391,9 @@ class Grid:
@staticmethod @staticmethod
def _find_closest_seed(seeds: np.ndarray, weights: np.ndarray, point: np.ndarray) -> np.integer: def _find_closest_seed(seeds: np.ndarray,
weights: np.ndarray,
point: np.ndarray) -> np.integer:
return np.argmin(np.sum((np.broadcast_to(point,(len(seeds),3))-seeds)**2,axis=1) - weights) return np.argmin(np.sum((np.broadcast_to(point,(len(seeds),3))-seeds)**2,axis=1) - weights)
@staticmethod @staticmethod
@ -624,7 +630,9 @@ class Grid:
) )
def save(self, fname: Union[str, Path], compress: bool = True): def save(self,
fname: Union[str, Path],
compress: bool = True):
""" """
Save as VTK image data file. Save as VTK image data file.
@ -643,7 +651,8 @@ class Grid:
v.save(fname,parallel=False,compress=compress) v.save(fname,parallel=False,compress=compress)
def save_ASCII(self, fname: Union[str, TextIO]): def save_ASCII(self,
fname: Union[str, TextIO]):
""" """
Save as geom file. Save as geom file.
@ -770,7 +779,9 @@ class Grid:
) )
def mirror(self, directions: Sequence[str], reflect: bool = False) -> 'Grid': def mirror(self,
directions: Sequence[str],
reflect: bool = False) -> 'Grid':
""" """
Mirror grid along given directions. Mirror grid along given directions.
@ -822,7 +833,9 @@ class Grid:
) )
def flip(self, directions: Union[Literal['x', 'y', 'z'], Sequence[Literal['x', 'y', 'z']]]) -> 'Grid': def flip(self,
directions: Union[Literal['x', 'y', 'z'],
Sequence[Literal['x', 'y', 'z']]]) -> 'Grid':
""" """
Flip grid along given directions. Flip grid along given directions.
@ -852,7 +865,9 @@ class Grid:
) )
def scale(self, cells: IntSequence, periodic: bool = True) -> 'Grid': def scale(self,
cells: IntSequence,
periodic: bool = True) -> 'Grid':
""" """
Scale grid to new cells. Scale grid to new cells.
@ -958,7 +973,9 @@ class Grid:
) )
def rotate(self, R: Rotation, fill: int = None) -> 'Grid': def rotate(self,
R: Rotation,
fill: int = None) -> 'Grid':
""" """
Rotate grid (pad if required). Rotate grid (pad if required).
@ -1049,7 +1066,9 @@ class Grid:
) )
def substitute(self, from_material: IntSequence, to_material: IntSequence) -> 'Grid': def substitute(self,
from_material: IntSequence,
to_material: IntSequence) -> 'Grid':
""" """
Substitute material indices. Substitute material indices.
@ -1150,7 +1169,9 @@ class Grid:
) )
def get_grain_boundaries(self, periodic: bool = True, directions: Sequence[str] = 'xyz'): def get_grain_boundaries(self,
periodic: bool = True,
directions: Sequence[str] = 'xyz'):
""" """
Create VTK unstructured grid containing grain boundaries. Create VTK unstructured grid containing grain boundaries.

View File

@ -12,7 +12,10 @@ from . import util
class Table: class Table:
"""Manipulate multi-dimensional spreadsheet-like data.""" """Manipulate multi-dimensional spreadsheet-like data."""
def __init__(self, data: np.ndarray, shapes: dict, comments: Union[str, list] = None): def __init__(self,
data: np.ndarray,
shapes: dict,
comments: Union[str, list] = None):
""" """
New spreadsheet. New spreadsheet.
@ -41,7 +44,8 @@ class Table:
return '\n'.join(['# '+c for c in self.comments])+'\n'+data_repr return '\n'.join(['# '+c for c in self.comments])+'\n'+data_repr
def __getitem__(self, item: Union[slice, Tuple[slice, ...]]) -> 'Table': def __getitem__(self,
item: Union[slice, Tuple[slice, ...]]) -> 'Table':
""" """
Slice the Table according to item. Slice the Table according to item.
@ -100,7 +104,9 @@ class Table:
copy = __copy__ copy = __copy__
def _label(self, what: Union[str, List[str]], how: str) -> List[str]: def _label(self,
what: Union[str, List[str]],
how: str) -> List[str]:
""" """
Expand labels according to data shape. Expand labels according to data shape.
@ -147,7 +153,10 @@ class Table:
self.data.columns = self._label(self.shapes,how) #type: ignore self.data.columns = self._label(self.shapes,how) #type: ignore
def _add_comment(self, label: str, shape: Tuple[int, ...], info: str = None): def _add_comment(self,
label: str,
shape: Tuple[int, ...],
info: str = None):
if info is not None: if info is not None:
specific = f'{label}{" "+str(shape) if np.prod(shape,dtype=int) > 1 else ""}: {info}' specific = f'{label}{" "+str(shape) if np.prod(shape,dtype=int) > 1 else ""}: {info}'
general = util.execution_stamp('Table') general = util.execution_stamp('Table')
@ -321,7 +330,8 @@ class Table:
return list(self.shapes) return list(self.shapes)
def get(self, label: str) -> np.ndarray: def get(self,
label: str) -> np.ndarray:
""" """
Get column data. Get column data.
@ -341,7 +351,10 @@ class Table:
return data.astype(type(data.flatten()[0])) return data.astype(type(data.flatten()[0]))
def set(self, label: str, data: np.ndarray, info: str = None) -> 'Table': def set(self,
label: str,
data: np.ndarray,
info: str = None) -> 'Table':
""" """
Set column data. Set column data.
@ -374,7 +387,10 @@ class Table:
return dup return dup
def add(self, label: str, data: np.ndarray, info: str = None) -> 'Table': def add(self,
label: str,
data: np.ndarray,
info: str = None) -> 'Table':
""" """
Add column data. Add column data.
@ -406,7 +422,8 @@ class Table:
return dup return dup
def delete(self, label: str) -> 'Table': def delete(self,
label: str) -> 'Table':
""" """
Delete column data. Delete column data.
@ -427,7 +444,10 @@ class Table:
return dup return dup
def rename(self, old: Union[str, List[str]], new: Union[str, List[str]], info: str = None) -> 'Table': def rename(self,
old: Union[str, List[str]],
new: Union[str, List[str]],
info: str = None) -> 'Table':
""" """
Rename column data. Rename column data.
@ -453,7 +473,9 @@ class Table:
return dup return dup
def sort_by(self, labels: Union[str, List[str]], ascending: Union[bool, List[bool]] = True) -> 'Table': def sort_by(self,
labels: Union[str, List[str]],
ascending: Union[bool, List[bool]] = True) -> 'Table':
""" """
Sort table by values of given labels. Sort table by values of given labels.
@ -486,7 +508,8 @@ class Table:
return dup return dup
def append(self, other: 'Table') -> 'Table': def append(self,
other: 'Table') -> 'Table':
""" """
Append other table vertically (similar to numpy.vstack). Append other table vertically (similar to numpy.vstack).
@ -511,7 +534,8 @@ class Table:
return dup return dup
def join(self, other: 'Table') -> 'Table': def join(self,
other: 'Table') -> 'Table':
""" """
Append other table horizontally (similar to numpy.hstack). Append other table horizontally (similar to numpy.hstack).
@ -538,7 +562,8 @@ class Table:
return dup return dup
def save(self, fname: FileHandle): def save(self,
fname: FileHandle):
""" """
Save as plain text file. Save as plain text file.

View File

@ -22,7 +22,8 @@ class VTK:
High-level interface to VTK. High-level interface to VTK.
""" """
def __init__(self, vtk_data: vtk.vtkDataSet): def __init__(self,
vtk_data: vtk.vtkDataSet):
""" """
New spatial visualization. New spatial visualization.
@ -38,7 +39,9 @@ class VTK:
@staticmethod @staticmethod
def from_image_data(cells: IntSequence, size: FloatSequence, origin: FloatSequence = np.zeros(3)) -> 'VTK': def from_image_data(cells: IntSequence,
size: FloatSequence,
origin: FloatSequence = np.zeros(3)) -> 'VTK':
""" """
Create VTK of type vtk.vtkImageData. Create VTK of type vtk.vtkImageData.
@ -68,7 +71,9 @@ class VTK:
@staticmethod @staticmethod
def from_rectilinear_grid(grid: np.ndarray, size: FloatSequence, origin: FloatSequence = np.zeros(3)) -> 'VTK': def from_rectilinear_grid(grid: np.ndarray,
size: FloatSequence,
origin: FloatSequence = np.zeros(3)) -> 'VTK':
""" """
Create VTK of type vtk.vtkRectilinearGrid. Create VTK of type vtk.vtkRectilinearGrid.
@ -100,7 +105,9 @@ class VTK:
@staticmethod @staticmethod
def from_unstructured_grid(nodes: np.ndarray, connectivity: np.ndarray, cell_type: str) -> 'VTK': def from_unstructured_grid(nodes: np.ndarray,
connectivity: np.ndarray,
cell_type: str) -> 'VTK':
""" """
Create VTK of type vtk.vtkUnstructuredGrid. Create VTK of type vtk.vtkUnstructuredGrid.
@ -238,7 +245,11 @@ class VTK:
def _write(writer): def _write(writer):
"""Wrapper for parallel writing.""" """Wrapper for parallel writing."""
writer.Write() writer.Write()
def save(self, fname: Union[str, Path], parallel: bool = True, compress: bool = True):
def save(self,
fname: Union[str, Path],
parallel: bool = True,
compress: bool = True):
""" """
Save as VTK file. Save as VTK file.
@ -284,7 +295,9 @@ class VTK:
# Check https://blog.kitware.com/ghost-and-blanking-visibility-changes/ for missing data # Check https://blog.kitware.com/ghost-and-blanking-visibility-changes/ for missing data
# Needs support for damask.Table # Needs support for damask.Table
def add(self, data: Union[np.ndarray, np.ma.MaskedArray], label: str = None): def add(self,
data: Union[np.ndarray, np.ma.MaskedArray],
label: str = None):
""" """
Add data to either cells or points. Add data to either cells or points.
@ -331,7 +344,8 @@ class VTK:
raise TypeError raise TypeError
def get(self, label: str) -> np.ndarray: def get(self,
label: str) -> np.ndarray:
""" """
Get either cell or point data. Get either cell or point data.
@ -383,7 +397,8 @@ class VTK:
return [] return []
def set_comments(self, comments: Union[str, List[str]]): def set_comments(self,
comments: Union[str, List[str]]):
""" """
Set comments. Set comments.
@ -400,7 +415,8 @@ class VTK:
self.vtk_data.GetFieldData().AddArray(s) self.vtk_data.GetFieldData().AddArray(s)
def add_comments(self, comments: Union[str, List[str]]): def add_comments(self,
comments: Union[str, List[str]]):
""" """
Add comments. Add comments.

View File

@ -54,7 +54,8 @@ _colors = {
#################################################################################################### ####################################################################################################
# Functions # Functions
#################################################################################################### ####################################################################################################
def srepr(msg, glue: str = '\n') -> str: def srepr(msg,
glue: str = '\n') -> str:
r""" r"""
Join items with glue string. Join items with glue string.
@ -148,7 +149,10 @@ def strikeout(msg) -> str:
return _colors['crossout']+srepr(msg)+_colors['end_color'] return _colors['crossout']+srepr(msg)+_colors['end_color']
def run(cmd: str, wd: str = './', env: Dict[str, str] = None, timeout: int = None) -> Tuple[str, str]: def run(cmd: str,
wd: str = './',
env: Dict[str, str] = None,
timeout: int = None) -> Tuple[str, str]:
""" """
Run a command. Run a command.
@ -373,14 +377,17 @@ def project_equal_area(vector: np.ndarray,
return np.roll(np.block([v[...,:2]/np.sqrt(1.0+np.abs(v[...,2:3])),np.zeros_like(v[...,2:3])]), return np.roll(np.block([v[...,:2]/np.sqrt(1.0+np.abs(v[...,2:3])),np.zeros_like(v[...,2:3])]),
-shift if keepdims else 0,axis=-1)[...,:3 if keepdims else 2] -shift if keepdims else 0,axis=-1)[...,:3 if keepdims else 2]
def execution_stamp(class_name: str, function_name: str = None) -> str: def execution_stamp(class_name: str,
function_name: str = None) -> str:
"""Timestamp the execution of a (function within a) class.""" """Timestamp the execution of a (function within a) class."""
now = datetime.datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S%z') now = datetime.datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S%z')
_function_name = '' if function_name is None else f'.{function_name}' _function_name = '' if function_name is None else f'.{function_name}'
return f'damask.{class_name}{_function_name} v{version} ({now})' return f'damask.{class_name}{_function_name} v{version} ({now})'
def hybrid_IA(dist: np.ndarray, N: int, rng_seed = None) -> np.ndarray: def hybrid_IA(dist: np.ndarray,
N: int,
rng_seed = None) -> np.ndarray:
""" """
Hybrid integer approximation. Hybrid integer approximation.
@ -473,7 +480,8 @@ def shapeshifter(fro: Tuple[int, ...],
return fill[:-1] return fill[:-1]
def shapeblender(a: Tuple[int, ...], b: Tuple[int, ...]) -> Tuple[int, ...]: def shapeblender(a: Tuple[int, ...],
b: Tuple[int, ...]) -> Tuple[int, ...]:
""" """
Return a shape that overlaps the rightmost entries of 'a' with the leftmost of 'b'. Return a shape that overlaps the rightmost entries of 'a' with the leftmost of 'b'.
@ -517,7 +525,8 @@ def extend_docstring(extra_docstring: str) -> Callable:
return _decorator return _decorator
def extended_docstring(f: Callable, extra_docstring: str) -> Callable: def extended_docstring(f: Callable,
extra_docstring: str) -> Callable:
""" """
Decorator: Combine another function's docstring with a given docstring. Decorator: Combine another function's docstring with a given docstring.
@ -593,7 +602,9 @@ def DREAM3D_cell_data_group(fname: Union[str, Path]) -> str:
return cell_data_group return cell_data_group
def Bravais_to_Miller(*, uvtw: np.ndarray = None, hkil: np.ndarray = None) -> np.ndarray: def Bravais_to_Miller(*,
uvtw: np.ndarray = None,
hkil: np.ndarray = None) -> np.ndarray:
""" """
Transform 4 MillerBravais indices to 3 Miller indices of crystal direction [uvw] or plane normal (hkl). Transform 4 MillerBravais indices to 3 Miller indices of crystal direction [uvw] or plane normal (hkl).
@ -620,7 +631,9 @@ def Bravais_to_Miller(*, uvtw: np.ndarray = None, hkil: np.ndarray = None) -> np
return np.einsum('il,...l',basis,axis) return np.einsum('il,...l',basis,axis)
def Miller_to_Bravais(*, uvw: np.ndarray = None, hkl: np.ndarray = None) -> np.ndarray: def Miller_to_Bravais(*,
uvw: np.ndarray = None,
hkl: np.ndarray = None) -> np.ndarray:
""" """
Transform 3 Miller indices to 4 MillerBravais indices of crystal direction [uvtw] or plane normal (hkil). Transform 3 Miller indices to 4 MillerBravais indices of crystal direction [uvtw] or plane normal (hkil).
@ -710,7 +723,10 @@ class ProgressBar:
Works for 0-based loops, ETA is estimated by linear extrapolation. Works for 0-based loops, ETA is estimated by linear extrapolation.
""" """
def __init__(self, total: int, prefix: str, bar_length: int): def __init__(self,
total: int,
prefix: str,
bar_length: int):
""" """
Set current time as basis for ETA estimation. Set current time as basis for ETA estimation.
@ -733,7 +749,8 @@ class ProgressBar:
sys.stderr.write(f"{self.prefix} {''*self.bar_length} 0% ETA n/a") sys.stderr.write(f"{self.prefix} {''*self.bar_length} 0% ETA n/a")
sys.stderr.flush() sys.stderr.flush()
def update(self, iteration: int) -> None: def update(self,
iteration: int) -> None:
fraction = (iteration+1) / self.total fraction = (iteration+1) / self.total
filled_length = int(self.bar_length * fraction) filled_length = int(self.bar_length * fraction)