示例#1
0
文件: cad.py 项目: mmorse1217/cadmesh
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
示例#2
0
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 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()
示例#4
0
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.")
示例#6
0
    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")
示例#7
0
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')
示例#8
0
文件: load.py 项目: tnakaicode/OCCGO
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()
    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
示例#10
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
示例#11
0
    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
示例#13
0
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
示例#14
0
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()
示例#15
0
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)
示例#16
0
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
示例#17
0
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()
示例#18
0
 def read_step(file_loc):
     step_reader = STEPControl_Reader()
     step_reader.ReadFile(file_loc)
     step_reader.TransferRoot()
     shape = step_reader.Shape()
     return shape