shortened __repr__ code

This commit is contained in:
Philip Eisenlohr 2022-02-23 08:37:23 -05:00
parent 77e57a268c
commit 5882a8560c
3 changed files with 76 additions and 82 deletions

View File

@ -120,10 +120,11 @@ class Orientation(Rotation,Crystal):
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human readable summary.""" """Give short human-readable summary."""
return '\n'.join([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.""" """Create deep copy."""

View File

@ -88,7 +88,7 @@ class Rotation:
def __repr__(self) -> str: def __repr__(self) -> str:
"""Give short human readable summary.""" """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)

View File

@ -38,6 +38,33 @@ class VTK:
self.vtk_data = vtk_data self.vtk_data = vtk_data
def __repr__(self) -> str:
"""Give short human-readable summary."""
info = [self.vtk_data.__vtkname__]
for data in ['Cell Data', 'Point Data']:
if data == 'Cell Data': info.append(f'\n# cells: {self.N_cells}')
if data == 'Point Data': info.append(f'\n# points: {self.N_points}')
if data in self.labels:
info += [f' - {l}' for l in self.labels[data]]
return util.srepr(info)
def __eq__(self,
other: object) -> bool:
"""
Equal to other.
Parameters
----------
other : damask.VTK
VTK to compare self against.
"""
return self.as_ASCII() == other.as_ASCII() if isinstance(other, VTK) else NotImplemented
def copy(self): def copy(self):
if isinstance(self.vtk_data,vtk.vtkImageData): if isinstance(self.vtk_data,vtk.vtkImageData):
dup = vtk.vtkImageData() dup = vtk.vtkImageData()
@ -55,16 +82,47 @@ class VTK:
return VTK(dup) return VTK(dup)
@property
def comments(self) -> List[str]:
"""Return the comments."""
fielddata = self.vtk_data.GetFieldData()
for a in range(fielddata.GetNumberOfArrays()):
if fielddata.GetArrayName(a) == 'comments':
comments = fielddata.GetAbstractArray(a)
return [comments.GetValue(i) for i in range(comments.GetNumberOfValues())]
return []
@comments.setter
def comments(self,
comments: Union[str, Sequence[str]]):
"""
Set comments.
Parameters
----------
comments : str or list of str
Comments.
"""
s = vtk.vtkStringArray()
s.SetName('comments')
for c in util.tail_repack(comments,self.comments):
s.InsertNextValue(c)
self.vtk_data.GetFieldData().AddArray(s)
@property @property
def N_points(self) -> int: def N_points(self) -> int:
"""Number of points in vtkdata.""" """Number of points in vtkdata."""
return self.vtk_data.GetNumberOfPoints() return self.vtk_data.GetNumberOfPoints()
@property @property
def N_cells(self) -> int: def N_cells(self) -> int:
"""Number of cells in vtkdata.""" """Number of cells in vtkdata."""
return self.vtk_data.GetNumberOfCells() return self.vtk_data.GetNumberOfCells()
@property @property
def labels(self): def labels(self):
"""Labels of datasets.""" """Labels of datasets."""
@ -80,6 +138,7 @@ class VTK:
return labels return labels
@staticmethod @staticmethod
def from_image_data(cells: IntSequence, def from_image_data(cells: IntSequence,
size: FloatSequence, size: FloatSequence,
@ -280,6 +339,17 @@ class VTK:
"""Wrapper for parallel writing.""" """Wrapper for parallel writing."""
writer.Write() writer.Write()
def as_ASCII(self) -> str:
"""ASCII representation of the VTK data."""
writer = vtk.vtkDataSetWriter()
writer.SetHeader(f'# {util.execution_stamp("VTK")}')
writer.WriteToOutputStringOn()
writer.SetInputData(self.vtk_data)
writer.Write()
return writer.GetOutputString()
def save(self, def save(self,
fname: Union[str, Path], fname: Union[str, Path],
parallel: bool = True, parallel: bool = True,
@ -350,7 +420,7 @@ class VTK:
N_data = data.shape[0] N_data = data.shape[0]
data_ = data.reshape(N_data,-1)\ data_ = data.reshape(N_data,-1) \
.astype(np.single if data.dtype in [np.double,np.longdouble] else data.dtype) .astype(np.single if data.dtype in [np.double,np.longdouble] else data.dtype)
if data.dtype.type is np.str_: if data.dtype.type is np.str_:
@ -429,83 +499,6 @@ class VTK:
raise ValueError(f'array "{label}" not found') raise ValueError(f'array "{label}" not found')
@property
def comments(self) -> List[str]:
"""Return the comments."""
fielddata = self.vtk_data.GetFieldData()
for a in range(fielddata.GetNumberOfArrays()):
if fielddata.GetArrayName(a) == 'comments':
comments = fielddata.GetAbstractArray(a)
return [comments.GetValue(i) for i in range(comments.GetNumberOfValues())]
return []
@comments.setter
def comments(self,
comments: Union[str, Sequence[str]]):
"""
Set comments.
Parameters
----------
comments : str or list of str
Comments.
"""
s = vtk.vtkStringArray()
s.SetName('comments')
for c in util.tail_repack(comments,self.comments):
s.InsertNextValue(c)
self.vtk_data.GetFieldData().AddArray(s)
def __repr__(self) -> str:
"""Give short human-readable summary."""
info = []
if isinstance(self.vtk_data,vtk.vtkImageData):
info.append('vtkImageData')
elif isinstance(self.vtk_data,vtk.vtkUnstructuredGrid):
info.append('vtkUnstructuredGrid')
elif isinstance(self.vtk_data,vtk.vtkPolyData):
info.append('vtkPolyData')
elif isinstance(self.vtk_data,vtk.vtkRectilinearGrid):
info.append('vtkRectilinearGrid')
for data in ['Cell Data', 'Point Data']:
if data == 'Cell Data': info.append(f'\n# cells: {self.N_cells}')
if data == 'Point Data': info.append(f'\n# points: {self.N_points}')
if data in self.labels:
info.append(f'with {data}:')
info += self.labels[data]
return util.srepr(info)
def __eq__(self,
other: object) -> bool:
"""
Test equality of other.
Parameters
----------
other : damask.VTK
VTK to compare self against.
"""
if not isinstance(other, VTK):
return NotImplemented
return self.as_ASCII() == other.as_ASCII()
def as_ASCII(self) -> str:
"""ASCII representation of the VTK data."""
writer = vtk.vtkDataSetWriter()
writer.SetHeader(f'# {util.execution_stamp("VTK")}')
writer.WriteToOutputStringOn()
writer.SetInputData(self.vtk_data)
writer.Write()
return writer.GetOutputString()
def show(self, def show(self,
label: str = None, label: str = None,
colormap: Colormap = Colormap.from_predefined('cividis')): colormap: Colormap = Colormap.from_predefined('cividis')):