def _update_grid(self, nodes): """deflects the geometry""" grid = self.grid points = grid.GetPoints() #inan = np.where(nodes.ravel() == np.nan)[0] #if len(inan) > 0: #raise RuntimeError('nan in nodes...') numpy_to_vtk_points(nodes, points=points, dtype='<f', deep=1) grid.Modified() self.grid_selected.Modified() self._update_follower_grids(nodes)
def set_quad_grid(self, name, nodes, elements, color, line_width=5, opacity=1.): """ Makes a CQUAD4 grid """ self.create_alternate_vtk_grid(name, color=color, line_width=line_width, opacity=opacity, representation='wire') nnodes = nodes.shape[0] nquads = elements.shape[0] #print(nodes) if nnodes == 0: return if nquads == 0: return #print('adding quad_grid %s; nnodes=%s nquads=%s' % (name, nnodes, nquads)) assert isinstance(nodes, np.ndarray), type(nodes) points = numpy_to_vtk_points(nodes) grid = self.alt_grids[name] grid.SetPoints(points) etype = 9 # vtk.vtkQuad().GetCellType() create_vtk_cells_of_constant_element_type(grid, elements, etype) self._add_alt_actors({name : self.alt_grids[name]}) #if name in self.geometry_actors: self.geometry_actors[name].Modified()
def highlight_nodes(self, nids, model_name='', add_actor=True): """ Highlights a series of nodes Parameters ---------- nids : int, List[int] the nodes to apply a message to model_name : str, List[str] the name of the actor to highlight the nodes for """ npoints = len(nids) all_nids = self.gui.get_node_ids(model_name=model_name, ids=None) all_xyz = self.gui.get_xyz_cid0(model_name=model_name) i = np.searchsorted(all_nids, nids) xyz = all_xyz[i, :] #ugrid = vtk.vtkUnstrucuturedGrid() points = numpy_to_vtk_points(xyz, points=None, dtype='<f', deep=1) ugrid = create_unstructured_point_grid(points, npoints) actor = self.gui.mouse_actions.create_highlighted_actor( ugrid, representation='points', add_actor=add_actor) self.gui.vtk_interactor.Render() return actor
def _create_cart3d_free_edges(self, model, nodes, elements): """creates the free edges to help identify unclosed models""" free_edges_array = model.get_free_edges(elements) nfree_edges = len(free_edges_array) if nfree_edges: npoints = 2 * nfree_edges if 'free_edges' not in self.gui.alt_grids: self.gui.create_alternate_vtk_grid('free_edges', color=PINK_FLOAT, line_width=3, opacity=1.0, representation='surface') alt_grid = self.gui.alt_grids['free_edges'] etype = 3 # vtk.vtkLine().GetCellType() elements2 = np.arange(0, npoints, dtype='int32').reshape(nfree_edges, 2) create_vtk_cells_of_constant_element_type(alt_grid, elements2, etype) #alt_grid.Allocate(nfree_edges, 1000) free_edge_nodes = nodes[free_edges_array.ravel(), :] points = numpy_to_vtk_points(free_edge_nodes) alt_grid.SetPoints(points) else: # TODO: clear free edges pass if 'free_edges' in self.gui.alt_grids: self.gui._add_alt_actors(self.gui.alt_grids) self.gui.geometry_actors['free_edges'].Modified() if hasattr(self.gui.geometry_actors['free_edges'], 'Update'): self.gui.geometry_actors['free_edges'].Update()
def load_stl_geometry(self, stl_filename, name='main', plot=True): #print("load_stl_geometry...") skip_reading = self.gui._remove_old_geometry(stl_filename) if skip_reading: return model = read_stl(stl_filename, remove_elements_with_bad_normals=True, log=self.gui.log, debug=False) #self.model_type = model.model_type nodes = model.nodes elements = model.elements normals = model.get_normals(elements, stop_on_failure=False) areas = model.get_area(elements, stop_on_failure=False) #nnormals = model.get_normals_at_nodes(elements) self.gui.nnodes = nodes.shape[0] self.gui.nelements = elements.shape[0] self.gui.log.info('nnodes=%s nelements=%s' % (self.gui.nnodes, self.gui.nelements)) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) points = numpy_to_vtk_points(nodes) self.gui.nid_map = {} #elem.SetNumberOfPoints(nnodes) assert nodes is not None unused_nnodes = nodes.shape[0] xmax, ymax, zmax = nodes.max(axis=0) xmin, ymin, zmin = nodes.min(axis=0) self.gui.log.info('xmax=%s xmin=%s' % (xmax, xmin)) self.gui.log.info('ymax=%s ymin=%s' % (ymax, ymin)) self.gui.log.info('zmax=%s zmin=%s' % (zmax, zmin)) dim_max = max(xmax - xmin, ymax - ymin, zmax - zmin) self.gui.create_global_axes(dim_max) etype = 5 # vtkTriangle().GetCellType() create_vtk_cells_of_constant_element_type(grid, elements, etype) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() # loadSTLResults - regions/loads self.gui.scalarBar.VisibilityOff() self.gui.scalarBar.Modified() cases = OrderedDict() self.gui.isubcase_name_map = {} ID = 1 form, cases, node_ids, element_ids = self._fill_stl_case( cases, ID, elements, nodes, normals, areas) self.gui.node_ids = node_ids self.gui.element_ids = element_ids self.gui._finish_results_io2(form, cases)
def add_user_geometry(alt_grid: vtk.vtkUnstructuredGrid, geom_grid: vtk.vtkUnstructuredGrid, xyz: np.ndarray, nid_map: Dict[int, int], nnodes: int, bars: np.ndarray, tris: np.ndarray, quads: np.ndarray, nelements: int, nbars: int, ntris: int, nquads: int) -> vtk.vtkPoints: """helper method for ``_add_user_geometry``""" # set points points = numpy_to_vtk_points(xyz, dtype='<f') if nelements > 0: for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nbars: for i, bar in enumerate(bars[:, 1:]): g1 = nid_map[bar[0]] g2 = nid_map[bar[1]] elem = vtk.vtkLine() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if ntris: for i, tri in enumerate(tris[:, 1:]): g1 = nid_map[tri[0]] g2 = nid_map[tri[1]] g3 = nid_map[tri[2]] elem = vtk.vtkTriangle() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) elem.GetPointIds().SetId(2, g3) geom_grid.InsertNextCell(5, elem.GetPointIds()) if nquads: for i, quad in enumerate(quads[:, 1:]): g1 = nid_map[quad[0]] g2 = nid_map[quad[1]] g3 = nid_map[quad[2]] g4 = nid_map[quad[3]] elem = vtk.vtkQuad() point_ids = elem.GetPointIds() point_ids.SetId(0, g1) point_ids.SetId(1, g2) point_ids.SetId(2, g3) point_ids.SetId(3, g4) geom_grid.InsertNextCell(9, elem.GetPointIds()) alt_grid.SetPoints(points) if nelements > 0: geom_grid.SetPoints(points) return points
def create_highlighted_actors( gui, grid: vtk.vtkUnstructuredGrid, all_nodes=None, nodes=None, set_node_scalars=True, all_elements=None, elements=None, set_element_scalars=True, add_actors: bool = False) -> List[vtk.vtkLODActor]: """creates nodes & element highlighted objects""" actors = [] nnodes = 0 nelements = 0 if nodes is not None: nnodes = len(nodes) assert len(all_nodes) >= nnodes if elements is not None: nelements = len(elements) assert len(all_elements) >= nelements assert nnodes + nelements > 0 if nnodes: point_ids = np.searchsorted(all_nodes, nodes) output_data = grid.GetPoints().GetData() points_array = vtk_to_numpy(output_data) # yeah! point_array2 = points_array[point_ids, :] points2 = numpy_to_vtk_points(point_array2) ugrid = create_unstructured_point_grid(points2, nnodes) if set_node_scalars: point_ids_array = numpy_to_vtk(nodes) ugrid.GetPointData().SetScalars(point_ids_array) actor = create_highlighted_actor(gui, ugrid, representation='points', add_actor=add_actors) actors.append(actor) if nelements: cell_ids = np.searchsorted(all_elements, elements) selection_node = create_vtk_selection_node_by_cell_ids(cell_ids) ugrid = extract_selection_node_from_grid_to_ugrid(grid, selection_node) if set_element_scalars: element_ids_array = numpy_to_vtk(elements) ugrid.GetPointData().SetScalars(None) ugrid.GetCellData().SetScalars(element_ids_array) actor = create_highlighted_actor(gui, ugrid, representation='wire', add_actor=add_actors) actors.append(actor) return actors
def create_filtered_point_ugrid(ugrid, nids, nids2): """ We need to filter the nodes that were filtered by the numpy setdiff1d, so we don't show extra points """ #unused_pointsu = ugrid.GetPoints() output_data = ugrid.GetPoints().GetData() points_array = vtk_to_numpy(output_data) # yeah! isort_nids = np.argsort(nids) nids = nids[isort_nids] inids = np.searchsorted(nids, nids2) points_array_sorted = points_array[isort_nids, :] point_array2 = points_array_sorted[inids, :] points2 = numpy_to_vtk_points(point_array2) npoints = len(nids2) ugrid = create_unstructured_point_grid(points2, npoints) return ugrid
def create_grid(self): # result_array = vtk.vtkDataArray.CreateDataArray(vtk_typecode) # result_array.SetNumberOfTuples(shape[0]) # result_array.SetVoidArray(z_flat, len(z_flat), 1) # *********points_array = numpy_to_vtk(num_array=nodes, deep=deep, array_type=vtk.VTK_FLOAT,) # points = vtk.vtkPoints() # nnodes = nodes.shape[0] # points.SetNumberOfPoints(nnodes) # points.SetData(result_array) out = self.model.get_displacement_index_xyz_cp_cd( fdtype='float32', idtype='int32', sort_ids=True) icd_transform, icp_transform, xyz_cp, nid_cp_cd = out cid = 0 xyz_cid0 = self.model.transform_xyzcp_to_xyz_cid( xyz_cp, nid_cp_cd[:, 0], icp_transform, cid=cid, in_place=False) points = numpy_to_vtk_points(xyz_cid0) grid = vtk.vtkUnstructuredGrid() grid.SetPoints(points) for (eid, element) in sorted(iteritems(self.model.elements)): if isinstance(element, CQUAD4): node_ids = element.node_ids n1, n2, n3, n4 = [int(nid) - 1 for nid in node_ids] elem = vtk.vtkQuad() elem.GetPointIds().SetId(0, n1) elem.GetPointIds().SetId(1, n2) elem.GetPointIds().SetId(2, n3) elem.GetPointIds().SetId(3, n4) grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) return grid
def load_cart3d_geometry(self, cart3d_filename, name='main', plot=True): """ The entry point for Cart3d geometry loading. Parameters ---------- cart3d_filename : str the cart3d filename to load name : str the name of the "main" actor for the GUI plot : bool; default=True should the model be generated or should we wait until after the results are loaded """ skip_reading = self._remove_old_cart3d_geometry(cart3d_filename) if skip_reading: return self.gui.eid_maps[name] = {} self.gui.nid_maps[name] = {} model = read_cart3d(cart3d_filename, log=self.gui.log, debug=False) self.gui.model_type = 'cart3d' nodes = model.nodes elements = model.elements regions = model.regions loads = model.loads self.gui.nnodes = model.npoints self.gui.nelements = model.nelements grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) #if 0: #fraction = 1. / self.nnodes # so you can color the nodes by ID #for nid, node in sorted(iteritems(nodes)): #self.grid_result.InsertNextValue(nid * fraction) assert nodes is not None #nnodes = nodes.shape[0] mmax = nodes.max(axis=0) mmin = nodes.min(axis=0) dim_max = (mmax - mmin).max() xmax, ymax, zmax = mmax xmin, ymin, zmin = mmin self.gui.log_info("xmin=%s xmax=%s dx=%s" % (xmin, xmax, xmax - xmin)) self.gui.log_info("ymin=%s ymax=%s dy=%s" % (ymin, ymax, ymax - ymin)) self.gui.log_info("zmin=%s zmax=%s dz=%s" % (zmin, zmax, zmax - zmin)) self.gui.create_global_axes(dim_max) points = numpy_to_vtk_points(nodes) #assert elements.min() == 0, elements.min() etype = 5 # vtkTriangle().GetCellType() create_vtk_cells_of_constant_element_type(grid, elements, etype) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() self._create_cart3d_free_edges(model, nodes, elements) # loadCart3dResults - regions/loads self.gui.scalarBar.VisibilityOn() self.gui.scalarBar.Modified() assert loads is not None if 'Mach' in loads: avg_mach = mean(loads['Mach']) note = ': avg(Mach)=%g' % avg_mach else: note = '' self.gui.isubcase_name_map = {1: ['Cart3d%s' % note, '']} cases = OrderedDict() ID = 1 form, cases, icase, node_ids, element_ids, data_map_dict = _fill_cart3d_geometry_objects( cases, ID, nodes, elements, regions, model) self.data_map = data_map_dict mach, unused_alpha, unused_beta = self._create_box( cart3d_filename, ID, form, cases, icase, regions) #mach = None _fill_cart3d_results(cases, form, icase, ID, loads, model, mach) self.gui.node_ids = node_ids self.gui.element_ids = element_ids self.gui._finish_results_io2(form, cases)
def load_vrml_geometry(self, vrml_filename, name='main', plot=True): """loads a VRML file into the GUI""" model_name = name #key = self.case_keys[self.icase] #case = self.result_cases[key] self.gui.eid_maps[name] = {} self.gui.nid_maps[name] = {} skip_reading = self.gui._remove_old_geometry(vrml_filename) if skip_reading: return nodes, quads, tris = read_vrml(vrml_filename) points = numpy_to_vtk_points(nodes) nnodes = nodes.shape[0] assert nnodes > 0 ntris = len(tris) nquads = len(quads) nelements = ntris + nquads self.gui.nelements = nelements self.gui.nnodes = nnodes self.gui.log.info( f"nnodes={nnodes} nelements={nelements} (nquads={nquads} ntris={ntris})" ) assert nelements > 0, nelements grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) #self.gui.nid_map = {} etypes = [] elements = [] if ntris: elements.append(tris) etypes.append(5) # vtkTriangle().GetCellType() if nquads: elements.append(quads) etypes.append(9) # vtkQuad().GetCellType() assert len(etypes) > 0, etypes #self.gui.model.elements = elements #self.gui.model.etypes = etypes create_vtk_cells_of_constant_element_types(grid, elements, etypes) self.gui.nelements = nelements grid.SetPoints(points) grid.Modified() #------------------------------------------------ self.gui.scalar_bar_actor.VisibilityOn() self.gui.scalar_bar_actor.Modified() self.gui.isubcase_name_map = {1: ['AFLR UGRID Surface', '']} cases = OrderedDict() ID = 1 node_ids = np.arange(1, nnodes + 1, dtype='int32') element_ids = np.arange(1, nelements + 1, dtype='int32') self.gui.node_ids = node_ids self.gui.element_ids = element_ids #eids = arange(1, len(elements) + 1, dtype='int32') #nids = arange(1, len(nodes) + 1, dtype='int32') #regions = np.array(regions, dtype='int32') icase = 0 colormap = self.gui.settings.colormap eid_res = GuiResult(ID, header='ElementID', title='ElementID', location='centroid', scalar=element_ids) nid_res = GuiResult(ID, header='NodeID', title='NodeID', location='node', scalar=node_ids) nxyz_res = NormalResult(0, 'Normals', 'Normals', nlabels=2, labelsize=5, ncolors=2, colormap=colormap, data_format='%.1f', uname='NormalResult') geometry_form = [ ('ElementID', icase, []), ('NodeID', icase + 1, []), ('Normals', icase + 2, []), ] cases[icase] = (eid_res, (ID, 'ElementID')) cases[icase + 1] = (nid_res, (ID, 'NodeID')) cases[icase + 2] = (nxyz_res, (0, 'Normals')) form = geometry_form if plot: self.gui._finish_results_io2(model_name, form, cases)
def load_fast_geometry(self, fgrid_filename, name='main', plot=True): skip_reading = self.gui._remove_old_geometry(fgrid_filename) if skip_reading: return ext = os.path.splitext(fgrid_filename)[1] ext = ext.lower() if ext == '.fgrid': dimension_flag = 3 else: msg = 'unsupported extension=%r. Use "fgrid".' % ext raise RuntimeError(msg) #read_loads = True model = read_fgrid( fgrid_filename, dimension_flag, log=self.gui.log, debug=False, ) nodes = model.nodes ntris = 0 ntets = 0 if model.tets is None: dimension_flag = 2 if model.tris is not None: tris = model.tris - 1 ntris = tris.shape[0] else: dimension_flag = 3 tets = model.tets - 1 ntets = tets.shape[0] nnodes = nodes.shape[0] model.log.info('ntris=%s ntets=%s' % (ntris, ntets)) #print('node0 = %s' % str(nodes[0, :])) #print('node%i = %s' % (1, str(nodes[1, :]))) #print('node%i = %s' % (2, str(nodes[2, :]))) #print('node%i = %s' % (nnodes, str(nodes[-1, :]))) #mapbc = model.mapbc #loads = model.loads self.gui.nnodes = nnodes nelements = ntris + ntets self.gui.nelements = nelements #print("nnodes = %i" % self.nnodes) #print("nelements = %i" % self.nelements) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) points = numpy_to_vtk_points(nodes) self.gui.nid_map = {} assert nodes is not None nnodes = nodes.shape[0] if dimension_flag == 2: for (n0, n1, n2) in tris: elem = vtkTriangle() elem.GetPointIds().SetId(0, n0) elem.GetPointIds().SetId(1, n1) elem.GetPointIds().SetId(2, n2) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(5, elem.GetPointIds()) elif dimension_flag == 3: for (n0, n1, n2, n3) in tets: elem = vtkTetra() elem.GetPointIds().SetId(0, n0) elem.GetPointIds().SetId(1, n1) elem.GetPointIds().SetId(2, n2) elem.GetPointIds().SetId(3, n3) #elem.GetCellType() = 10 # vtkTetra grid.InsertNextCell(10, elem.GetPointIds()) else: raise RuntimeError('dimension_flag=%r' % dimension_flag) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() # regions/loads self.gui.scalarBar.Modified() cases = OrderedDict() #cases = self.result_cases form = [] node_ids, element_ids = self._fill_fast_results(form, cases, model, nnodes, nelements, dimension_flag, results=True) self.gui.node_ids = node_ids self.gui.element_ids = element_ids self.gui._finish_results_io2(form, cases)
def _create_bar_yz_update(self, model: BDF, node0: int, ugrid, points_list, bar_beam_eids: List[int], bar_pid_to_eids: Dict[int, List[int]]) -> None: if not node0: return if ugrid is None: ugrid = create_3d_beams(model, bar_pid_to_eids) else: assert len(points_list), points_list points_array = _make_points_array(points_list) points = numpy_to_vtk_points(points_array) ugrid.SetPoints(points) if ugrid is None: return gui = self.gui def update_grid_function(unused_nid_map, ugrid, points, nodes) -> None: # pragma: no cover """custom function to update the 3d bars""" if not gui.settings.nastran_is_3d_bars_update: return points_list = [] node0b = 0 for eid in bar_beam_eids: elem = self.model.elements[eid] pid_ref = elem.pid_ref if pid_ref is None: pid_ref = self.model.Property(elem.pid) assert not isinstance(pid_ref, integer_types), elem ptype = pid_ref.type bar_type = get_bar_type(ptype, pid_ref) #nids = elem.nodes (nid1, nid2) = elem.node_ids node1 = model.nodes[nid1] node2 = model.nodes[nid2] i1, i2 = np.searchsorted(self.node_ids, [nid1, nid2]) n1 = nodes[i1, :] n2 = nodes[i2, :] #centroid = (n1 + n2) / 2. i = n2 - n1 Li = norm(i) ihat = i / Li unused_v, wa, wb, xform = rotate_v_wa_wb( model, elem, n1, n2, node1, node2, ihat, i, eid, Li, model.log) if wb is None: # one or more of v, wa, wb are bad continue ugridi = None node0b = add_3d_bar_element(bar_type, ptype, pid_ref, n1 + wa, n2 + wb, xform, ugridi, node0b, points_list, add_to_ugrid=False) points_array = _make_points_array(points_list) points_array2 = numpy_to_vtk( num_array=points_array, deep=1, array_type=vtk.VTK_FLOAT, ) points.SetData(points_array2) ugrid.SetPoints(points) points.Modified() ugrid.Modified() return #def update_grid_function(unused_nid_map, ugrid, points, nodes) -> None: # pragma: no cover #"""custom function to update the 3d bars""" #if not gui.settings.nastran_is_3d_bars_update: #return #update_3d_beams(ugrid, model, bar_pid_to_eids) gui.create_alternate_vtk_grid( '3d_bars', color=BLUE_FLOAT, opacity=0.2, #'3d_bars', color=BLUE_FLOAT, opacity=1.0, #representation='wire', is_visible=True, representation='surface', is_visible=True, follower_function=update_grid_function, ugrid=ugrid, )
def _apply_points_list(points_list, ugrid): if points_list: points_array = _make_points_array(points_list) points = numpy_to_vtk_points(points_array) ugrid.SetPoints(points)
def load_openfoam_geometry(self, openfoam_filename, mesh_3d, name='main', plot=True, **kwargs): model_name = name #key = self.caseKeys[self.iCase] #case = self.resultCases[key] #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename) skip_reading = self.gui._remove_old_geometry(openfoam_filename) if skip_reading: return log = self.gui.log reset_labels = True #self.log.info('self.modelType=%s' % self.modelType) log.info('mesh_3d = %s' % mesh_3d) if mesh_3d in ['hex', 'shell']: model = BlockMesh(log=log, debug=False) # log=self.log, debug=False elif mesh_3d == 'faces': model = BlockMesh(log=log, debug=False) # log=self.log, debug=False boundary = Boundary(log=log, debug=False) self.gui.modelType = 'openfoam' #self.modelType = model.modelType log.info('openfoam_filename = %s' % openfoam_filename) is_face_mesh = False if mesh_3d == 'hex': is_3d_blockmesh = True is_surface_blockmesh = False (nodes, hexas, quads, names, patches) = model.read_openfoam(openfoam_filename) elif mesh_3d == 'shell': is_3d_blockmesh = False is_surface_blockmesh = True (nodes, hexas, quads, names, patches) = model.read_openfoam(openfoam_filename) elif mesh_3d == 'faces': is_3d_blockmesh = False is_surface_blockmesh = False is_face_mesh = True #(nodes, hexas, quads, names, patches) = model.read_openfoam(openfoam_filename) else: raise RuntimeError(mesh_3d) tris = [] if mesh_3d == 'hex': self.gui.nelements = len(hexas) elif mesh_3d == 'shell': self.gui.nelements = len(quads) elif mesh_3d == 'faces': dirname = os.path.dirname(openfoam_filename) point_filename = os.path.join(dirname, 'points') face_filename = os.path.join(dirname, 'faces') boundary_filename = os.path.join(dirname, 'boundary') check_path(face_filename, 'face_filename') check_path(point_filename, 'point_filename') check_path(boundary_filename, 'boundary_filename') hexas = None patches = None nodes, quads, names = boundary.read_openfoam( point_filename, face_filename, boundary_filename) self.gui.nelements = len(quads) + len(tris) else: raise RuntimeError(mesh_3d) self.gui.nnodes = len(nodes) log = self.gui.log log.debug("nnodes = %s" % self.gui.nnodes) log.debug("nelements = %s" % self.gui.nelements) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) self.gui.nid_map = {} assert nodes is not None nnodes = nodes.shape[0] xmax, ymax, zmax = nodes.max(axis=0) xmin, ymin, zmin = nodes.min(axis=0) nodes -= np.array([xmin, ymin, zmin]) log.info('xmax=%s xmin=%s' % (xmax, xmin)) log.info('ymax=%s ymin=%s' % (ymax, ymin)) log.info('zmax=%s zmin=%s' % (zmax, zmin)) dim_max = max(xmax - xmin, ymax - ymin, zmax - zmin) #dim_max = (mmax - mmin).max() assert dim_max > 0 # breaks the model without subracting off the delta #self.update_axes_length(dim_max) self.gui.create_global_axes(dim_max) #print('is_face_mesh=%s is_3d_blockmesh=%s is_surface_blockmesh=%s' % ( #is_face_mesh, is_3d_blockmesh, is_surface_blockmesh)) with open('points.bdf', 'w') as bdf_file: bdf_file.write('CEND\n') bdf_file.write('BEGIN BULK\n') unames = unique(names) for pid in unames: bdf_file.write('PSHELL,%i,1,0.1\n' % pid) bdf_file.write('MAT1,1,1.0e7,,0.3\n') if is_face_mesh: points = vtk.vtkPoints() points.SetNumberOfPoints(self.gui.nnodes) unodes = unique(quads) unodes.sort() # should stop plotting duplicate nodes for inode, node in enumerate(nodes): if inode in unodes: bdf_file.write('GRID,%i,,%s,%s,%s\n' % ( inode + 1, node[0], node[1], node[2], )) points.InsertPoint(inode, node) else: points = numpy_to_vtk_points(nodes) #elements -= 1 normals = None if is_3d_blockmesh: nelements = hexas.shape[0] cell_type_hexa8 = vtkHexahedron().GetCellType() create_vtk_cells_of_constant_element_type( grid, hexas, cell_type_hexa8) elif is_surface_blockmesh: nelements = quads.shape[0] cell_type_quad4 = vtkQuad().GetCellType() create_vtk_cells_of_constant_element_type( grid, quads, cell_type_quad4) elif is_face_mesh: elems = quads nelements = quads.shape[0] nnames = len(names) normals = zeros((nelements, 3), dtype='float32') if nnames != nelements: msg = 'nnames=%s nelements=%s names.max=%s names.min=%s' % ( nnames, nelements, names.max(), names.min()) raise RuntimeError(msg) for eid, element in enumerate(elems): ineg = where(element == -1)[0] nnodes = 4 if ineg: nnodes = ineg.max() #pid = 1 pid = names[eid] if nnodes == 3: # triangle! bdf_file.write('CTRIA3,%i,%i,%i,%i,%i\n' % (eid + 1, pid, element[0] + 1, element[1] + 1, element[2] + 1)) elem = vtkTriangle() a = nodes[element[1], :] - nodes[element[0], :] b = nodes[element[2], :] - nodes[element[0], :] n = cross(a, b) normals[eid, :] = n / norm(n) elem.GetPointIds().SetId(0, element[0]) elem.GetPointIds().SetId(1, element[1]) elem.GetPointIds().SetId(2, element[2]) grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif nnodes == 4: bdf_file.write( 'CQUAD4,%i,%i,%i,%i,%i,%i\n' % (eid + 1, pid, element[0] + 1, element[1] + 1, element[2] + 1, element[3] + 1)) a = nodes[element[2], :] - nodes[element[0], :] b = nodes[element[3], :] - nodes[element[1], :] n = cross(a, b) normals[eid, :] = n / norm(n) elem = vtkQuad() elem.GetPointIds().SetId(0, element[0]) elem.GetPointIds().SetId(1, element[1]) elem.GetPointIds().SetId(2, element[2]) elem.GetPointIds().SetId(3, element[3]) grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: raise RuntimeError('nnodes=%s' % nnodes) else: msg = 'is_surface_blockmesh=%s is_face_mesh=%s; pick one' % ( is_surface_blockmesh, is_face_mesh) raise RuntimeError(msg) bdf_file.write('ENDDATA\n') self.gui.nelements = nelements grid.SetPoints(points) grid.Modified() self.gui.scalar_bar_actor.VisibilityOn() self.gui.scalar_bar_actor.Modified() self.gui.isubcase_name_map = {0: ['OpenFoam BlockMeshDict', '']} cases = OrderedDict() ID = 1 #print("nElements = ",nElements) if mesh_3d == 'hex': form, cases, node_ids, element_ids = self._fill_openfoam_case( cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh) elif mesh_3d == 'shell': form, cases, node_ids, element_ids = self._fill_openfoam_case( cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh) elif mesh_3d == 'faces': if len(names) == nelements: is_surface_blockmesh = True form, cases, node_ids, element_ids = self._fill_openfoam_case( cases, ID, nodes, nelements, patches, names, normals, is_surface_blockmesh) else: raise RuntimeError(mesh_3d) self.gui.node_ids = node_ids self.gui.element_ids = element_ids if plot: self.gui._finish_results_io2(model_name, form, cases, reset_labels=reset_labels) else: self.gui._set_results(form, cases)
def load_panair_geometry(self, panair_filename, name='main', plot=True): model_name = name self.gui.nid_map = {} #key = self.case_keys[self.icase] #case = self.result_cases[key] skip_reading = self.gui._remove_old_geometry(panair_filename) if skip_reading: return model = PanairGrid(log=self.gui.log, debug=self.gui.debug) self.gui.model_type = model.model_type model.read_panair(panair_filename) self.gui.geom_model = model # get_wakes=True shows explicit wakes # # TODO: bad for results...what about just not adding it to the patches/bcs? nodes, elements, regions, kt, cp_norm = model.get_points_elements_regions( get_wakes=True) self.gui.nnodes = len(nodes) self.gui.nelements = len(elements) #print("nnodes = ",self.nnodes) #print("nelements = ", self.nelements) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) points = vtk.vtkPoints() points.SetNumberOfPoints(self.gui.nnodes) assert len(nodes) > 0 mmax = amax(nodes, axis=0) mmin = amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.gui.create_global_axes(dim_max) points = numpy_to_vtk_points(nodes) assert len(elements) > 0 elem = vtkQuad() quad_type = elem.GetCellType() create_vtk_cells_of_constant_element_type(grid, elements, quad_type) grid.SetPoints(points) grid.Modified() # loadPanairResults - regions/loads if plot: self.gui.scalar_bar_actor.VisibilityOn() self.gui.scalar_bar_actor.Modified() self.gui.isubcase_name_map = {1: ['Panair', '']} cases = OrderedDict() ID = 1 loads = [] form, cases, node_ids, element_ids = self._fill_panair_geometry_case( cases, ID, nodes, elements, regions, kt, cp_norm, loads) self.gui.node_ids = node_ids self.gui.element_ids = element_ids #if plot: self.gui._finish_results_io2(model_name, form, cases)
def load_degen_geom_geometry(self, csv_filename, name='main', plot=True): # pragma: no cover #key = self.case_keys[self.icase] #case = self.result_cases[key] skip_reading = self._remove_old_adb_geometry(csv_filename) if skip_reading: return model = DegenGeom(log=self.log, debug=False) self.model_type = 'vspaero' #self.model_type = model.model_type model.read_degen_geom(csv_filename) nodes = [] elements = [] inid = 0 for name, comps in sorted(model.components.items()): self.log.debug('name = %r' % name) #print(comps) #print('------------') for comp in comps: self.log.info(comp) nnodes = comp.xyz.shape[0] nodes.append(comp.xyz) is_elem = np.linalg.norm(comp.elements, axis=1) > 0 elements.append(comp.elements[is_elem] + inid) inid += nnodes if len(nodes) == 1: nodes = nodes[0] elements = elements[0] else: nodes = np.vstack(nodes) elements = np.vstack(elements) nnodes = nodes.shape[0] nelements = elements.shape[0] self.nnodes = nnodes self.nelements = nelements self.grid.Allocate(self.nelements, 1000) #vectorReselt.SetNumberOfComponents(3) self.nid_map = {} assert nodes is not None #print("nxyz_nodes=%s" % nxyz_nodes) mmax = amax(nodes, axis=0) mmin = amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.create_global_axes(dim_max) points = numpy_to_vtk_points(nodes) #self.log.info('nxyz_nodes=%s nwake_nodes=%s total=%s' % ( #nnodes, nwake_nodes, nxyz_nodes + nwake_nodes)) #self.log.info('nxyz_elements=%s nwake_elements=%s total=%s' % ( #nxyz_elements, nwake_elements, nxyz_elements + nwake_elements)) elements -= 1 etype = 9 # vtkQuad().GetCellType() create_vtk_cells_of_constant_element_type(self.grid, elements, etype) self.grid.SetPoints(points) self.grid.Modified() if hasattr(self.grid, 'Update'): self.grid.Update() #self.log_info("updated grid") # load results - regions/loads self.scalarBar.VisibilityOn() self.scalarBar.Modified() #mach = model.machs[0] #alpha = model.alphas[0] #beta = model.betas[0] #note = ': Mach=%.2f, alpha=%.1f, beta=%.1f' % (mach, alpha, beta) note = 'name=%s' % name self.isubcase_name_map = {1: ['OpenVSP%s' % note, '']} cases = {} ID = 1 form, cases = self._fill_degen_geom_case(cases, ID, model, nnodes, nelements) self._finish_results_io2(form, cases)
def load_ugrid_geometry(self, ugrid_filename, read_solids=False, name='main', plot=True): """ The entry point for UGRID geometry loading. Parameters ---------- ugrid_filename : str the ugrid filename to load read_solids : bool True : load the tets/pentas/hexas from the UGRID3D model False : UGRID2D or limits the UGRID3D model to tris/quads name : str the name of the "main" actor for the GUI plot : bool; default=True should the model be generated or should we wait until after the results are loaded """ model_name = name #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename) #if skip_reading: # return model, is_2d, is_3d = get_ugrid_model(ugrid_filename, read_solids, self.gui.log) self.gui.model_type = 'ugrid' self.gui.log.debug('ugrid_filename = %s' % ugrid_filename) model.read_ugrid(ugrid_filename) self.gui.model = model nnodes = model.nodes.shape[0] ntris = model.tris.shape[0] nquads = model.quads.shape[0] ntets = 0 npenta5s = 0 npenta6s = 0 nhexas = 0 if is_2d: tris = model.tris quads = model.quads nelements = ntris + nquads else: if read_solids: ntets = model.tets.shape[0] npenta5s = model.penta5s.shape[0] npenta6s = model.penta6s.shape[0] nhexas = model.hexas.shape[0] tets = model.tets - 1 penta5s = model.penta5s - 1 penta6s = model.penta6s - 1 hexas = model.hexas - 1 nelements = ntets + npenta5s + npenta6s + nhexas else: tris = model.tris - 1 quads = model.quads - 1 nelements = ntris + nquads #self.nodes = nodes #self.tris = tris #self.quads = quads #self.pids = pids #self.tets = tets #self.penta5s = penta5s #self.penta6s = penta6s #self.hexas = hexas nodes = model.nodes self.gui.nelements = nelements self.gui.nnodes = nnodes self.gui.log.info("nnodes=%s nelements=%s" % (self.gui.nnodes, self.gui.nelements)) assert nelements > 0, nelements grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) mmax = amax(nodes, axis=0) mmin = amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.gui.create_global_axes(dim_max) self.gui.log.info('max = %s' % mmax) self.gui.log.info('min = %s' % mmin) if is_3d and read_solids: diff_node_ids = model.check_hanging_nodes(stop_on_diff=False) if len(diff_node_ids): self.gui.create_alternate_vtk_grid('hanging_nodes', color=RED_FLOAT, line_width=5, opacity=1., point_size=10, representation='point') self._add_ugrid_nodes_to_grid('hanging_nodes', diff_node_ids, nodes) self.gui._add_alt_actors(self.gui.alt_grids) points = numpy_to_vtk_points(nodes) elements = [] etypes = [] if is_2d or not read_solids: if ntris: elements.append(tris) etypes.append(5) # vtkTriangle().GetCellType() if nquads: elements.append(quads) etypes.append(9) # vtkQuad().GetCellType() elif is_3d: if ntets: elements.append(tets) etypes.append(10) # VTK_TETRA().GetCellType() if npenta5s: elements.append(penta5s) etypes.append(14) # vtk.vtkPyramid().GetCellType() if npenta6s: elements.append(penta6s) etypes.append(13) # VTK_WEDGE().GetCellType() if nhexas: elements.append(hexas) etypes.append(12) # VTK_HEXAHEDRON().GetCellType() self.gui.model.elements = elements self.gui.model.etypes = etypes create_vtk_cells_of_constant_element_types(grid, elements, etypes) self.gui.nelements = nelements grid.SetPoints(points) grid.Modified() # loadCart3dResults - regions/loads self.gui.scalar_bar_actor.VisibilityOn() self.gui.scalar_bar_actor.Modified() self.gui.isubcase_name_map = {1: ['AFLR UGRID Surface', '']} cases = OrderedDict() ID = 1 if hasattr(model, 'pids'): form, cases, node_ids, element_ids = self._fill_ugrid3d_case( ugrid_filename, cases, ID, nnodes, nelements, model, read_solids) else: form, cases, node_ids, element_ids = self._fill_ugrid2d_case( cases, ID, nnodes, nelements) self.gui.node_ids = node_ids self.gui.element_ids = element_ids if plot: self.gui._finish_results_io2(model_name, form, cases)
def load_usm3d_geometry(self, cogsg_filename, name='main', plot=True): skip_reading = self.parent._remove_old_geometry(cogsg_filename) if skip_reading: return self.parent.eid_maps[name] = {} self.parent.nid_maps[name] = {} model = Usm3d(log=self.parent.log, debug=False) base_filename, ext = os.path.splitext(cogsg_filename) #node_filename = base_filename + '.node' #ele_filename = base_filename + '.ele' if ext == '.cogsg': dimension_flag = 3 #elif ext == '.ele': #dimension_flag = 3 else: raise RuntimeError( 'unsupported extension. Use "cogsg" or "front".') read_loads = True nodes, tris_tets, tris, bcs, mapbc, loads, flo_filename = model.read_usm3d( base_filename, dimension_flag, read_loads=read_loads) del tris_tets nodes = model.nodes tris = model.tris tets = model.tets bcs = model.bcs mapbc = model.mapbc loads = model.loads self.parent.out_filename = None if flo_filename is not None: self.parent.out_filename = flo_filename bcmap_to_bc_name = model.bcmap_to_bc_name self.parent.nnodes = nodes.shape[0] ntris = 0 ntets = 0 if tris is not None: ntris = tris.shape[0] if dimension_flag == 2: pass elif dimension_flag == 3: ntets = tets.shape[0] ntets = 0 else: raise RuntimeError() self.parent.nelements = ntris + ntets self.parent.log.debug("nnodes = %i" % self.parent.nnodes) self.parent.log.debug("nelements = %i" % self.parent.nelements) grid = self.parent.grid grid.Allocate(self.parent.nelements, 1000) self.parent.nid_map = {} self.parent.eid_map = {} assert nodes is not None unused_nnodes = nodes.shape[0] points = numpy_to_vtk_points(nodes) if ntris: self.parent.element_ids = np.arange(1, ntris + 1, dtype='int32') etype = 5 # vtkTriangle().GetCellType() create_vtk_cells_of_constant_element_type(grid, tris, etype) else: ntets = tets.shape[0] self.parent.element_ids = np.arange(1, ntets + 1, dtype='int32') if dimension_flag == 2: pass elif dimension_flag == 3: if ntets: etype = 10 # vtkTetra().GetCellType() assert tets.max() > 0, tets.min() create_vtk_cells_of_constant_element_type(grid, tets, etype) else: raise RuntimeError('dimension_flag=%r' % dimension_flag) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() # regions/loads self.parent.scalarBar.Modified() cases = OrderedDict() form = [] form, cases = self._fill_usm3d_results(cases, form, bcs, mapbc, bcmap_to_bc_name, loads, is_geometry=True) self.parent._finish_results_io2(form, cases)
def load_ugrid_geometry(self, ugrid_filename, name='main', plot=True): """ The entry point for UGRID geometry loading. Parameters ---------- ugrid_filename : str the ugrid filename to load name : str the name of the "main" actor for the GUI plot : bool; default=True should the model be generated or should we wait until after the results are loaded """ #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename) #if skip_reading: # return if is_binary_file(ugrid_filename): model = UGRID(log=self.log, debug=True) ext = os.path.basename(ugrid_filename).split('.')[ 2] # base, fmt, ext is_2d = False else: ext = os.path.basename(ugrid_filename).split('.')[1] # base, ext model = UGRID2D_Reader(log=self.log, debug=True) is_2d = True is_3d = not is_2d self.model_type = 'ugrid' self.log.debug('ugrid_filename = %s' % ugrid_filename) assert ext == 'ugrid', ugrid_filename model.read_ugrid(ugrid_filename) if is_2d: tris = model.tris quads = model.quads else: tris = model.tris - 1 quads = model.quads - 1 #self.nodes = nodes #self.tris = tris #self.quads = quads #self.pids = pids #self.tets = tets #self.penta5s = penta5s #self.penta6s = penta6s #self.hexas = hexas nnodes = model.nodes.shape[0] ntris = model.tris.shape[0] nquads = model.quads.shape[0] nelements = ntris + nquads nodes = model.nodes self.nelements = nelements self.nnodes = nnodes self.log.info("nnodes=%s nelements=%s" % (self.nnodes, self.nelements)) assert nelements > 0, nelements self.grid.Allocate(self.nelements, 1000) mmax = amax(nodes, axis=0) mmin = amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.create_global_axes(dim_max) self.log.info('max = %s' % mmax) self.log.info('min = %s' % mmin) if is_3d: diff_node_ids = model.check_hanging_nodes(stop_on_diff=False) if len(diff_node_ids): red = (1., 0., 0.) self.create_alternate_vtk_grid('hanging_nodes', color=red, line_width=5, opacity=1., point_size=10, representation='point') self._add_ugrid_nodes_to_grid('hanging_nodes', diff_node_ids, nodes) self._add_alt_actors(self.alt_grids) points = numpy_to_vtk_points(nodes) if ntris: for eid, element in enumerate(tris): elem = vtkTriangle() elem.GetPointIds().SetId(0, element[0]) elem.GetPointIds().SetId(1, element[1]) elem.GetPointIds().SetId(2, element[2]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nquads: for eid, element in enumerate(quads): elem = vtkQuad() elem.GetPointIds().SetId(0, element[0]) elem.GetPointIds().SetId(1, element[1]) elem.GetPointIds().SetId(2, element[2]) elem.GetPointIds().SetId(3, element[3]) self.grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) self.nelements = nelements self.grid.SetPoints(points) self.grid.Modified() self.log.info('update...') if hasattr(self.grid, 'Update'): self.grid.Update() #self.log.info("updated grid") # loadCart3dResults - regions/loads self.scalarBar.VisibilityOn() self.scalarBar.Modified() self.isubcase_name_map = {1: ['AFLR UGRID Surface', '']} cases = {} ID = 1 if hasattr(model, 'pids'): form, cases = self._fill_ugrid3d_case(ugrid_filename, cases, ID, nnodes, nelements, model) else: form, cases = self._fill_ugrid2d_case(cases, ID, nnodes, nelements) if plot: self._finish_results_io2(form, cases)
def _add_user_geometry(self, csv_filename, name, color): """ helper method for ``on_load_user_geom`` A custom geometry can be the pyNastran custom form or an STL """ if name in self.gui.geometry_actors: msg = 'Name: %s is already in geometry_actors\nChoose a different name.' % name raise ValueError(msg) if len(name) == 0: msg = 'Invalid Name: name=%r' % name raise ValueError(msg) point_name = name + '_point' geom_name = name + '_geom' grid_ids, xyz, bars, tris, quads = load_user_geom(csv_filename, self.gui.log, encoding='latin1') nbars = len(bars) ntris = len(tris) nquads = len(quads) nelements = nbars + ntris + nquads self.gui.create_alternate_vtk_grid(point_name, color=color, opacity=1.0, point_size=5, representation='point') if nelements > 0: nid_map = {} i = 0 for nid in grid_ids: nid_map[nid] = i i += 1 self.gui.create_alternate_vtk_grid(geom_name, color=color, opacity=1.0, line_width=5, representation='toggle') # allocate nnodes = len(grid_ids) #self.alt_grids[point_name].Allocate(npoints, 1000) #if nelements > 0: #self.alt_grids[geom_name].Allocate(npoints, 1000) # set points points = numpy_to_vtk_points(xyz, dtype='<f') if nelements > 0: alt_grid = self.gui.alt_grids[point_name] geom_grid = self.gui.alt_grids[geom_name] for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: for i in range(nnodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, i) alt_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nbars: for i, bar in enumerate(bars[:, 1:]): g1 = nid_map[bar[0]] g2 = nid_map[bar[1]] elem = vtk.vtkLine() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) geom_grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if ntris: for i, tri in enumerate(tris[:, 1:]): g1 = nid_map[tri[0]] g2 = nid_map[tri[1]] g3 = nid_map[tri[2]] elem = vtk.vtkTriangle() elem.GetPointIds().SetId(0, g1) elem.GetPointIds().SetId(1, g2) elem.GetPointIds().SetId(2, g3) geom_grid.InsertNextCell(5, elem.GetPointIds()) if nquads: for i, quad in enumerate(quads[:, 1:]): g1 = nid_map[quad[0]] g2 = nid_map[quad[1]] g3 = nid_map[quad[2]] g4 = nid_map[quad[3]] elem = vtk.vtkQuad() point_ids = elem.GetPointIds() point_ids.SetId(0, g1) point_ids.SetId(1, g2) point_ids.SetId(2, g3) point_ids.SetId(3, g4) geom_grid.InsertNextCell(9, elem.GetPointIds()) alt_grid.SetPoints(points) if nelements > 0: self.gui.alt_grids[geom_name].SetPoints(points) # create actor/mapper self._add_alt_geometry(alt_grid, point_name) if nelements > 0: self._add_alt_geometry(geom_grid, geom_name)
def _get_bar_yz_arrays(self, model, bar_beam_eids, scale, debug): lines_bar_y = [] lines_bar_z = [] points_list = [] bar_types = { # PBAR 'bar' : [], # PBEAML/PBARL "ROD": [], "TUBE": [], "TUBE2" : [], "I": [], "CHAN": [], "T": [], "BOX": [], "BAR": [], "CROSS": [], "H": [], "T1": [], "I1": [], "CHAN1": [], "Z": [], "CHAN2": [], "T2": [], "BOX1": [], "HEXA": [], "HAT": [], "HAT1": [], "DBOX": [], # was 12 # PBEAM 'beam' : [], # PBEAML specfic "L" : [], } # for GROUP="MSCBML0" allowed_types = [ 'BAR', 'BOX', 'BOX1', 'CHAN', 'CHAN1', 'CHAN2', 'CROSS', 'DBOX', 'H', 'HAT', 'HAT1', 'HEXA', 'I', 'I1', 'L', 'ROD', 'T', 'T1', 'T2', 'TUBE', 'TUBE2', 'Z', 'bar', 'beam', ] # bar_types['bar'] = [ [...], [...], [...] ] #bar_types = defaultdict(lambda : defaultdict(list)) found_bar_types = set([]) #neids = len(self.element_ids) for bar_type, data in iteritems(bar_types): eids = [] lines_bar_y = [] lines_bar_z = [] bar_types[bar_type] = (eids, lines_bar_y, lines_bar_z) #bar_types[bar_type] = [eids, lines_bar_y, lines_bar_z] ugrid = vtk.vtkUnstructuredGrid() node0 = 0 nid_release_map = defaultdict(list) #debug = True bar_nids = set([]) #print('bar_beam_eids = %s' % bar_beam_eids) for eid in bar_beam_eids: if eid not in self.eid_map: self.log.error('eid=%s is not a valid bar/beam element...' % eid) if debug: # pragma: no cover print('eid=%s is not a valid bar/beam element...' % eid) continue #unused_ieid = self.eid_map[eid] elem = model.elements[eid] pid_ref = elem.pid_ref if pid_ref is None: pid_ref = model.Property(elem.pid) assert not isinstance(pid_ref, integer_types), elem ptype = pid_ref.type bar_type = _get_bar_type(ptype, pid_ref) if debug: # pragma: no cover print('%s' % elem) print(' bar_type =', bar_type) found_bar_types.add(bar_type) (nid1, nid2) = elem.node_ids bar_nids.update([nid1, nid2]) node1 = model.nodes[nid1] node2 = model.nodes[nid2] n1 = node1.get_position() n2 = node2.get_position() # wa/wb are not considered in i_offset # they are considered in ihat i = n2 - n1 Li = norm(i) ihat = i / Li if elem.pa != 0: nid_release_map[nid1].append((eid, elem.pa)) if elem.pb != 0: nid_release_map[nid2].append((eid, elem.pb)) unused_v, wa, wb, xform = rotate_v_wa_wb( model, elem, n1, n2, node1, node2, ihat, i, eid, Li) if wb is None: # one or more of v, wa, wb are bad continue yhat = xform[1, :] zhat = xform[2, :] ## concept has a GOO #if debug: # pragma: no cover #print(' centroid = %s' % centroid) #print(' ihat = %s' % ihat) #print(' yhat = %s' % yhat) #print(' zhat = %s' % zhat) #print(' scale = %s' % scale) #if eid == 616211: #print(' check - eid=%s yhat=%s zhat=%s v=%s i=%s n%s=%s n%s=%s' % ( #eid, yhat, zhat, v, i, nid1, n1, nid2, n2)) #print('adding bar %s' % bar_type) #print(' centroid=%s' % centroid) #print(' yhat=%s len=%s' % (yhat, np.linalg.norm(yhat))) #print(' zhat=%s len=%s' % (zhat, np.linalg.norm(zhat))) #print(' Li=%s scale=%s' % (Li, scale)) if bar_type not in allowed_types: msg = 'bar_type=%r allowed=[%s]' % (bar_type, ', '.join(allowed_types)) raise RuntimeError(msg) if bar_type in BEAM_GEOM_TYPES: node0 = add_3d_bar_element( bar_type, ptype, pid_ref, n1+wa, n2+wb, xform, ugrid, node0, points_list) centroid = (n1 + n2) / 2. bar_types[bar_type][0].append(eid) bar_types[bar_type][1].append((centroid, centroid + yhat * Li * scale)) bar_types[bar_type][2].append((centroid, centroid + zhat * Li * scale)) if node0: # and '3d_bars' not in self.alt_grids: def update_grid_function(unused_nid_map, ugrid, points, nodes): # pragma: no cover """custom function to update the 3d bars""" points_list = [] node0b = 0 for eid in bar_beam_eids: elem = self.model.elements[eid] pid_ref = elem.pid_ref if pid_ref is None: pid_ref = self.model.Property(elem.pid) assert not isinstance(pid_ref, integer_types), elem ptype = pid_ref.type bar_type = _get_bar_type(ptype, pid_ref) #nids = elem.nodes (nid1, nid2) = elem.node_ids node1 = model.nodes[nid1] node2 = model.nodes[nid2] i1, i2 = np.searchsorted(self.node_ids, [nid1, nid2]) n1 = nodes[i1, :] n2 = nodes[i2, :] #centroid = (n1 + n2) / 2. i = n2 - n1 Li = norm(i) ihat = i / Li unused_v, wa, wb, xform = rotate_v_wa_wb( model, elem, n1, n2, node1, node2, ihat, i, eid, Li) if wb is None: # one or more of v, wa, wb are bad continue ugridi = None node0b = add_3d_bar_element( bar_type, ptype, pid_ref, n1+wa, n2+wb, xform, ugridi, node0b, points_list, add_to_ugrid=False) points_array = _make_points_array(points_list) points_array2 = numpy_to_vtk( num_array=points_array, deep=1, array_type=vtk.VTK_FLOAT, ) points.SetData(points_array2) ugrid.SetPoints(points) points.Modified() ugrid.Modified() return if points_list: if not sys.argv[0].startswith('test_'): update_grid_function = None self.gui.create_alternate_vtk_grid( '3d_bars', color=BLUE, opacity=0.2, representation='surface', is_visible=True, follower_function=update_grid_function, ugrid=ugrid, ) points_array = _make_points_array(points_list) points = numpy_to_vtk_points(points_array) ugrid.SetPoints(points) #print('bar_types =', bar_types) for bar_type in list(bar_types): bars = bar_types[bar_type] if len(bars[0]) == 0: del bar_types[bar_type] continue #bar_types[bar_type][1] = np.array(bars[1], dtype='float32') # lines_bar_y #bar_types[bar_type][2] = np.array(bars[2], dtype='float32') # lines_bar_z debug = False if debug: # pragma: no cover #np.set_printoptions(formatter={'float': '{: 0.3f}'.format}) for bar_type, data in sorted(iteritems(bar_types)): eids, lines_bar_y, lines_bar_z = data if len(eids): #print('barsi =', barsi) #print('bar_type = %r' % bar_type) for eid, line_y, line_z in zip(eids, lines_bar_y, lines_bar_z): print('eid=%s centroid=%s cy=%s cz=%s' % ( eid, line_y[0], line_y[1], line_z[1])) #print('found_bar_types =', found_bar_types) #no_axial_torsion = (no_axial, no_torsion) #no_shear_bending = (no_shear_y, no_shear_z, no_bending_y, no_bending_z) #no_dofs = (no_bending, no_bending_bad, no_6_16, no_0_456, #no_0_56, no_56_456, no_0_6, no_0_16) return bar_nids, bar_types, nid_release_map
def _make_avus_geometry(self, model, quads_only=False): nodes = model.nodes #nnodes = self.nnodes grid = self.gui.grid mmax = amax(nodes, axis=0) mmin = amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.gui.create_global_axes(dim_max) points = numpy_to_vtk_points(nodes) #elements = model.elements quads = model.quad_elements hexas = model.hexa_elements tets = model.tet_elements tris = model.tri_elements nquads = len(quads) ntris = len(tris) nhexas = len(hexas) ntets = len(tets) is_shells = nquads + ntris is_solids = ntets + nhexas if is_shells: is_surface = True if nquads: elements = quads for face in quads: elem = vtkQuad() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) epoints.SetId(3, face[3]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if ntris: elements = tris for face in tris: elem = vtkTriangle() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(5, elem.GetPointIds()) elif is_solids: if ntets: elements = tets is_surface = False self.nelements = model.nelements grid.Allocate(self.nelements, 1000) nelements = elements.shape[0] for node_ids in elements: elem = vtkTetra() epoints = elem.GetPointIds() epoints.SetId(0, node_ids[0]) epoints.SetId(1, node_ids[1]) epoints.SetId(2, node_ids[2]) epoints.SetId(3, node_ids[3]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nhexas: elements = hexas is_surface = True # is_surface = False is_volume = not is_surface if is_surface: self.nelements = model.nelements free_faces = array(model.get_free_faces(), dtype='int32') # + 1 nfaces = len(free_faces) elements = free_faces grid.Allocate(nfaces, 1000) for face in free_faces: elem = vtkQuad() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) epoints.SetId(3, face[3]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) elif is_volume: self.nelements = model.nelements grid.Allocate(self.nelements, 1000) nelements = elements.shape[0] for eid in range(nelements): elem = vtkHexahedron() node_ids = elements[eid, :] epoints = elem.GetPointIds() epoints.SetId(0, node_ids[0]) epoints.SetId(1, node_ids[1]) epoints.SetId(2, node_ids[2]) epoints.SetId(3, node_ids[3]) epoints.SetId(4, node_ids[4]) epoints.SetId(5, node_ids[5]) epoints.SetId(6, node_ids[6]) epoints.SetId(7, node_ids[7]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: raise NotImplementedError() grid.SetPoints(points) grid.Modified() return is_surface
def _make_tecplot_geometry(self, model, quads_only=False): """ Returns ------- is_surface : bool the model is made up of only shells (not 100%) """ grid = self.gui.grid nnodes = self.gui.nnodes nodes = np.zeros((nnodes, 3), dtype='float32') #print('nnodes=', nnodes) inode = 0 quads = [] tris = [] tets = [] hexas = [] for zone in model.zones: nodes2d = zone.xy nodes3d = zone.xyz nnodes2d = nodes2d.shape[0] nnodes3d = nodes3d.shape[0] # elements if 'I' in zone.headers_dict: i = zone.headers_dict['I'] if 'J' in zone.headers_dict: j = zone.headers_dict['J'] nnodes = i * j elements = np.arange(0, nnodes).reshape(j, i) #print('elements:') #print(elements) n1 = elements[:-1, :-1].ravel() n2 = elements[:-1, 1:].ravel() n3 = elements[1:, 1:].ravel() n4 = elements[1:, :-1].ravel() nquads = (i - 1) * (j - 1) quadsi = np.vstack([n1, n2, n3, n4]).T #trisi = None #tetsi = None #hexasi = None trisi = [] tetsi = [] hexasi = [] else: quadsi = zone.quad_elements hexasi = zone.hexa_elements tetsi = zone.tet_elements trisi = zone.tri_elements if len(quadsi): quads.append(inode + quadsi) if len(trisi): tris.append(inode + trisi) if len(tetsi): tets.append(inode + tetsi) if len(hexasi): hexas.append(inode + hexasi) # nodes if nnodes2d and nnodes3d: raise RuntimeError('2d and 3d nodes is not supported') elif nnodes2d: nodes[inode:inode + nnodes2d, :2] = nodes2d inode += nnodes2d elif nnodes3d: nodes[inode:inode + nnodes3d] = nodes3d inode += nnodes3d else: # pragma: no cover raise RuntimeError('failed to find 2d/3d nodes') #print('inode', inode) #print(nodes) #print('-------------') #print('stack', len(quads)) quads = stack(quads) tris = stack(tris) tets = stack(tets) hexas = stack(hexas) nquads = len(quads) ntris = len(tris) nhexas = len(hexas) ntets = len(tets) nshells = nquads + ntris nsolids = ntets + nhexas if nshells: is_surface = True grid = self.gui.grid _create_tecplot_shells(grid, nquads, quads, ntris, tris) self.gui.nelements = nshells elif nsolids: #if 0: #tris, quads = model.skin_elements() #is_tris = bool(len(tris)) #is_quads = bool(len(quads)) #self._create_tecplot_shells(is_quads, quads, is_tris, tris) #else: is_surface = False grid = self.gui.grid nelements = _create_tecplot_solids(grid, zone, nsolids, ntets, tets, nhexas, hexas, is_surface=is_surface) self.gui.nelements = nelements else: raise NotImplementedError() #---------------------------------------------- #print('nnodes', nnodes, inode) mmax = np.amax(nodes, axis=0) mmin = np.amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.gui.create_global_axes(dim_max) #print('nodes', nodes) #nnodes = nodes.shape[0] points = numpy_to_vtk_points(nodes) grid.SetPoints(points) grid.Modified() return is_surface
def load_tetgen_geometry(self, smesh_filename, name='main', plot=True): skip_reading = self.gui._remove_old_geometry(smesh_filename) if skip_reading: return model = Tetgen(log=self.gui.log, debug=False) base_filename, ext = os.path.splitext(smesh_filename) ext = ext.lower() node_filename = base_filename + '.node' ele_filename = base_filename + '.ele' if ext == '.smesh': dimension_flag = 2 elif ext == '.ele': dimension_flag = 3 else: raise RuntimeError('unsupported extension. Use "smesh" or "ele".') model.read_tetgen(node_filename, smesh_filename, ele_filename, dimension_flag) nodes = model.nodes tris = model.tris tets = model.tets nnodes = nodes.shape[0] self.gui.nnodes = nodes.shape[0] ntris = 0 ntets = 0 if dimension_flag == 2: ntris = tris.shape[0] elif dimension_flag == 3: ntets = tets.shape[0] else: raise RuntimeError() nelements = ntris + ntets self.gui.nelements = nelements #print("nnodes = ",self.gui.nnodes) #print("nelements = ", self.gui.nelements) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) assert nodes is not None points = numpy_to_vtk_points(nodes) self.gui.nid_map = {} #elements -= 1 if dimension_flag == 2: etype = 5 # vtkTriangle().GetCellType() create_vtk_cells_of_constant_element_type(grid, tris, etype) elif dimension_flag == 3: etype = 10 # vtkTetra().GetCellType() create_vtk_cells_of_constant_element_type(grid, tets, etype) else: raise RuntimeError('dimension_flag=%r; expected=[2, 3]' % dimension_flag) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() # loadTetgenResults - regions/loads self.gui.scalarBar.VisibilityOff() self.gui.scalarBar.Modified() form, cases, node_ids, element_ids = self._fill_tetgen_case( nnodes, nelements) self.gui.node_ids = node_ids self.gui.element_ids = element_ids self.gui._finish_results_io2(form, cases, reset_labels=True)
def load_su2_geometry(self, su2_filename, name='main', plot=True): model_name = name skip_reading = self.gui._remove_old_geometry(su2_filename) if skip_reading: return model = SU2(log=self.gui.log, debug=False) #self.model_type = model.model_type ndim, nodes, elements, unused_regions = model.read_su2(su2_filename) nnodes = nodes.shape[0] nelements = 0 for etype, elems in elements.items(): nsub_elements = elems.shape[0] if nsub_elements: nelements += nsub_elements #print('min of type = %s' % elems.min()) assert nnodes > 0, nnodes assert nelements > 0, nelements self.gui.nnodes = nnodes self.gui.nelements = nelements self.gui.log.info('nnodes=%s nelements=%s' % (self.gui.nnodes, self.gui.nelements)) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) self.gui.nid_map = {} assert nodes is not None nnodes = nodes.shape[0] if ndim == 3: xmax, ymax, zmax = nodes.max(axis=0) xmin, ymin, zmin = nodes.min(axis=0) self.gui.log.info('xmax=%s xmin=%s' % (xmax, xmin)) self.gui.log.info('ymax=%s ymin=%s' % (ymax, ymin)) self.gui.log.info('zmax=%s zmin=%s' % (zmax, zmin)) dim_max = max(xmax - xmin, ymax - ymin, zmax - zmin) elif ndim == 2: xmax, ymax = nodes.max(axis=0) xmin, ymin = nodes.min(axis=0) self.gui.log.info('xmax=%s xmin=%s' % (xmax, xmin)) self.gui.log.info('ymax=%s ymin=%s' % (ymax, ymin)) dim_max = max(xmax - xmin, ymax - ymin) self.gui.create_global_axes(dim_max) if ndim == 2: nodes = np.hstack( [nodes, np.zeros((nnodes, 1), dtype=nodes.dtype)]) #else: # ndim=3 points = numpy_to_vtk_points(nodes) #nelements = 0 #elements = { #5 : tris, #9 : quads, #} #print('dict =', elements) for etype, elems in elements.items(): #print(etype, elems) if isinstance(elems, list): #print('continue') continue #print(type(elems)) nsub_elements = elems.shape[0] if nsub_elements == 0: #print('continue') continue #print('eid_min =', elems.min()) assert nsub_elements > 0, nsub_elements if etype == 5: for eid in range(nsub_elements): elem = vtkTriangle() node_ids = elems[eid, :] elem.GetPointIds().SetId(0, node_ids[0]) elem.GetPointIds().SetId(1, node_ids[1]) elem.GetPointIds().SetId(2, node_ids[2]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(5, elem.GetPointIds()) elif etype == 9: for eid in range(nsub_elements): elem = vtk.vtkQuad() node_ids = elems[eid, :] elem.GetPointIds().SetId(0, node_ids[0]) elem.GetPointIds().SetId(1, node_ids[1]) elem.GetPointIds().SetId(2, node_ids[2]) elem.GetPointIds().SetId(3, node_ids[3]) grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: raise NotImplementedError(etype) grid.SetPoints(points) grid.Modified() # loadSTLResults - regions/loads self.gui.scalar_bar_actor.VisibilityOff() self.gui.scalar_bar_actor.Modified() cases = OrderedDict() self.gui.isubcase_name_map = {} ID = 1 form, cases, node_ids, element_ids = self._fill_su2_case( cases, ID, nelements, nnodes) self.gui.node_ids = node_ids self.gui.element_ids = element_ids self.gui._finish_results_io2(model_name, form, cases)
def load_bedge_geometry(self, bedge_filename, name='main', plot=True): #skip_reading = self.remove_old_openfoam_geometry(openfoam_filename) #if skip_reading: # return self.gui.modelType = 'bedge' model = read_bedge(bedge_filename) self.gui.log.info('bedge_filename = %s' % bedge_filename) nnodes = model.nodes.shape[0] nbars = model.bars.shape[0] nelements = nbars nodes = model.nodes self.gui.nelements = nelements self.gui.nnodes = nnodes self.gui.log.debug("nNodes = %s" % self.gui.nnodes) self.gui.log.debug("nElements = %s" % self.gui.nelements) assert nelements > 0, nelements black = (0., 0., 0.) self.gui.create_alternate_vtk_grid('nodes', color=black, line_width=5, opacity=1., point_size=3, representation='point') alt_grid = self.gui.alt_grids['nodes'] alt_grid.Allocate(nnodes, 1000) grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) points = numpy_to_vtk_points(nodes) mmax = np.amax(nodes, axis=0) mmin = np.amin(nodes, axis=0) unused_dim_max = (mmax - mmin).max() self.gui.log.info('max = %s' % mmax) self.gui.log.info('min = %s' % mmin) #print('dim_max =', dim_max) #self.update_axes_length(dim_max) etype = 1 # vtk.vtkVertex().GetCellType() #elements = np.arange(0, len(nodes), dtype='int32') #assert len(elements) == len(nodes) #create_vtk_cells_of_constant_element_type(alt_grid, elements, etype) for inode, unused_node in enumerate(nodes): elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, inode) alt_grid.InsertNextCell(etype, elem.GetPointIds()) bars = model.bars etype = 3 # vtkLine().GetCellType() create_vtk_cells_of_constant_element_type(grid, bars, etype) self.gui.nelements = nelements alt_grid.SetPoints(points) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() #print("updated grid") # loadBedgeResults - regions/loads #self.TurnTextOn() self.gui.scalarBar.VisibilityOn() self.gui.scalarBar.Modified() self.gui.isubcase_name_map = {1: ['AFLR BEDGE', '']} cases = OrderedDict() ID = 1 self.gui._add_alt_actors(self.gui.alt_grids) form, cases = self._fill_bedge_case(bedge_filename, cases, ID, nnodes, nelements, model) if plot: self.gui._finish_results_io2(form, cases)
def get_inside_point_ids(self, ugrid, ugrid_flipped): """ The points that are returned from the frustum, despite being defined as inside are not all inside. The cells are correct though. If you determine the cells outside the volume and the points associated with that, and boolean the two, you can find the points that are actually inside. In other words, ``points`` corresponds to the points inside the volume and barely outside. ``point_ids_flipped`` corresponds to the points entirely outside the volume. Parameters ========== ugrid : vtk.vtkUnstructuredGrid() the "inside" grid ugrid_flipped : vtk.vtkUnstructuredGrid() the outside grid Returns ======= ugrid : vtk.vtkUnstructuredGrid() an updated grid that has the correct points nids : (n, ) int ndarray the node_ids """ nids = None points = ugrid.GetPointData() if points is None: return ugrid, nids ids = points.GetArray('Ids') if ids is None: return ugrid, nids # all points associated with the correctly selected cells are returned # but we get extra points for the cells that are inside and out point_ids = vtk_to_numpy(ids) nids = self.parent.get_node_ids(self.name, point_ids) # these are the points outside the box/frustum (and also include the bad point) points_flipped = ugrid_flipped.GetPointData() ids_flipped = points_flipped.GetArray('Ids') point_ids_flipped = vtk_to_numpy(ids_flipped) nids_flipped = self.parent.get_node_ids(self.name, point_ids_flipped) #nids = self.parent.gui.get_reverse_node_ids(self.name, point_ids_flipped) # setA - setB nids2 = np.setdiff1d(nids, nids_flipped, assume_unique=True) #narrays = points.GetNumberOfArrays() #for iarray in range(narrays): #name = points.GetArrayName(iarray) #print('iarray=%s name=%r' % (iarray, name)) #------------------ if self.representation == 'points': # we need to filter the nodes that were filtered by the # numpy setdiff1d, so we don't show extra points pointsu = ugrid.GetPoints() output_data = ugrid.GetPoints().GetData() points_array = numpy_support.vtk_to_numpy(output_data) # yeah! isort_nids = np.argsort(nids) nids = nids[isort_nids] inids = np.searchsorted(nids, nids2) points_array_sorted = points_array[isort_nids, :] point_array2 = points_array_sorted[inids, :] points2 = numpy_to_vtk_points(point_array2) npoints = len(nids2) ugrid = create_unstructured_point_grid(points2, npoints) nids = nids2 return ugrid, nids
def _make_tecplot_geometry(self, model, quads_only=False): nodes = model.xyz unused_nnodes = self.gui.nnodes grid = self.gui.grid mmax = amax(nodes, axis=0) mmin = amin(nodes, axis=0) dim_max = (mmax - mmin).max() self.gui.create_global_axes(dim_max) points = numpy_to_vtk_points(nodes) #elements = model.elements quads = model.quad_elements hexas = model.hexa_elements tets = model.tet_elements tris = model.tri_elements nquads = len(quads) ntris = len(tris) nhexas = len(hexas) ntets = len(tets) nshells = nquads + ntris nsolids = ntets + nhexas if nshells: is_surface = True self._create_tecplot_shells(nquads, quads, ntris, tris) self.gui.nelements = nshells elif nsolids: #if 0: #tris, quads = model.skin_elements() #is_tris = bool(len(tris)) #is_quads = bool(len(quads)) #self._create_tecplot_shells(is_quads, quads, is_tris, tris) #else: is_surface = False if is_surface: if nhexas: free_faces = array(model.get_free_faces(), dtype='int32') # + 1 nfaces = len(free_faces) self.gui.nelements = nfaces unused_elements = free_faces grid.Allocate(nfaces, 1000) for face in free_faces: elem = vtkQuad() epoints = elem.GetPointIds() epoints.SetId(0, face[0]) epoints.SetId(1, face[1]) epoints.SetId(2, face[2]) epoints.SetId(3, face[3]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: # is_volume grid.Allocate(nsolids, 1000) self.gui.nelements = nsolids if ntets: for node_ids in tets: elem = vtkTetra() epoints = elem.GetPointIds() epoints.SetId(0, node_ids[0]) epoints.SetId(1, node_ids[1]) epoints.SetId(2, node_ids[2]) epoints.SetId(3, node_ids[3]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) if nhexas: for node_ids in hexas: elem = vtkHexahedron() epoints = elem.GetPointIds() epoints.SetId(0, node_ids[0]) epoints.SetId(1, node_ids[1]) epoints.SetId(2, node_ids[2]) epoints.SetId(3, node_ids[3]) epoints.SetId(4, node_ids[4]) epoints.SetId(5, node_ids[5]) epoints.SetId(6, node_ids[6]) epoints.SetId(7, node_ids[7]) #elem.GetCellType() = 5 # vtkTriangle grid.InsertNextCell(elem.GetCellType(), elem.GetPointIds()) else: raise NotImplementedError() grid.SetPoints(points) grid.Modified() return is_surface
def load_obj_geometry(self, obj_filename, name='main', plot=True): """ The entry point for OBJ geometry loading. Parameters ---------- obj_filename : str the obj filename to load name : str the name of the "main" actor for the GUI plot : bool; default=True should the model be generated or should we wait until after the results are loaded """ skip_reading = self._remove_old_obj_geometry(obj_filename) if skip_reading: return log = self.gui.log self.gui.eid_maps[name] = {} self.gui.nid_maps[name] = {} model = read_obj(obj_filename, log=log, debug=False) self.model_type = 'obj' nodes = model.nodes nelements = model.nelements self.gui.nnodes = model.nnodes self.gui.nelements = nelements grid = self.gui.grid grid.Allocate(self.gui.nelements, 1000) assert nodes is not None #nnodes = nodes.shape[0] mmax = nodes.max(axis=0) mmin = nodes.min(axis=0) dim_max = (mmax - mmin).max() xmax, ymax, zmax = mmax xmin, ymin, zmin = mmin log.info("xmin=%s xmax=%s dx=%s" % (xmin, xmax, xmax - xmin)) log.info("ymin=%s ymax=%s dy=%s" % (ymin, ymax, ymax - ymin)) log.info("zmin=%s zmax=%s dz=%s" % (zmin, zmax, zmax - zmin)) self.gui.create_global_axes(dim_max) points = numpy_to_vtk_points(nodes) #assert elements.min() == 0, elements.min() tri_etype = 5 # vtkTriangle().GetCellType() #self.create_vtk_cells_of_constant_element_type(grid, elements, etype) quad_etype = 9 # vtk.vtkQuad().GetCellType() tris = model.tri_faces quads = model.quad_faces if len(tris): for eid, element in enumerate(tris): elem = vtk.vtkTriangle() elem.GetPointIds().SetId(0, element[0]) elem.GetPointIds().SetId(1, element[1]) elem.GetPointIds().SetId(2, element[2]) grid.InsertNextCell(tri_etype, elem.GetPointIds()) if len(quads): for eid, element in enumerate(quads): elem = vtk.vtkQuad() elem.GetPointIds().SetId(0, element[0]) elem.GetPointIds().SetId(1, element[1]) elem.GetPointIds().SetId(2, element[2]) elem.GetPointIds().SetId(3, element[3]) grid.InsertNextCell(quad_etype, elem.GetPointIds()) grid.SetPoints(points) grid.Modified() if hasattr(grid, 'Update'): # pragma: no cover grid.Update() self.gui.scalar_bar_actor.VisibilityOn() self.gui.scalar_bar_actor.Modified() self.gui.isubcase_name_map = {1: ['OBJ', '']} cases = OrderedDict() ID = 1 form, cases, icase, node_ids, element_ids = self._fill_obj_geometry_objects( cases, ID, nodes, nelements, model) self.gui.node_ids = node_ids self.gui.element_ids = element_ids self.gui._finish_results_io2(form, cases)