def read_iges_file(filename, return_as_shapes=False, verbosity=False): """ read the IGES file and returns a compound filename: the file path return_as_shapes: optional, False by default. If True returns a list of shapes, else returns a single compound verbosity: optionl, False by default. """ assert os.path.isfile(filename) iges_reader = IGESControl_Reader() status = iges_reader.ReadFile(filename) _shapes = [] if status == IFSelect_RetDone: # check status if verbosity: failsonly = False iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) iges_reader.TransferRoots() nbr = iges_reader.NbRootsForTransfer() for n in range(1, nbr + 1): nbs = iges_reader.NbShapes() if nbs == 0: print("At least one shape in IGES cannot be transfered") elif nbr == 1 and nbs == 1: aResShape = iges_reader.Shape(1) if aResShape.IsNull(): print("At least one shape in IGES cannot be transferred") else: _shapes.append(aResShape) else: for i in range(1, nbs + 1): aShape = iges_reader.Shape(i) if aShape.IsNull(): print( "At least one shape in STEP cannot be transferred") else: _shapes.append(aShape) # if not return as shapes # create a compound and store all shapes # TODO if not return_as_shapes: builder = BRep_Builder() Comp = TopoDS_Compound() builder.MakeCompound(Comp) for s in _shapes: builder.Add(Comp, s) _shapes = Comp return _shapes
def plot(self, plot_file=None, save_fig=False): """ Method to plot an iges file. If `plot_file` is not given it plots `self.infile`. :param string plot_file: the iges filename you want to plot. :param bool save_fig: a flag to save the figure in png or not. If True the plot is not shown. :return: figure: matlplotlib structure for the figure of the chosen geometry :rtype: matplotlib.pyplot.figure """ if plot_file is None: plot_file = self.infile else: self._check_filename_type(plot_file) ## read in the IGES file reader = IGESControl_Reader() reader.ReadFile(plot_file) reader.TransferRoots() shape = reader.Shape() stl_writer = StlAPI_Writer() # Do not switch SetASCIIMode() from False to True. stl_writer.SetASCIIMode(False) stl_writer.Write(shape, 'aux_figure.stl') # Create a new plot figure = pyplot.figure() axes = mplot3d.Axes3D(figure) # Load the STL files and add the vectors to the plot stl_mesh = mesh.Mesh.from_file('aux_figure.stl') os.remove('aux_figure.stl') axes.add_collection3d( mplot3d.art3d.Poly3DCollection(stl_mesh.vectors / 1000)) ## Get the limits of the axis and center the geometry max_dim = np.array([np.max(stl_mesh.vectors[:,:,0])/1000, \ np.max(stl_mesh.vectors[:,:,1])/1000, \ np.max(stl_mesh.vectors[:,:,2])/1000]) min_dim = np.array([np.min(stl_mesh.vectors[:,:,0])/1000, \ np.min(stl_mesh.vectors[:,:,1])/1000, \ np.min(stl_mesh.vectors[:,:,2])/1000]) max_lenght = np.max(max_dim - min_dim) axes.set_xlim(-.6 * max_lenght + (max_dim[0] + min_dim[0]) / 2, .6 * max_lenght + (max_dim[0] + min_dim[0]) / 2) axes.set_ylim(-.6 * max_lenght + (max_dim[1] + min_dim[1]) / 2, .6 * max_lenght + (max_dim[1] + min_dim[1]) / 2) axes.set_zlim(-.6 * max_lenght + (max_dim[2] + min_dim[2]) / 2, .6 * max_lenght + (max_dim[2] + min_dim[2]) / 2) # Show the plot to the screen if not save_fig: pyplot.show() else: figure.savefig(plot_file.split('.')[0] + '.png') return figure
def load_iges(self, path): """ Load an iges model """ reader = IGESControl_Reader() status = reader.ReadFile(path) if status != IFSelect_RetDone: raise ValueError("Failed to load: {}".format(path)) reader.PrintCheckLoad(False, IFSelect_ItemsByEntity) reader.PrintCheckTransfer(False, IFSelect_ItemsByEntity) ok = reader.TransferRoots() return reader.Shape(1)
def load_iges(filename): iges_reader = IGESControl_Reader() status = iges_reader.ReadFile(filename) if status != IFSelect_RetDone: raise IOError("IGES reader status = %s" % (str(status))) iges_reader.TransferRoots() # Not sure what this does BRepShape = iges_reader.Shape(1) return BRepShape
def read_file(self): """ Read the IGES file and stores the result in a list of TopoDS_Shape """ aReader = IGESControl_Reader() status = aReader.ReadFile(self._filename) if status == IFSelect_RetDone: failsonly = False aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) nbr = aReader.NbRootsForTransfer() aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) # ok = aReader.TransferRoots() for n in range(1, nbr + 1): self.nbs = aReader.NbShapes() if self.nbs == 0: print("At least one shape in IGES cannot be transfered") elif nbr == 1 and self.nbs == 1: aResShape = aReader.Shape(1) if aResShape.IsNull(): print( "At least one shape in IGES cannot be transferred") self._shapes.append(aResShape) else: for i in range(1, self.nbs + 1): aShape = aReader.Shape(i) if aShape.IsNull(): print( "At least one shape in STEP cannot be transferred" ) else: self._shapes.append(aShape) return True else: print("Error: can't read file %s" % self._filename) return False return False
def iges_importer(path_): from OCC.IGESControl import IGESControl_Reader from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity iges_reader = IGESControl_Reader() status = iges_reader.ReadFile(path_) if status == IFSelect_RetDone: # check status failsonly = False iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = iges_reader.TransferRoots() aResShape = iges_reader.Shape(1) return aResShape else: raise AssertionError("could not import IGES file: {0}".format(path_))
def load_shape_from_file(self, filename): """ This class method loads a shape from the file `filename`. :param string filename: name of the input file. It should have proper extension (.iges or .igs) :return: shape: loaded shape :rtype: TopoDS_Shape """ self._check_filename_type(filename) self._check_extension(filename) reader = IGESControl_Reader() reader.ReadFile(filename) reader.TransferRoots() shape = reader.Shape() return shape
def show(self, show_file=None): """ Method to show an iges file. If `show_file` is not given it plots `self.infile`. :param string show_file: the iges filename you want to show. """ if show_file is None: show_file = self.infile else: self._check_filename_type(show_file) # read in the IGES file reader = IGESControl_Reader() reader.ReadFile(show_file) reader.TransferRoots() shape = reader.Shape() display, start_display, __, __ = init_display() display.FitAll() display.DisplayShape(shape, update=True) # Show the plot to the screen start_display()
def parse(self, filename): """ Method to parse the file `filename`. It returns a matrix with all the coordinates. :param string filename: name of the input file. :return: mesh_points: it is a `n_points`-by-3 matrix containing the coordinates of the points of the mesh :rtype: numpy.ndarray """ self._check_filename_type(filename) self._check_extension(filename) self.infile = filename # read in the IGES file reader = IGESControl_Reader() reader.ReadFile(self.infile) reader.TransferRoots() shape = reader.Shape() # cycle on the faces to get the control points # init some quantities n_faces = 0 control_point_position = [0] faces_explorer = TopExp_Explorer(shape, TopAbs_FACE) mesh_points = np.zeros(shape=(0, 3)) while faces_explorer.More(): # performing some conversions to get the right format (BSplineSurface) iges_face = OCC.TopoDS.topods_Face(faces_explorer.Current()) iges_nurbs_converter = BRepBuilderAPI_NurbsConvert(iges_face) iges_nurbs_converter.Perform(iges_face) nurbs_face = iges_nurbs_converter.Shape() brep_face = BRep_Tool.Surface(OCC.TopoDS.topods_Face(nurbs_face)) bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face) # openCascade object occ_face = bspline_face.GetObject() # extract the Control Points of each face n_poles_u = occ_face.NbUPoles() n_poles_v = occ_face.NbVPoles() control_polygon_coordinates = np.zeros(shape=(n_poles_u * n_poles_v, 3)) # cycle over the poles to get their coordinates i = 0 for pole_u_direction in xrange(n_poles_u): for pole_v_direction in xrange(n_poles_v): control_point_coordinates = occ_face.Pole(pole_u_direction+1, pole_v_direction+1) control_polygon_coordinates[i, :] = [control_point_coordinates.X(), \ control_point_coordinates.Y(), control_point_coordinates.Z()] i += 1 # pushing the control points coordinates to the mesh_points array (used for FFD) mesh_points = np.append(mesh_points, control_polygon_coordinates, axis=0) control_point_position.append(control_point_position[-1] + n_poles_u * n_poles_v) n_faces += 1 faces_explorer.Next() self._control_point_position = control_point_position return mesh_points
def write(self, mesh_points, filename, tolerance=None): """ Writes a iges file, called filename, copying all the structures from self.filename but the coordinates. mesh_points is a matrix that contains the new coordinates to write in the iges file. :param numpy.ndarray mesh_points: it is a `n_points`-by-3 matrix containing the coordinates of the points of the mesh :param string filename: name of the output file. :param float tolerance: tolerance for the construction of the faces and wires in the write function. If not given it uses `self.tolerance`. """ self._check_filename_type(filename) self._check_extension(filename) self._check_infile_instantiation(self.infile) self.outfile = filename if tolerance is not None: self.tolerance = tolerance # init the ouput file writer writer = IGESControl_Writer() # read in the IGES file reader = IGESControl_Reader() reader.ReadFile(self.infile) reader.TransferRoots() shape_read = reader.Shape() # cycle on the faces to update the control points position # init some quantities faces_explorer = TopExp_Explorer(shape_read, TopAbs_FACE) n_faces = 0 control_point_position = self._control_point_position compound_builder = BRep_Builder() compound = OCC.TopoDS.TopoDS_Compound() compound_builder.MakeCompound(compound) while faces_explorer.More(): # similar to the parser method iges_face = OCC.TopoDS.topods_Face(faces_explorer.Current()) iges_nurbs_converter = BRepBuilderAPI_NurbsConvert(iges_face) iges_nurbs_converter.Perform(iges_face) nurbs_face = iges_nurbs_converter.Shape() face_aux = OCC.TopoDS.topods_Face(nurbs_face) brep_face = BRep_Tool.Surface(OCC.TopoDS.topods_Face(nurbs_face)) bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face) occ_face = bspline_face.GetObject() n_poles_u = occ_face.NbUPoles() n_poles_v = occ_face.NbVPoles() i = 0 for pole_u_direction in xrange(n_poles_u): for pole_v_direction in xrange(n_poles_v): control_point_coordinates = mesh_points[i+control_point_position[n_faces], :] point_xyz = gp_XYZ(control_point_coordinates[0], control_point_coordinates[1], \ control_point_coordinates[2]) gp_point = gp_Pnt(point_xyz) occ_face.SetPole(pole_u_direction+1, pole_v_direction+1, gp_point) i += 1 # construct the deformed wire for the trimmed surfaces wire_maker = BRepBuilderAPI_MakeWire() tol = ShapeFix_ShapeTolerance() brep = BRepBuilderAPI_MakeFace(occ_face.GetHandle(), self.tolerance).Face() brep_face = BRep_Tool.Surface(brep) # cycle on the edges edge_explorer = TopExp_Explorer(nurbs_face, TopAbs_EDGE) while edge_explorer.More(): edge = OCC.TopoDS.topods_Edge(edge_explorer.Current()) # edge in the (u,v) coordinates edge_uv_coordinates = OCC.BRep.BRep_Tool.CurveOnSurface(edge, face_aux) # evaluating the new edge: same (u,v) coordinates, but different (x,y,x) ones edge_phis_coordinates_aux = BRepBuilderAPI_MakeEdge(edge_uv_coordinates[0], brep_face) edge_phis_coordinates = edge_phis_coordinates_aux.Edge() tol.SetTolerance(edge_phis_coordinates, self.tolerance) wire_maker.Add(edge_phis_coordinates) edge_explorer.Next() # grouping the edges in a wire wire = wire_maker.Wire() # trimming the surfaces brep_surf = BRepBuilderAPI_MakeFace(occ_face.GetHandle(), wire).Shape() compound_builder.Add(compound, brep_surf) n_faces += 1 faces_explorer.Next() writer.AddShape(compound) writer.Write(self.outfile)
#!/usr/bin/python # coding: utf-8 r""" """ from __future__ import print_function import sys from OCC.IGESControl import IGESControl_Reader from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity from OCC.Display.SimpleGui import init_display iges_reader = IGESControl_Reader() status = iges_reader.ReadFile('./models/surf114.igs') if status == IFSelect_RetDone: # check status failsonly = False iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = iges_reader.TransferRoots() aResShape = iges_reader.Shape(1) else: print("Error: can't read file.") sys.exit(0) display, start_display, add_menu, add_function_to_menu = init_display('wx') display.DisplayShape(aResShape, update=True) start_display()