def get_results(self) -> List[Any]: print(self) #txyz = self.VALUE[:, :3].copy() txyz = self.VALUE assert txyz.shape[1] == 3, txyz.shape txyz_array = numpy_to_vtk(txyz, deep=1, array_type=None) return [self.name], [txyz_array]
def set_mass_grid(alt_grids: Dict[str, vtk.vtkUnstructuredGrid], model: BDF, nodes, node_ids) -> None: #nmass = len(model.masses) #eid_array = np.full(nmass, -1, dtype='int32') #mass_array = np.full(nmass, np.nan, dtype='float32') #xyz_array = np.full((nmass, 3), np.nan, dtype='float32') i = 0 eids = [] mass = [] xyz = [] mass_grid = vtk.vtkUnstructuredGrid() for eid, element in model.masses.items(): if element.type == 'CONM2': nid = element.nid inid = np.searchsorted(node_ids, nid) xyz_nid = nodes[inid, :] centroid = element.offset(xyz_nid) #eid_array[i] = eid #mass_array[i] = element.mass #xyz_array[i, :] = centroid eids.append(eid) mass.append(element.mass) xyz.append(centroid) vtk_elem = vtk.vtkVertex() vtk_elem.GetPointIds().SetId(0, inid) mass_grid.InsertNextCell(vtk_elem.GetCellType(), vtk_elem.GetPointIds()) else: model.log.debug(f'skipping:\n{str(elem)}') continue i += 1 eid_array = np.array(eids, dtype='int32')[:i] mass_array = np.array(mass, dtype='float32')[:i] xyz_array = np.array(xyz, dtype='float32')[:i, :] vtk_points = numpy_to_vtk_points(xyz_array, points=None, dtype='<f', deep=1) mass_grid.SetPoints(vtk_points) # add vectors vtk_eids = numpy_to_vtk(eid_array, deep=0, array_type=None) vtk_mass = numpy_to_vtk(mass_array, deep=0, array_type=None) vtk_eids.SetName('Mass ID') vtk_mass.SetName('Mass') #point_data = mass_grid.GetPointData() cell_data = mass_grid.GetCellData() cell_data.AddArray(vtk_mass) alt_grids['mass'] = mass_grid
def _elements_to_vtk(vtk_ugrid: vtk.vtkUnstructuredGrid, etype_nids: np.ndarray, cell_offsets_array: np.ndarray, cell_types_array: np.ndarray): # Create the array of cells nelements = len(cell_offsets_array) cells_id_type = numpy_to_vtkIdTypeArray(etype_nids, deep=1) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(nelements, cells_id_type) # Cell types deep = False vtk_cell_types = numpy_to_vtk( cell_types_array, deep=deep, array_type=vtk.vtkUnsignedCharArray().GetDataType()) vtk_cell_offsets = numpy_to_vtk(cell_offsets_array, deep=deep, array_type=vtk.VTK_ID_TYPE) #grid = vtk.vtkUnstructuredGrid() vtk_ugrid.SetCells(vtk_cell_types, vtk_cell_offsets, vtk_cells)
def get_results(self) -> List[Any]: print(self) isort = self.eids.argsort() eids_sorted = self.eids[isort] isort_EID = self.EID.argsort() i = isort[isort_EID] #txyz = self.VALUE[:, :3].copy() names = [f'{self.name}: {header}' for header in self.headers()] results = [ numpy_to_vtk(arrayi, deep=1, array_type=None) for arrayi in (self.ENERGY, self.PERCENT, self.DENSITY) ] return names, results
def numpy_to_vtk_points(nodes, points=None, dtype='<f', deep=1): """common method to account for vtk endian quirks and efficiently adding points""" assert isinstance(nodes, np.ndarray), type(nodes) if points is None: points = vtk.vtkPoints() nnodes = nodes.shape[0] points.SetNumberOfPoints(nnodes) # if we're in big endian, VTK won't work, so we byte swap nodes = np.asarray(nodes, dtype=np.dtype(dtype)) points_array = numpy_to_vtk( num_array=nodes, deep=deep, array_type=vtk.VTK_FLOAT, ) points.SetData(points_array) return points
def fill_vtk_unstructured_grid(geom_model: BDF, vtk_ugrid: vtk.vtkUnstructuredGrid, add_property=True, add_material=True): #cell_type_point = 1 # vtk.vtkVertex().GetCellType() #cell_type_line = 3 # vtk.vtkLine().GetCellType() #cell_type_tri3 = 5 #cell_type_tri6 = 22 #cell_type_quad4 = 9 #cell_type_quad8 = 23 #cell_type_tetra4 = 10 #cell_type_tetra10 = 24 #cell_type_pyram5 = 14 # vtk.vtkPyramid().GetCellType() #cell_type_pyram13 = 27 # vtk.vtkQuadraticPyramid().GetCellType() #cell_type_hexa8 = 12 #cell_type_hexa20 = 25 #cell_type_penta6 = 13 #cell_type_penta15 = 26 #nodes, node_ids, nid_map, idtype = _load_nodes(geom_model) nodes = geom_model._nodes node_ids = geom_model._node_ids #nid_map = geom_model._nid_map idtype = geom_model._idtype vtk_points = numpy_to_vtk_points(nodes, points=None, dtype='<f', deep=1) vtk_ugrid.SetPoints(vtk_points) etype_nids, cell_offsets_array, cell_types_array, eids, pids = _load_elements( geom_model, node_ids, idtype=idtype) nelements = len(eids) # build the grid _elements_to_vtk(vtk_ugrid, etype_nids, cell_offsets_array, cell_types_array) # fill the grid with results #point_data = vtk_ugrid.GetPointData() cell_data = vtk_ugrid.GetCellData() eid_array = numpy_to_vtk(eids, deep=0, array_type=None) eid_array.SetName('ElementID') cell_data.AddArray(eid_array) if add_property: pid_array = numpy_to_vtk(pids, deep=0, array_type=None) pid_array.SetName('PropertyID') cell_data.AddArray(pid_array) #if add_property: #pid_array = numpy_to_vtk(pids, deep=0, array_type=None) #pid_array.SetName('PropertyID') #cell_data.AddArray(pid_array) if add_material: psolid_mids = np.full(nelements, -1, dtype='int64') pshell_mids = np.full((nelements, 4), -1, dtype='int64') thickness = np.full(nelements, np.nan, dtype='float32') upids = np.unique(pids) is_solid = False is_shell = False for pid in upids: ipid = np.where(pid == pids) prop = geom_model.properties[pid] if prop.type == 'PSOLID': is_solid = True psolid_mids[ipid] = prop.mid elif prop.type == 'PSHELL': is_shell = True thickness[ipid] = prop.t for imid, mid in enumerate([prop.mid1, prop.mid2, prop.mid3, prop.mid4]): if mid is None: continue pshell_mids[ipid, imid] = mid else: geom_model.log.warning(f'skipping:\n{prop}') if is_solid: mid_array = numpy_to_vtk(psolid_mids, deep=0, array_type=None) mid_array.SetName('Solid Material') cell_data.AddArray(mid_array) if is_shell: thickness_array = numpy_to_vtk(thickness, deep=0, array_type=None) thickness_array.SetName('Shell Thickness') cell_data.AddArray(thickness_array) for imid in range(4): mids = pshell_mids[:, imid] shell_mid_array = numpy_to_vtk(mids, deep=0, array_type=None) thickness_array.SetName(f'Shell Material {imid+1}') cell_data.AddArray(shell_mid_array) #print(point_data) return eids
def get_results(self) -> Tuple[List[str], List[Any]]: txyz = np.stack([self.TX, self.TY, self.TZ], axis=1) txyz_array = numpy_to_vtk(txyz, deep=1, array_type=None) return [self.name], [txyz_array]
def create_vtk_cells_of_constant_element_types(grid, elements_list, etypes_list): """ Adding constant type elements is overly complicated enough as in ``create_vtk_cells_of_constant_element_type``. Now we extend this to multiple element types. grid : vtk.vtkUnstructuredGrid() the unstructured grid elements_list : List[elements, ...] elements : (nelements, nnodes_per_element) int ndarray the elements to add etypes_list : List[etype, ...] etype : int the VTK flag as defined in ``create_vtk_cells_of_constant_element_type`` """ if isinstance(etypes_list, list) and len(etypes_list) == 1: create_vtk_cells_of_constant_element_type(grid, elements_list[0], etypes_list[0]) return dtype = get_numpy_idtype_for_vtk() cell_offsets_list2 = [] cell_types_list2 = [] elements_list2 = [] nelements = 0 noffsets = 0 for element, etype in zip(elements_list, etypes_list): nelement, nnodes_per_element = element.shape nnodesp1 = nnodes_per_element + 1 # TODO: was 4; for a tri??? cell_offset = np.arange(0, nelement, dtype='int32') * nnodesp1 + noffsets noffset = nelement * nnodesp1 cell_type = np.ones(nelement, dtype='int32') * etype assert len(cell_offset) == nelement nnodesp1 = nnodes_per_element + 1 element_vtk = np.zeros((nelement, nnodesp1), dtype=dtype) element_vtk[:, 0] = nnodes_per_element # 3 nodes/tri element_vtk[:, 1:] = element cell_offsets_list2.append(cell_offset) cell_types_list2.append(cell_type) elements_list2.append(element_vtk.ravel()) nelements += nelement noffsets += noffset cell_types_array = np.hstack(cell_types_list2) cell_offsets_array = np.hstack(cell_offsets_list2) elements_array = np.hstack(elements_list2) # Create the array of cells cells_id_type = numpy_to_vtkIdTypeArray(elements_array.ravel(), deep=1) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(nelements, cells_id_type) # Cell types vtk_cell_types = numpy_to_vtk( cell_types_array, deep=0, array_type=vtk.vtkUnsignedCharArray().GetDataType()) vtk_cell_offsets = numpy_to_vtk(cell_offsets_array, deep=0, array_type=vtkConstants.VTK_ID_TYPE) grid.SetCells(vtk_cell_types, vtk_cell_offsets, vtk_cells)
def create_vtk_cells_of_constant_element_type(grid, elements, etype): """ Adding constant type elements is overly complicated. Parameters ---------- grid : vtk.vtkUnstructuredGrid() the unstructured grid elements : (nelements, nnodes_per_element) int ndarray the elements to add etype : int VTK cell type Notes ----- The documentation in this method is triangle-specific as it was developed for a tri mesh. It's more general than that though. 1 = vtk.vtkVertex().GetCellType() 3 = vtkLine().GetCellType() 5 = vtkTriangle().GetCellType() 9 = vtk.vtkQuad().GetCellType() 10 = vtkTetra().GetCellType() #vtkPenta().GetCellType() #vtkHexa().GetCellType() #vtkPyram().GetCellType() """ nelements, nnodes_per_element = elements.shape # We were careful about how we defined the arrays, so the data # is contiguous when we ravel it. Otherwise, you need to # deepcopy the arrays (deep=1). However, numpy_to_vtk isn't so # good, so we could use np.copy, which is better, but it's # ultimately unnecessary. #nodes = numpy_to_vtk(elements, deep=0, array_type=vtk.VTK_ID_TYPE) # (nnodes_per_element + 1) # TODO: was 4; for a tri...didn't seem to crash??? cell_offsets = np.arange(0, nelements, dtype='int32') * (nnodes_per_element + 1) assert len(cell_offsets) == nelements # Create the array of cells vtk_cells = vtk.vtkCellArray() dtype = get_numpy_idtype_for_vtk() elements_vtk = np.zeros((nelements, nnodes_per_element + 1), dtype=dtype) elements_vtk[:, 0] = nnodes_per_element # 3 nodes/tri element elements_vtk[:, 1:] = elements cells_id_type = numpy_to_vtkIdTypeArray(elements_vtk.ravel(), deep=1) vtk_cells.SetCells(nelements, cells_id_type) # Cell types # 5 = vtkTriangle().GetCellType() cell_types = np.ones(nelements, dtype='int32') * etype vtk_cell_types = numpy_to_vtk( cell_types, deep=0, array_type=vtk.vtkUnsignedCharArray().GetDataType()) vtk_cell_offsets = numpy_to_vtk(cell_offsets, deep=0, array_type=vtkConstants.VTK_ID_TYPE) grid.SetCells(vtk_cell_types, vtk_cell_offsets, vtk_cells)
def main(): grid = vtk.vtkUnstructuredGrid() grid_mapper = vtk.vtkDataSetMapper() grid_mapper.SetInputData(grid) #grid_mapper.SetInputData(grid) nodes = np.array([ [0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 2., 1.], ], dtype='float32') points = vtk.vtkPoints() points.SetNumberOfPoints(4) points_array = numpy_to_vtk( num_array=nodes, deep=True, array_type=vtk.VTK_FLOAT, ) nelements = 1 grid.Allocate(nelements, 1000) grid.SetPoints(points) elem = vtk.vtkQuad() pts = elem.GetPointIds() pts.SetId(0, 0) pts.SetId(1, 1) pts.SetId(2, 2) pts.SetId(3, 3) grid.InsertNextCell(elem.GetCellType(), pts) grid.Modified() forces = np.array([ [0., 0.1, 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., .3], ], dtype='float32') rend = vtk.vtkRenderer() if 1: maskPts = vtk.vtkMaskPoints() maskPts.SetInputData(grid) arrow = vtk.vtkArrowSource() arrow.SetTipResolution(16) arrow.SetTipLength(0.3) arrow.SetTipRadius(0.1) glyph = vtk.vtkGlyph3D() glyph.SetSourceConnection(arrow.GetOutputPort()) glyph.SetInputConnection(maskPts.GetOutputPort()) glyph.SetVectorModeToUseNormal() glyph.SetScaleFactor(1) glyph.SetColorModeToColorByVector() glyph.SetScaleModeToScaleByVector() glyph.OrientOn() glyph.Update() glyph_mapper = vtk.vtkPolyDataMapper() glyph_mapper.SetInputConnection(glyph.GetOutputPort()) glyph_mapper.SetScalarModeToUsePointFieldData() glyph_mapper.SetColorModeToMapScalars() glyph_mapper.ScalarVisibilityOn() glyph_mapper.SelectColorArray('Elevation') # Colour by scalars. #glyph_mapper.SetScalarRange(scalarRangeElevation) glyph_actor = vtk.vtkActor() glyph_actor.SetMapper(glyph_mapper) glyph_actor.RotateX(-45) glyph_actor.RotateZ(45) rend.AddViewProp(glyph_actor) #rend.AddActor(glyph_actor) geom_actor = vtk.vtkActor() geom_actor.SetMapper(grid_mapper) # ------------------------------------------------------------ # Create the RenderWindow, Renderer and Interactor # ------------------------------------------------------------ renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() renWin.AddRenderer(rend) iren.SetRenderWindow(renWin) # add actors #rend.AddViewProp(geom_actor) #rend.AddViewProp(edgeActor) rend.AddActor(geom_actor) #rend.AddViewProp(glyph_actor) #rend.AddActor2D(scalarBar) rend.SetBackground(0.7, 0.8, 1.0) renWin.SetSize(800, 800) renWin.Render() iren.Start()