def load_shape_from_file(self, filename): """ This method loads a shape from the file `filename`. :param string filename: name of the input file. It should have proper extension (.step or .stp) :return: shape: loaded shape :rtype: TopoDS_Shape """ self._check_filename_type(filename) self._check_extension(filename) reader = STEPControl_Reader() return_reader = reader.ReadFile(filename) # check status if return_reader == IFSelect_RetDone: return_transfer = reader.TransferRoots() if return_transfer: # load all shapes in one shape = reader.OneShape() return shape else: raise RuntimeError("Shapes not loaded.") else: raise RuntimeError("Cannot read the file.")
def read_step_file(filename, return_as_shapes=False, verbosity=False): assert os.path.isfile(filename) step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status if verbosity: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) shapes = [] nr = 1 try: while True: ok = step_reader.TransferRoot(nr) if not ok: break _nbs = step_reader.NbShapes() shapes.append(step_reader.Shape(nr)) # a compound #assert not shape_to_return.IsNull() nr += 1 except: print("No Shape", nr) else: raise AssertionError("Error: can't read file.") return shapes
def read_step_file(filename, return_as_shapes=False, verbosity=False): """ read the STEP 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. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status if verbosity: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) transfer_result = step_reader.TransferRoot(1) assert transfer_result _nbs = step_reader.NbShapes() assert _nbs == 1 shape_to_return = step_reader.Shape(1) # a compound assert not shape_to_return.IsNull() else: raise AssertionError("Error: can't read file.") if return_as_shapes: shape_to_return = TopologyExplorer(shape_to_return).solids() return shape_to_return
def read_step_file(filename, verbosity=True): """ read the STEP file and returns a compound (based on OCC.Extend.DataExchange) filename: the file path return_as_shapes: optional, False by default. If True returns a list of shapes, else returns a single compound verbosity: optional, False by default. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status != IFSelect_RetDone: # check status raise AssertionError("Error: can't read file.") if verbosity: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) _nbr = step_reader.TransferRoots() _nbs = step_reader.NbShapes() shape_to_return = step_reader.OneShape() # a compound if shape_to_return is None: raise AssertionError("Shape is None.") elif shape_to_return.IsNull(): raise AssertionError("Shape is Null.") return shape_to_return
def upload_model(): if request.method == "POST": if request.files: model = request.files["model"] modelfile = os.path.join(app.config["MODEL_UPLOADS"], model.filename) model.save(modelfile) filename, file_extension = os.path.splitext(model.filename) #big_shp = read_step_file(modelfile) step_reader = STEPControl_Reader() status = step_reader.ReadFile(modelfile) if status == IFSelect_RetDone: ok = step_reader.TransferRoots() _nbs = step_reader.NbShapes() big_shp = step_reader.Shape() tess = ShapeTesselator(big_shp) tess.Compute(compute_edges=False, mesh_quality=0.5) jsonfile = filename + ".json" with open(os.path.join(app.config["MODEL_UPLOADS"], jsonfile), "w") as text_file: json_shape = tess.ExportShapeToThreejsJSONString(filename) json_shape = json_shape.replace("data\\", "data/") json_shape = json_shape.replace("\\step_postprocessed\\", "/step_postprocessed/") text_file.write(json_shape) else: raise Exception("error could not read step file") return redirect(url_for('modelview', modelname=jsonfile)) return render_template("public/upload.html")
class StepRead(object): """ Read a STEP file. :param str fn: The file to read. """ def __init__(self, fn): self._reader = STEPControl_Reader() self._tr = self._reader.WS().TransferReader() # Read file status = self._reader.ReadFile(fn) if status != IFSelect_RetDone: raise RuntimeError("Error reading STEP file.") # Convert to desired units Interface_Static.SetCVal("xstep.cascade.unit", Settings.units) # Transfer nroots = self._reader.TransferRoots() if nroots > 0: self._shape = Shape.wrap(self._reader.OneShape()) @property def object(self): """ :return: The STEP reader object. :rtype: OCC.Core.STEPControl.STEPControl_Reader """ return self._reader @property def shape(self): """ :return: The main shape. :rtype: afem.topology.entities.Shape """ return self._shape def name_from_shape(self, shape): """ Attempt to extract the name for the STEP entity that corresponds to the shape. :param afem.topology.entities.Shape shape: The shape. :return: The name or None if not found. :rtype: str or None """ item = self._tr.EntityFromShapeResult(shape.object, 1) if not item: return None return item.Name().ToCString()
def get_volume(stepfile): from OCC.Core.GProp import GProp_GProps from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.BRepGProp import brepgprop_VolumeProperties step_reader = STEPControl_Reader() step_reader.ReadFile(stepfile) step_reader.TransferRoot() shape = step_reader.Shape() prop = GProp_GProps() brepgprop_VolumeProperties(shape, prop, 1e-5) return prop.Mass()
def OpenCascadeMeshHierarchy(stepfile, element_size, levels, comm=COMM_WORLD, distribution_parameters=None, callbacks=None, order=1, mh_constructor=MeshHierarchy, cache=True, verbose=True, gmsh="gmsh", project_refinements_to_cad=True, reorder=None): # OpenCascade doesn't give a nice error message if stepfile # doesn't exist, it segfaults ... try: from OCC.Core.STEPControl import STEPControl_Reader from OCC.Extend.TopologyUtils import TopologyExplorer except ImportError: raise ImportError("To use OpenCascadeMeshHierarchy, you must install firedrake with the OpenCascade python bindings (firedrake-update --opencascade).") if not os.path.isfile(stepfile): raise OSError("%s does not exist" % stepfile) step_reader = STEPControl_Reader() step_reader.ReadFile(stepfile) step_reader.TransferRoot() shape = step_reader.Shape() cad = TopologyExplorer(shape) dim = 3 if cad.number_of_solids() > 0 else 2 coarse = make_coarse_mesh(stepfile, cad, element_size, dim, comm=comm, distribution_parameters=distribution_parameters, cache=cache, verbose=verbose, gmsh=gmsh) mh = mh_constructor(coarse, levels, distribution_parameters=distribution_parameters, callbacks=callbacks, reorder=reorder) project_to_cad = project_mesh_to_cad_2d if dim == 2 else project_mesh_to_cad_3d if project_refinements_to_cad: for mesh in mh: project_to_cad(mesh, cad) mh.nested = False if order > 1: VFS = VectorFunctionSpace Ts = [ Function(VFS(mesh, "CG", order)).interpolate(mesh.coordinates) for mesh in mh] ho_meshes = [Mesh(T) for T in Ts] mh = HierarchyBase( ho_meshes, mh.coarse_to_fine_cells, mh.fine_to_coarse_cells, refinements_per_level=mh.refinements_per_level, nested=mh.nested ) if project_refinements_to_cad: for mesh in mh: project_to_cad(mesh, cad) else: project_to_cad(mh[0], cad) for i in range(1, len(mh)): prolong(Ts[i-1], Ts[i]) return mh
def read_step_file(filename, return_as_shapes=False, verbosity=True): """ read the STEP 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: optional, False by default. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status if verbosity: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) shapes_to_return = [] for root_num in range(1, step_reader.NbRootsForTransfer() + 1): transfer_result = step_reader.TransferRoot(root_num) if not transfer_result: raise AssertionError("Transfer failed.") shape = step_reader.Shape(root_num) if shape.IsNull(): raise AssertionError("Shape is null.") shapes_to_return.append(shape) if return_as_shapes: return shapes_to_return builder = BRep_Builder() compound_shape = TopoDS_Compound() builder.MakeCompound(compound_shape) for shape in shapes_to_return: builder.Add(compound_shape, shape) return compound_shape else: raise AssertionError("Error: can't read file.")
def read_step(filename): from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = step_reader.TransferRoot(1) _nbs = step_reader.NbShapes() return step_reader.Shape(1) else: raise ValueError('Cannot read the file')
def load_model_file(filePath): step_reader = STEPControl_Reader() status = step_reader.ReadFile(filePath) if status == IFSelect_RetDone: # check status failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = step_reader.TransferRoot(1) nbs = step_reader.NbShapes() shape = step_reader.Shape(1) return shape else: raise Exception(":Error: can't read file - Method: load_STEP_file")
def read_step_file(filename): """ read the STEP file and returns a compound """ step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) step_reader.TransferRoot(1) a_shape = step_reader.Shape(1) else: print("Error: can't read file.") sys.exit(0) return a_shape
def read_step(file_name): step_reader = STEPControl_Reader() status = step_reader.ReadFile(file_name) if status == IFSelect_RetDone: # check status failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = step_reader.TransferRoot(1) _nbs = step_reader.NbShapes() aResShape = step_reader.Shape(1) return aResShape else: print("Error: can't read file.") sys.exit(0)
def read_step_file(filename): """ read the STEP file and returns a compound """ step_reader = STEPControl_Reader() logging.info("### Read Step File ###") status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status # failsonly = True # step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) # step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) step_reader.TransferRoot(1) a_shape = step_reader.Shape(1) else: logging.debug('Current Path:', os.getcwd()) logging.error("Error: can't read file.") sys.exit(0) return a_shape
def read_step_file(filename, as_compound=True, verbosity=True): """ read the STEP file and returns a compound filename: the file path verbosity: optional, False by default. as_compound: True by default. If there are more than one shape at root, gather all shapes into one compound. Otherwise returns a list of shapes. """ if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status if verbosity: failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) transfer_result = step_reader.TransferRoots() if not transfer_result: raise AssertionError("Transfer failed.") _nbs = step_reader.NbShapes() if _nbs == 0: raise AssertionError("No shape to transfer.") elif _nbs == 1: # most cases return step_reader.Shape(1) elif _nbs > 1: print("Number of shapes:", _nbs) shps = [] # loop over root shapes for k in range(1, _nbs + 1): new_shp = step_reader.Shape(k) if not new_shp.IsNull(): shps.append(new_shp) if as_compound: compound, result = list_of_shapes_to_compound(shps) if not result: print("Warning: all shapes were not added to the compound") return compound else: print("Warning, returns a list of shapes.") return shps else: raise AssertionError("Error: can't read file.") return None
def read_file(self): """ Read the STEP file and stores the result in a _shapes list """ stepcontrol_reader = STEPControl_Reader() status = stepcontrol_reader.ReadFile(self._filename) if status == IFSelect_RetDone: stepcontrol_reader.PrintCheckLoad(False, IFSelect_ItemsByEntity) nb_roots = stepcontrol_reader.NbRootsForTransfer() logger.info("%i root(s)" % nb_roots) if nb_roots == 0: msg = "No root for transfer" logger.error(msg) raise StepFileReadException(msg) stepcontrol_reader.PrintCheckTransfer(False, IFSelect_ItemsByEntity) self._number_of_shapes = stepcontrol_reader.NbShapes() for n in range(1, nb_roots + 1): logger.info("Root index %i" % n) ok = stepcontrol_reader.TransferRoot(n) logger.info("TransferRoots status : %i" % ok) if ok: # for i in range(1, self.nb_shapes + 1): a_shape = stepcontrol_reader.Shape(n) if a_shape.IsNull(): msg = "At least one shape in IGES cannot be transferred" logger.warning(msg) else: self._shapes.append(a_shape) logger.info("Appending a %s to list of shapes" % topo_types_dict[a_shape.ShapeType()]) else: msg = "One shape could not be transferred" logger.warning(msg) warnings.warn(msg) return True else: msg = "Status is not IFSelect_RetDone" logger.error(msg) raise StepFileReadException(msg)
def read_step_file(filename): """ read the STEP file and returns a compound """ print("loading STEP file... ") step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status failsonly = False ok = step_reader.TransferRoot(1) _nbs = step_reader.NbShapes() aResShape = step_reader.Shape(1) else: print("Error: can't read file.") sys.exit(0) print("done.") return aResShape
def read_step_file(filename): """ Read the STEP file and returns a shape. This cann't access any colour/name/layer atribute If these are used, please use the following method instead """ step_reader = STEPControl_Reader() status = step_reader.ReadFile(filename) if status == IFSelect_RetDone: # check status failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) step_reader.TransferRoot(1) step_reader.NbShapes() aResShape = step_reader.Shape(1) topo = Topo(aResShape) else: print("Error: can't read file.") sys.exit(0) return topo
def export_to_image(params): """ Метод формирует по исходному файлу изображение с заданным расширением """ # Проверяем что переданный путь существует if not os.path.isfile(params.get("path_to_cad")) or \ not os.access(params.get("path_to_cad"), os.R_OK): raise RuntimeError screen_size = (int(params.get("width")), int(params.get("height"))) # Запускаем виртуальный дисплей, на котором будем формировать gui xvfb_display = Display(visible=0, size=screen_size, bgcolor='black') xvfb_display.start() # Формируем площадку для отображения данных используя OpenCAD display, _, _, _ = init_display("wx", size=screen_size) # Вычитываем переданный файл с расширением .stp step_reader = STEPControl_Reader() step_reader.ReadFile(params.get("path_to_cad")) step_reader.TransferRoot() shape = step_reader.Shape() # Отображаем полученную фигуру display.DisplayShape(shape, update=True) # Снимаем дамп с экрана display.View.Dump(params.get("path_to_image")) # К сожалению, при работе через xvfb код выше # сохраняет данные только в формате bitmap, # из-за этого приходиться преобразовывать изображения вручную img = Image.open(params.get("path_to_image")) img.save(params.get("path_to_image")) xvfb_display.stop()
def importStep(fileName): """ Accepts a file name and loads the STEP file into a cadquery shape :param fileName: The path and name of the STEP file to be imported """ # Now read and return the shape reader = STEPControl_Reader() readStatus = reader.ReadFile(fileName) if readStatus != OCC.Core.IFSelect.IFSelect_RetDone: raise ValueError("STEP File could not be loaded") for i in range(reader.NbRootsForTransfer()): reader.TransferRoot(i + 1) occ_shapes = [] for i in range(reader.NbShapes()): occ_shapes.append(reader.Shape(i + 1)) # Make sure that we extract all the solids solids = [] for shape in occ_shapes: solids.append(Shape.cast(shape)) return cadquery.Workplane("XY").newObject(solids)
def create_labeled_hierarchy(coarse, stepfile, levels, order=1, comm=COMM_WORLD, distribution_parameters=None, callbacks=None, reorder=None): try: from OCC.Core.STEPControl import STEPControl_Reader from OCC.Extend.TopologyUtils import TopologyExplorer except ImportError: raise ImportError( "To use OpenCascadeMeshHierarchy, you must install firedrake with the OpenCascade python bindings (firedrake-update --opencascade)." ) if not os.path.isfile(stepfile): raise OSError("%s does not exist" % stepfile) project_refinements_to_cad = True step_reader = STEPControl_Reader() step_reader.ReadFile(stepfile) step_reader.TransferRoot() shape = step_reader.Shape() cad = TopologyExplorer(shape) mh = MeshHierarchy(coarse, levels, distribution_parameters=distribution_parameters, callbacks=callbacks, reorder=reorder) project_to_cad = project_mesh_to_cad_2d for mesh in mh: project_to_cad(mesh, cad) mh.nested = False if order > 1: VFS = VectorFunctionSpace Ts = [ Function(VFS(mesh, "CG", order)).interpolate(mesh.coordinates) for mesh in mh ] ho_meshes = [Mesh(T) for T in Ts] from collections import defaultdict for i, m in enumerate(ho_meshes): m._shared_data_cache = defaultdict(dict) for k in mh[i]._shared_data_cache: if k != "hierarchy_physical_node_locations": m._shared_data_cache[k] = mh[i]._shared_data_cache[k] mh = HierarchyBase(ho_meshes, mh.coarse_to_fine_cells, mh.fine_to_coarse_cells, refinements_per_level=mh.refinements_per_level, nested=mh.nested) if project_refinements_to_cad: for mesh in mh: project_to_cad(mesh, cad) else: project_to_cad(mh[0], cad) for i in range(1, len(mh)): prolong(Ts[i - 1], Ts[i]) return mh
def read_step(file_loc): step_reader = STEPControl_Reader() step_reader.ReadFile(file_loc) step_reader.TransferRoot() shape = step_reader.Shape() return shape
from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity from OCC.Display.SimpleGui import init_display step_reader = STEPControl_Reader() status = step_reader.ReadFile('./RFQ_noRMS_Spiral_Cut_90+angle_temp.stp') if status == IFSelect_RetDone: # check status failsonly = False step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity) step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity) ok = step_reader.TransferRoot(1) _nbs = step_reader.NbShapes() aResShape = step_reader.Shape(1) else: print("Error: can't read file.") sys.exit(0) from OCC.Core.DataExchange import read_iges display, start_display, add_menu, add_function_to_menu = init_display() display.DisplayShape(aResShape, update=True) start_display()
import numpy as np from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.TopAbs import TopAbs_FACE from OCC.Core.TopExp import TopExp_Explorer from OCC.Core.StepRepr import StepRepr_RepresentationItem from OCC.Core.BRepAdaptor import BRepAdaptor_Surface from OCC.Core.GeomAbs import GeomAbs_Cylinder from OCC.Core.TopoDS import topods # Read the file and get the shape reader = STEPControl_Reader() tr = reader.WS().TransferReader() reader.ReadFile('geometry_names.stp') reader.TransferRoots() shape = reader.OneShape() # Explore the faces of the shape (these are known to be named) exp = TopExp_Explorer(shape, TopAbs_FACE) while exp.More(): s = exp.Current() exp.Next() # Converting TopoDS_Shape to TopoDS_Face face = topods.Face(s) # Working on the geometry face_adaptor = BRepAdaptor_Surface(face) face_type = face_adaptor.GetType() if face_type == GeomAbs_Cylinder: cylinder = face_adaptor.Cylinder() entity = {}
def read_step_file_withnames( filename, breadface=False, breadedge=False ): #Read a step file with names attached to solid, faces (can be extended to edges) """""[Read a step file with names attached to solid, faces (can be extended to edges)] Arguments: filename {[type]} -- [path to the .stp file] Keyword Arguments: breadface {bool} -- [read the faces' names] (default: {False}) breadedge {bool} -- [read the edges' names] (default: {False}) Returns: (dSolids, dFaces, dEdges) -- [two dicts with name (int) as key and aShape as value] """ "" reader = STEPControl_Reader() #tr = reader.WS().GetObject().TransferReader().GetObject() tr = reader.WS().GetObject().TransferReader() reader.ReadFile(filename) reader.TransferRoots() shape = reader.OneShape() dSolids = dict( ) #solids initial as a dict with name (int) as key and aShape as value dFaces = dict( ) #faces initial as a dict with name (int) as key and aShape as value dEdges = dict( ) #edges initial as a dict with name (int) as key and aShape as value #read the solid names exp = TopExp_Explorer(shape, TopAbs_SOLID) while exp.More(): s = exp.Current() exp.Next() #Converting TopoDS_Shape to TopoDS_Face solid = topods.Solid(s) #Working on the name item = tr.EntityFromShapeResult(s, 1) if item == None: continue #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject() item = StepRepr_RepresentationItem.DownCast(item) name = item.Name().ToCString() if name: print('Found entity named: {}: {}.'.format(name, s)) nameid = int(name.split('_')[-1]) dSolids[nameid] = solid # read the face names if breadface: exp = TopExp_Explorer(shape, TopAbs_FACE) while exp.More(): s = exp.Current() exp.Next() #Converting TopoDS_Shape to TopoDS_Face face = topods.Face(s) #Working on the name item = tr.EntityFromShapeResult(s, 1) if item.IsNull(): continue #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject() item = StepRepr_RepresentationItem.DownCast(item) name = item.Name().GetObject().ToCString() if name: # print('Found entity named: {}: {}.'.format(name, s)) nameid = int(name.split('_')[-1]) dFaces[nameid] = face # read the edge names if breadedge: exp = TopExp_Explorer(shape, TopAbs_EDGE) while exp.More(): s = exp.Current() exp.Next() #Converting TopoDS_Shape to TopoDS_Face edge = topods.Edge(s) #Working on the name item = tr.EntityFromShapeResult(s, 1) if item.IsNull(): continue #item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject() item = StepRepr_RepresentationItem.DownCast(item) name = item.Name().GetObject().ToCString() if name: # print('Found entity named: {}: {}.'.format(name, s)) nameid = int(name.split('_')[-1]) dEdges[nameid] = edge ret = (dSolids, dFaces, dEdges) return ret