Merge branch 'magic_methods_default_docstrings' into 'development'

Added standard magic method descriptions to magic methods

Closes #112

See merge request damask/DAMASK!606
This commit is contained in:
Daniel Otto de Mentock 2022-08-10 15:35:56 +00:00
commit 66f129273c
9 changed files with 203 additions and 36 deletions

View File

@ -48,7 +48,12 @@ class Colormap(mpl.colors.ListedColormap):
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
"""Test equality of colormaps.""" """
Return self==other.
Test equality of other.
"""
if not isinstance(other, Colormap): if not isinstance(other, Colormap):
return NotImplemented return NotImplemented
return len(self.colors) == len(other.colors) \ return len(self.colors) == len(other.colors) \
@ -56,31 +61,61 @@ class Colormap(mpl.colors.ListedColormap):
def __add__(self, def __add__(self,
other: 'Colormap') -> 'Colormap': other: 'Colormap') -> 'Colormap':
"""Concatenate.""" """
Return self+other.
Concatenate.
"""
return Colormap(np.vstack((self.colors,other.colors)), return Colormap(np.vstack((self.colors,other.colors)),
f'{self.name}+{other.name}') f'{self.name}+{other.name}')
def __iadd__(self, def __iadd__(self,
other: 'Colormap') -> 'Colormap': other: 'Colormap') -> 'Colormap':
"""Concatenate (in-place).""" """
Return self+=other.
Concatenate (in-place).
"""
return self.__add__(other) return self.__add__(other)
def __mul__(self, def __mul__(self,
factor: int) -> 'Colormap': factor: int) -> 'Colormap':
"""Repeat.""" """
Return self*other.
Repeat.
"""
return Colormap(np.vstack([self.colors]*factor),f'{self.name}*{factor}') return Colormap(np.vstack([self.colors]*factor),f'{self.name}*{factor}')
def __imul__(self, def __imul__(self,
factor: int) -> 'Colormap': factor: int) -> 'Colormap':
"""Repeat (in-place).""" """
Return self*=other.
Repeat (in-place).
"""
return self.__mul__(factor) return self.__mul__(factor)
def __invert__(self) -> 'Colormap': def __invert__(self) -> 'Colormap':
"""Reverse.""" """
Return ~self.
Reverse.
"""
return self.reversed() return self.reversed()
def __repr__(self) -> str: def __repr__(self) -> str:
"""Show as matplotlib figure.""" """
Return repr(self).
Show as matplotlib figure.
"""
fig = plt.figure(self.name,figsize=(5,.5)) fig = plt.figure(self.name,figsize=(5,.5))
ax1 = fig.add_axes([0, 0, 1, 1]) ax1 = fig.add_axes([0, 0, 1, 1])
ax1.set_axis_off() ax1.set_axis_off()

View File

@ -64,7 +64,12 @@ class Config(dict):
super().__init__(**kwargs) super().__init__(**kwargs)
def __repr__(self) -> str: def __repr__(self) -> str:
"""Show as in file.""" """
Return repr(self).
Show as in file.
"""
output = StringIO() output = StringIO()
self.save(output) self.save(output)
output.seek(0) output.seek(0)
@ -72,7 +77,12 @@ class Config(dict):
def __copy__(self: MyType) -> MyType: def __copy__(self: MyType) -> MyType:
"""Create deep copy.""" """
Return deepcopy(self).
Create deep copy.
"""
return copy.deepcopy(self) return copy.deepcopy(self)
copy = __copy__ copy = __copy__
@ -81,6 +91,8 @@ class Config(dict):
def __or__(self: MyType, def __or__(self: MyType,
other) -> MyType: other) -> MyType:
""" """
Return self|other.
Update configuration with contents of other. Update configuration with contents of other.
Parameters Parameters
@ -105,7 +117,12 @@ class Config(dict):
def __ior__(self: MyType, def __ior__(self: MyType,
other) -> MyType: other) -> MyType:
"""Update configuration with contents of other.""" """
Return self|=other.
Update configuration with contents of other.
"""
return self.__or__(other) return self.__or__(other)

View File

