def from_rectilinearGrid(grid, size, origin=np.zeros(3)): """ Create VTK of type vtk.vtkRectilinearGrid. This is the common type for results from the grid solver. Parameters ---------- grid : numpy.ndarray of shape (3) of np.dtype = int Number of cells. size : numpy.ndarray of shape (3) Physical length. origin : numpy.ndarray of shape (3), optional Spatial origin. """ geom = vtk.vtkRectilinearGrid() geom.SetDimensions(*(grid + 1)) geom.SetXCoordinates( np_to_vtk(np.linspace(origin[0], origin[0] + size[0], grid[0] + 1), deep=True)) geom.SetYCoordinates( np_to_vtk(np.linspace(origin[1], origin[1] + size[1], grid[1] + 1), deep=True)) geom.SetZCoordinates( np_to_vtk(np.linspace(origin[2], origin[2] + size[2], grid[2] + 1), deep=True)) return VTK(geom)
def add(self, data: Union[np.ndarray, np.ma.MaskedArray], label: str = None): """ Add data to either cells or points. Parameters ---------- data : numpy.ndarray or numpy.ma.MaskedArray Data to add. First dimension needs to match either number of cells or number of points. label : str Data label. """ N_points = self.vtk_data.GetNumberOfPoints() N_cells = self.vtk_data.GetNumberOfCells() if isinstance(data, np.ndarray): if label is None: raise ValueError('No label defined for numpy.ndarray') N_data = data.shape[0] data_ = (data if not isinstance(data, np.ma.MaskedArray) else np.where(data.mask, data.fill_value, data)).reshape( N_data, -1) if data_.dtype in [np.double, np.longdouble]: d = np_to_vtk(data_.astype(np.single), deep=True) # avoid large files elif data_.dtype.type is np.str_: d = vtk.vtkStringArray() for s in np.squeeze(data_): d.InsertNextValue(s) else: d = np_to_vtk(data_, deep=True) d.SetName(label) if N_data == N_points: self.vtk_data.GetPointData().AddArray(d) elif N_data == N_cells: self.vtk_data.GetCellData().AddArray(d) else: raise ValueError( f'Cell / point count ({N_cells} / {N_points}) differs from data ({N_data}).' ) elif isinstance(data, Table): raise NotImplementedError('damask.Table') else: raise TypeError
def from_unstructuredGrid(nodes, connectivity, cell_type): """ Create VTK of type vtk.vtkUnstructuredGrid. This is the common type for results from FEM solvers. Parameters ---------- nodes : numpy.ndarray of shape (:,3) Spatial position of the nodes. connectivity : numpy.ndarray of np.dtype = int Cell connectivity (0-based), first dimension determines #Cells, second dimension determines #Nodes/Cell. cell_type : str Name of the vtk.vtkCell subclass. Tested for TRIANGLE, QUAD, TETRA, and HEXAHEDRON. """ vtk_nodes = vtk.vtkPoints() vtk_nodes.SetData(np_to_vtk(nodes)) cells = vtk.vtkCellArray() cells.SetNumberOfCells(connectivity.shape[0]) T = np.concatenate((np.ones( (connectivity.shape[0], 1), dtype=np.int64) * connectivity.shape[1], connectivity), axis=1).ravel() cells.SetCells(connectivity.shape[0], np_to_vtkIdTypeArray(T, deep=True)) geom = vtk.vtkUnstructuredGrid() geom.SetPoints(vtk_nodes) geom.SetCells( eval('vtk.VTK_{}'.format(cell_type.split('_', 1)[-1].upper())), cells) return VTK(geom)
def test_invalid_spacing(self,tmp_path,default): default.save(tmp_path/'spacing_ok.vtr') vtk = VTK.load(tmp_path/'spacing_ok.vtr') vtk.vtk_data.SetXCoordinates(np_to_vtk(np.sort(np.random.random(default.cells[0])))) vtk.save(tmp_path/'invalid_spacing.vtr',parallel=False) with pytest.raises(ValueError): Grid.load(tmp_path/'invalid_spacing.vtr')
def from_poly_data(points): """ Create VTK of type vtk.polyData. This is the common type for point-wise data. Parameters ---------- points : numpy.ndarray of shape (:,3) Spatial position of the points. """ N = points.shape[0] vtk_points = vtk.vtkPoints() vtk_points.SetData(np_to_vtk(points)) vtk_cells = vtk.vtkCellArray() vtk_cells.SetNumberOfCells(N) vtk_cells.SetCells(N,np_to_vtkIdTypeArray(np.stack((np.ones (N,dtype=np.int64), np.arange(N,dtype=np.int64)),axis=1).ravel(),deep=True)) vtk_data = vtk.vtkPolyData() vtk_data.SetPoints(vtk_points) vtk_data.SetVerts(vtk_cells) return VTK(vtk_data)
def from_rectilinear_grid(grid,size,origin=np.zeros(3)): """ Create VTK of type vtk.vtkRectilinearGrid. This is the common type for grid solver results. Parameters ---------- grid : iterable of int, len (3) Number of cells along each dimension. size : iterable of float, len (3) Physical lengths along each dimension. origin : iterable of float, len (3), optional Spatial origin coordinates. """ vtk_data = vtk.vtkRectilinearGrid() vtk_data.SetDimensions(*(np.array(grid)+1)) coord = [np_to_vtk(np.linspace(origin[i],origin[i]+size[i],grid[i]+1),deep=True) for i in [0,1,2]] [coord[i].SetName(n) for i,n in enumerate(['x','y','z'])] vtk_data.SetXCoordinates(coord[0]) vtk_data.SetYCoordinates(coord[1]) vtk_data.SetZCoordinates(coord[2]) return VTK(vtk_data)
def from_poly_data(points: np.ndarray) -> 'VTK': """ Create VTK of type vtk.polyData. This is the common type for point-wise data. Parameters ---------- points : numpy.ndarray of shape (:,3) Spatial position of the points. Returns ------- new : damask.VTK VTK-based geometry without nodal or cell data. """ N = points.shape[0] vtk_points = vtk.vtkPoints() vtk_points.SetData(np_to_vtk(np.ascontiguousarray(points))) vtk_cells = vtk.vtkCellArray() vtk_cells.SetNumberOfCells(N) vtk_cells.SetCells( N, np_to_vtkIdTypeArray(np.stack( (np.ones(N, dtype=np.int64), np.arange(N, dtype=np.int64)), axis=1).ravel(), deep=True)) vtk_data = vtk.vtkPolyData() vtk_data.SetPoints(vtk_points) vtk_data.SetVerts(vtk_cells) return VTK(vtk_data)
def from_rectilinear_grid(grid, size, origin=np.zeros(3)): """ Create VTK of type vtk.vtkRectilinearGrid. Parameters ---------- grid : iterable of int, len (3) Number of cells along each dimension. size : iterable of float, len (3) Physical length along each dimension. origin : iterable of float, len (3), optional Coordinates of grid origin. Returns ------- new : damask.VTK VTK-based geometry without nodal or cell data. """ warnings.warn('Support for vtr files will be removed in DAMASK 3.1.0', DeprecationWarning, 2) vtk_data = vtk.vtkRectilinearGrid() vtk_data.SetDimensions(*(np.array(grid) + 1)) coord = [ np_to_vtk(np.linspace(origin[i], origin[i] + size[i], grid[i] + 1), deep=True) for i in [0, 1, 2] ] [coord[i].SetName(n) for i, n in enumerate(['x', 'y', 'z'])] vtk_data.SetXCoordinates(coord[0]) vtk_data.SetYCoordinates(coord[1]) vtk_data.SetZCoordinates(coord[2]) return VTK(vtk_data)
def from_unstructured_grid(nodes: np.ndarray, connectivity: np.ndarray, cell_type: str) -> 'VTK': """ Create VTK of type vtk.vtkUnstructuredGrid. This is the common type for mesh solver results. Parameters ---------- nodes : numpy.ndarray of shape (:,3) Spatial position of the nodes. connectivity : numpy.ndarray of np.dtype = int Cell connectivity (0-based), first dimension determines #Cells, second dimension determines #Nodes/Cell. cell_type : str Name of the vtk.vtkCell subclass. Tested for TRIANGLE, QUAD, TETRA, and HEXAHEDRON. Returns ------- new : damask.VTK VTK-based geometry without nodal or cell data. """ vtk_nodes = vtk.vtkPoints() vtk_nodes.SetData(np_to_vtk(np.ascontiguousarray(nodes))) cells = vtk.vtkCellArray() cells.SetNumberOfCells(connectivity.shape[0]) T = np.concatenate((np.ones( (connectivity.shape[0], 1), dtype=np.int64) * connectivity.shape[1], connectivity), axis=1).ravel() cells.SetCells(connectivity.shape[0], np_to_vtkIdTypeArray(T, deep=True)) vtk_data = vtk.vtkUnstructuredGrid() vtk_data.SetPoints(vtk_nodes) cell_types = { 'TRIANGLE': vtk.VTK_TRIANGLE, 'QUAD': vtk.VTK_QUAD, 'TETRA': vtk.VTK_TETRA, 'HEXAHEDRON': vtk.VTK_HEXAHEDRON } vtk_data.SetCells(cell_types[cell_type.split("_", 1)[-1].upper()], cells) return VTK(vtk_data)
def from_polyData(points): """ Create VTK of type vtk.polyData. This is the common type for point-wise data. Parameters ---------- points : numpy.ndarray of shape (:,3) Spatial position of the points. """ vtk_points = vtk.vtkPoints() vtk_points.SetData(np_to_vtk(points)) geom = vtk.vtkPolyData() geom.SetPoints(vtk_points) return VTK(geom)
def add(self, data, label=None): """Add data to either cells or points.""" N_points = self.geom.GetNumberOfPoints() N_cells = self.geom.GetNumberOfCells() if isinstance(data, np.ndarray): d = np_to_vtk(num_array=data.reshape(data.shape[0], -1), deep=True) if label is None: raise ValueError('No label defined for numpy.ndarray') d.SetName(label) if data.shape[0] == N_cells: self.geom.GetCellData().AddArray(d) elif data.shape[0] == N_points: self.geom.GetPointData().AddArray(d) elif isinstance(data, pd.DataFrame): raise NotImplementedError('pd.DataFrame') elif isinstance(data, Table): raise NotImplementedError('damask.Table') else: raise TypeError
def add(self,data,label=None): """ Add data to either cells or points. Parameters ---------- data : numpy.ndarray Data to add. First dimension needs to match either number of cells or number of points. label : str Data label. """ N_points = self.vtk_data.GetNumberOfPoints() N_cells = self.vtk_data.GetNumberOfCells() if isinstance(data,np.ndarray): if label is None: raise ValueError('No label defined for numpy.ndarray') N_data = data.shape[0] d = np_to_vtk((data.astype(np.float32) if data.dtype in [np.float64, np.float128] else data).reshape(N_data,-1),deep=True) # avoid large files d.SetName(label) if N_data == N_points: self.vtk_data.GetPointData().AddArray(d) elif N_data == N_cells: self.vtk_data.GetCellData().AddArray(d) else: raise ValueError(f'Cell / point count ({N_cells} / {N_points}) differs from data ({N_data}).') elif isinstance(data,pd.DataFrame): raise NotImplementedError('pd.DataFrame') elif isinstance(data,Table): raise NotImplementedError('damask.Table') else: raise TypeError