centralizing functionality

This commit is contained in:
Martin Diehl 2020-03-11 23:54:36 +01:00
parent 575da581a9
commit bb2019810a
3 changed files with 63 additions and 91 deletions

View File

@ -1,14 +1,11 @@
import os
import sys
from io import StringIO
import numpy as np
from scipy import ndimage
import vtk
from vtk.util import numpy_support
from . import VTK
from . import util
from . import version
class Geom():
@ -384,36 +381,12 @@ class Geom():
"""
v = VTK.from_rectilinearGrid(self.grid,self.size,self.origin)
rGrid = v.geom
v.add(self.microstructure.flatten(order='F'),'microstructure')
ms = numpy_support.numpy_to_vtk(num_array=self.microstructure.flatten(order='F'),
array_type=vtk.VTK_INT if self.microstructure.dtype == int else vtk.VTK_FLOAT)
ms.SetName('microstructure')
rGrid.GetCellData().AddArray(ms)
if fname is None:
writer = vtk.vtkDataSetWriter()
writer.SetHeader('damask.Geom '+version)
writer.WriteToOutputStringOn()
if fname:
v.write(fname)
else:
writer = vtk.vtkXMLRectilinearGridWriter()
writer.SetCompressorTypeToZLib()
writer.SetDataModeToBinary()
ext = os.path.splitext(fname)[1]
if ext == '':
name = fname + '.' + writer.GetDefaultFileExtension()
elif ext[1:] == writer.GetDefaultFileExtension():
name = fname
else:
raise ValueError("unknown extension {}".format(ext))
writer.SetFileName(name)
writer.SetInputData(rGrid)
writer.Write()
if not fname: return writer.GetOutputString()
sys.stdout.write(v.__repr__())
def show(self):

View File

@ -77,8 +77,40 @@ class VTK: # capitals needed/preferred?
return VTK(geom)
@staticmethod
def from_file(fname,ftype=None):
ext = os.path.splitext(fname)[1]
if ext == '.vtk':
reader = vtk.vtkGenericDataObjectReader()
reader.SetFileName(fname)
reader.Update()
if ftype.lower() == 'rectilineargrid':
geom = reader.GetRectilinearGridOutput()
elif ftype.lower() == 'unstructuredgrid':
geom = reader.GetUnstructuredGridOutput()
elif ftype.lower() == 'polydata':
geom = reader.GetPolyDataOutput()
else:
raise Exception
else:
if ext == '.vtr':
reader = vtk.vtkXMLRectilinearGridReader()
elif ext == '.vtu':
reader = vtk.vtkXMLUnstructuredGridReader()
elif ext == '.vtp':
reader = vtk.vtkXMLPolyDataReader()
else:
raise Exception
def write(self,fname): #ToDo: Discuss how to handle consistently filename extensions
reader.SetFileName(fname)
reader.Update()
geom = reader.GetOutput()
return VTK(geom)
def write(self,fname):
"""ToDo: Check if given fileextension makes sense."""
if (isinstance(self.geom,vtk.vtkRectilinearGrid)):
writer = vtk.vtkXMLRectilinearGridWriter()
elif(isinstance(self.geom,vtk.vtkUnstructuredGrid)):
@ -95,9 +127,19 @@ class VTK: # capitals needed/preferred?
writer.Write()
def add(data,label=None):
def add(self,data,label=None):
Npoints = self.geom.GetNumberOfPoints()
Ncells = self.geom.GetNumberOfCells()
if isinstance(data,np.ndarray):
pass
shape = [data.shape[0],np.product(data.shape[1:],dtype=np.int)]
d = nps.numpy_to_vtk(num_array=data.reshape(shape),deep=True)
d.SetName(label)
if shape[0] == Ncells:
self.geom.GetCellData().AddArray(d)
elif shape[0] == Npoints:
self.geom.GetPointData().AddArray(d)
elif isinstance(data,pd.DataFrame):
pass
elif isinstance(data,table):

View File

@ -4,8 +4,6 @@ import glob
import os
from functools import partial
import vtk
from vtk.util import numpy_support
import h5py
import numpy as np
@ -77,10 +75,9 @@ class Result:
self.mat_physics = list(set(self.mat_physics)) # make unique
self.selection= {'increments': self.increments,
'constituents': self.constituents,
'materialpoints': self.materialpoints,
'con_physics': self.con_physics,
'mat_physics': self.mat_physics}
'constituents': self.constituents,'materialpoints': self.materialpoints,
'con_physics': self.con_physics, 'mat_physics': self.mat_physics
}
self.fname = fname
@ -231,15 +228,6 @@ class Result:
"""
self._manage_selection('del',what,datasets)
# def createGeometry4VTK():
# """ reads geometry and fummels... to return VTK.XXXobject (pointcloud fallback)"""
# myVTK = new
# myVTK.geom = result.getGeom()
# myVTK.table/data = result.spatiocondense(['f','p']) # of type damask.Table
# myVTK.writeme
# def datamerger(regular expression to filter groups into one copy)
@ -1050,12 +1038,9 @@ class Result:
elif mode.lower()=='point':
v = VTK.from_polyData(self.cell_coordinates())
vtk_geom = v.geom
N_digits = int(np.floor(np.log10(int(self.increments[-1][3:]))))+1
N_digits = int(np.floor(np.log10(min(int(self.increments[-1][3:]),1))))+1
for i,inc in enumerate(self.iterate('increments')):
vtk_data = []
materialpoints_backup = self.selection['materialpoints'].copy()
self.pick('materialpoints',False)
@ -1067,23 +1052,15 @@ class Result:
if len(x) == 0:
continue
array = self.read_dataset(x,0)
shape = [array.shape[0],np.product(array.shape[1:])]
vtk_data.append(numpy_support.numpy_to_vtk(num_array=array.reshape(shape),deep=True))
vtk_data[-1].SetName('1_'+x[0].split('/',1)[1]) #ToDo: hard coded 1!
vtk_geom.GetCellData().AddArray(vtk_data[-1])
v.add(array,'1_'+x[0].split('/',1)[1]) #ToDo: hard coded 1!
else:
x = self.get_dataset_location(label)
if len(x) == 0:
continue
array = self.read_dataset(x,0)
shape = [array.shape[0],np.product(array.shape[1:])]
vtk_data.append(numpy_support.numpy_to_vtk(num_array=array.reshape(shape),deep=True))
ph_name = re.compile(r'(?<=(constituent\/))(.*?)(?=(generic))') # identify phase name
dset_name = '1_' + re.sub(ph_name,r'',x[0].split('/',1)[1]) # removing phase name
vtk_data[-1].SetName(dset_name)
vtk_geom.GetCellData().AddArray(vtk_data[-1])
v.add(array,dset_name)
self.pick('materialpoints',materialpoints_backup)
constituents_backup = self.selection['constituents'].copy()
@ -1096,43 +1073,23 @@ class Result:
if len(x) == 0:
continue
array = self.read_dataset(x,0)
shape = [array.shape[0],np.product(array.shape[1:])]
vtk_data.append(numpy_support.numpy_to_vtk(num_array=array.reshape(shape),deep=True))
vtk_data[-1].SetName('1_'+x[0].split('/',1)[1]) #ToDo: why 1_?
vtk_geom.GetCellData().AddArray(vtk_data[-1])
v.add(array,'1_'+x[0].split('/',1)[1]) #ToDo: why 1_?
else:
x = self.get_dataset_location(label)
if len(x) == 0:
continue
array = self.read_dataset(x,0)
shape = [array.shape[0],np.product(array.shape[1:])]
vtk_data.append(numpy_support.numpy_to_vtk(num_array=array.reshape(shape),deep=True))
vtk_data[-1].SetName('1_'+x[0].split('/',1)[1])
vtk_geom.GetCellData().AddArray(vtk_data[-1])
v.add(array,'1_'+x[0].split('/',1)[1])
self.pick('constituents',constituents_backup)
if mode.lower()=='cell':
writer = vtk.vtkXMLRectilinearGridWriter() if self.structured else \
vtk.vtkXMLUnstructuredGridWriter()
x = self.get_dataset_location('u_n')
vtk_data.append(numpy_support.numpy_to_vtk(num_array=self.read_dataset(x,0),deep=True))
vtk_data[-1].SetName('u')
vtk_geom.GetPointData().AddArray(vtk_data[-1])
elif mode.lower()=='point':
writer = vtk.vtkXMLPolyDataWriter()
u = self.read_dataset(self.get_dataset_location('u_n'))
v.add(u,'u')
file_out = '{}_inc{}'.format(os.path.splitext(os.path.basename(self.fname))[0],
inc[3:].zfill(N_digits))
file_out = '{}_inc{}.{}'.format(os.path.splitext(os.path.basename(self.fname))[0],
inc[3:].zfill(N_digits),
writer.GetDefaultFileExtension())
writer.SetCompressorTypeToZLib()
writer.SetDataModeToBinary()
writer.SetFileName(file_out)
writer.SetInputData(vtk_geom)
writer.Write()
v.write(file_out)
###################################################################################################
# BEGIN DEPRECATED