@ -403,7 +403,12 @@ class Crystal():
def __repr__(self): def __repr__(self):
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
family = f'Crystal family: {self.family}' family = f'Crystal family: {self.family}'
return family if self.lattice is None else \ return family if self.lattice is None else \
util.srepr([family, util.srepr([family,
@ -415,7 +420,9 @@ class Crystal():
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
""" """
Equal to other. Return self==other.
Test equality of other.
Parameters Parameters
---------- ----------

View File

@ -62,7 +62,12 @@ class Grid:
self.comments = [] if comments_ is None else [str(c) for c in comments_] self.comments = [] if comments_ is None else [str(c) for c in comments_]
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
mat_min = np.nanmin(self.material) mat_min = np.nanmin(self.material)
mat_max = np.nanmax(self.material) mat_max = np.nanmax(self.material)
mat_N = self.N_materials mat_N = self.N_materials
@ -76,7 +81,12 @@ class Grid:
def __copy__(self) -> 'Grid': def __copy__(self) -> 'Grid':
"""Create deep copy.""" """
Return deepcopy(self).
Create deep copy.
"""
return copy.deepcopy(self) return copy.deepcopy(self)
copy = __copy__ copy = __copy__
@ -85,6 +95,8 @@ class Grid:
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
""" """
Return self==other.
Test equality of other. Test equality of other.
Parameters Parameters

View File

@ -120,14 +120,24 @@ class Orientation(Rotation,Crystal):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
return util.srepr([Crystal.__repr__(self), return util.srepr([Crystal.__repr__(self),
Rotation.__repr__(self)]) Rotation.__repr__(self)])
def __copy__(self: MyType, def __copy__(self: MyType,
rotation: Union[FloatSequence, Rotation] = None) -> MyType: rotation: Union[FloatSequence, Rotation] = None) -> MyType:
"""Create deep copy.""" """
Return deepcopy(self).
Create deep copy.
"""
dup = copy.deepcopy(self) dup = copy.deepcopy(self)
if rotation is not None: if rotation is not None:
dup.quaternion = Rotation(rotation).quaternion dup.quaternion = Rotation(rotation).quaternion
@ -140,7 +150,9 @@ class Orientation(Rotation,Crystal):
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
""" """
Equal to other. Return self==other.
Test equality of other.
Parameters Parameters
---------- ----------
@ -158,7 +170,9 @@ class Orientation(Rotation,Crystal):
def __ne__(self, def __ne__(self,
other: object) -> bool: other: object) -> bool:
""" """
Not equal to other. Return self!=other.
Test inequality of other.
Parameters Parameters
---------- ----------

View File

@ -152,14 +152,24 @@ class Result:
def __copy__(self) -> "Result": def __copy__(self) -> "Result":
"""Create deep copy.""" """
Return deepcopy(self).
Create deep copy.
"""
return copy.deepcopy(self) return copy.deepcopy(self)
copy = __copy__ copy = __copy__
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
with h5py.File(self.fname,'r') as f: with h5py.File(self.fname,'r') as f:
header = [f'Created by {f.attrs["creator"]}', header = [f'Created by {f.attrs["creator"]}',
f' on {f.attrs["created"]}', f' on {f.attrs["created"]}',

View File

@ -88,14 +88,24 @@ class Rotation:
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
return f'Quaternion{" " if self.quaternion.shape == (4,) else "s of shape "+str(self.quaternion.shape[:-1])+chr(10)}'\ return f'Quaternion{" " if self.quaternion.shape == (4,) else "s of shape "+str(self.quaternion.shape[:-1])+chr(10)}'\
+ str(self.quaternion) + str(self.quaternion)
def __copy__(self: MyType, def __copy__(self: MyType,
rotation: Union[FloatSequence, 'Rotation'] = None) -> MyType: rotation: Union[FloatSequence, 'Rotation'] = None) -> MyType:
"""Create deep copy.""" """
Return deepcopy(self).
Create deep copy.
"""
dup = copy.deepcopy(self) dup = copy.deepcopy(self)
if rotation is not None: if rotation is not None:
dup.quaternion = Rotation(rotation).quaternion dup.quaternion = Rotation(rotation).quaternion
@ -106,7 +116,12 @@ class Rotation:
def __getitem__(self, def __getitem__(self,
item: Union[Tuple[int], int, bool, np.bool_, np.ndarray]): item: Union[Tuple[int], int, bool, np.bool_, np.ndarray]):
"""Return slice according to item.""" """
Return self[item].
Return slice according to item.
"""
return self.copy() if self.shape == () else \ return self.copy() if self.shape == () else \
self.copy(self.quaternion[item+(slice(None),)] if isinstance(item,tuple) else self.quaternion[item]) self.copy(self.quaternion[item+(slice(None),)] if isinstance(item,tuple) else self.quaternion[item])
@ -114,7 +129,9 @@ class Rotation:
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
""" """
Equal to other. Return self==other.
Test equality of other.
Parameters Parameters
---------- ----------
@ -130,7 +147,9 @@ class Rotation:
def __ne__(self, def __ne__(self,
other: object) -> bool: other: object) -> bool:
""" """
Not equal to other. Return self!=other.
Test inequality of other.
Parameters Parameters
---------- ----------
@ -214,12 +233,22 @@ class Rotation:
def __len__(self) -> int: def __len__(self) -> int:
"""Length of leading/leftmost dimension of array.""" """
Return len(self).
Length of leading/leftmost dimension of array.
"""
return 0 if self.shape == () else self.shape[0] return 0 if self.shape == () else self.shape[0]
def __invert__(self: MyType) -> MyType: def __invert__(self: MyType) -> MyType:
"""Inverse rotation (backward rotation).""" """
Return ~self.
Inverse rotation (backward rotation).
"""
dup = self.copy() dup = self.copy()
dup.quaternion[...,1:] *= -1 dup.quaternion[...,1:] *= -1
return dup return dup
@ -228,6 +257,8 @@ class Rotation:
def __pow__(self: MyType, def __pow__(self: MyType,
exp: Union[float, int]) -> MyType: exp: Union[float, int]) -> MyType:
""" """
Return self**exp.
Perform the rotation 'exp' times. Perform the rotation 'exp' times.
Parameters Parameters
@ -243,6 +274,8 @@ class Rotation:
def __ipow__(self: MyType, def __ipow__(self: MyType,
exp: Union[float, int]) -> MyType: exp: Union[float, int]) -> MyType:
""" """
Return self**=exp.
Perform the rotation 'exp' times (in-place). Perform the rotation 'exp' times (in-place).
Parameters Parameters
@ -257,6 +290,8 @@ class Rotation:
def __mul__(self: MyType, def __mul__(self: MyType,
other: MyType) -> MyType: other: MyType) -> MyType:
""" """
Return self*other.
Compose with other. Compose with other.
Parameters Parameters
@ -284,6 +319,8 @@ class Rotation:
def __imul__(self: MyType, def __imul__(self: MyType,
other: MyType) -> MyType: other: MyType) -> MyType:
""" """
Return self*=other.
Compose with other (in-place). Compose with other (in-place).
Parameters Parameters
@ -298,6 +335,8 @@ class Rotation:
def __truediv__(self: MyType, def __truediv__(self: MyType,
other: MyType) -> MyType: other: MyType) -> MyType:
""" """
Return self/other.
Compose with inverse of other. Compose with inverse of other.
Parameters Parameters
@ -319,6 +358,8 @@ class Rotation:
def __itruediv__(self: MyType, def __itruediv__(self: MyType,
other: MyType) -> MyType: other: MyType) -> MyType:
""" """
Return self/=other.
Compose with inverse of other (in-place). Compose with inverse of other (in-place).
Parameters Parameters
@ -333,7 +374,9 @@ class Rotation:
def __matmul__(self, def __matmul__(self,
other: np.ndarray) -> np.ndarray: other: np.ndarray) -> np.ndarray:
""" """
Rotate vector, second order tensor, or fourth order tensor. Return self@other.
Rotate vector, second-order tensor, or fourth-order tensor.
Parameters Parameters
---------- ----------
@ -365,7 +408,7 @@ class Rotation:
R = self.as_matrix() R = self.as_matrix()
return np.einsum('...im,...jn,...ko,...lp,...mnop',R,R,R,R,other) return np.einsum('...im,...jn,...ko,...lp,...mnop',R,R,R,R,other)
else: else:
raise ValueError('can only rotate vectors, 2nd order tensors, and 4th order tensors') raise ValueError('can only rotate vectors, second-order tensors, and fourth-order tensors')
elif isinstance(other, Rotation): elif isinstance(other, Rotation):
raise TypeError('use "R1*R2", i.e. multiplication, to compose rotations "R1" and "R2"') raise TypeError('use "R1*R2", i.e. multiplication, to compose rotations "R1" and "R2"')
else: else:

View File

@ -37,7 +37,12 @@ class Table:
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
self._relabel('shapes') self._relabel('shapes')
data_repr = self.data.__repr__() data_repr = self.data.__repr__()
self._relabel('uniform') self._relabel('uniform')
@ -46,7 +51,12 @@ class Table:
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
"""Compare to other Table.""" """
Return self==other.
Test equality of other.
"""
return NotImplemented if not isinstance(other,Table) else \ return NotImplemented if not isinstance(other,Table) else \
self.shapes == other.shapes and self.data.equals(other.data) self.shapes == other.shapes and self.data.equals(other.data)
@ -54,7 +64,9 @@ class Table:
def __getitem__(self, def __getitem__(self,
item: Union[slice, Tuple[slice, ...]]) -> 'Table': item: Union[slice, Tuple[slice, ...]]) -> 'Table':
""" """
Slice the Table according to item. Return self[item].
Return slice according to item.
Parameters Parameters
---------- ----------
@ -102,12 +114,22 @@ class Table:
def __len__(self) -> int: def __len__(self) -> int:
"""Number of rows.""" """
Return len(self).
Number of rows.
"""
return len(self.data) return len(self.data)
def __copy__(self) -> 'Table': def __copy__(self) -> 'Table':
"""Create deep copy.""" """
Return deepcopy(self).
Create deep copy.
"""
return copy.deepcopy(self) return copy.deepcopy(self)
copy = __copy__ copy = __copy__

View File

@ -39,7 +39,12 @@ class VTK:
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human-readable summary.""" """
Return repr(self).
Give short human-readable summary.
"""
info = [self.vtk_data.__vtkname__] info = [self.vtk_data.__vtkname__]
for data in ['Cell Data', 'Point Data']: for data in ['Cell Data', 'Point Data']:
@ -54,7 +59,9 @@ class VTK:
def __eq__(self, def __eq__(self,
other: object) -> bool: other: object) -> bool:
""" """
Equal to other. Return self==other.
Test equality of other.
Parameters Parameters
---------- ----------