Ejemplo n.º 1
0
def hash_edge_lenght_to_face(faces):
    """
    for every edge in the list `faces`

        loop through the edges of the face
        associate (hash) the edge lenght to point to the face


    :note: this approach would blow less if you use a tuple ( length, edge-mid-point )

    the TopoDS_Edge entitiy has a HashCode method
    that might be actually a proper idea

    :param faces:
    :return: dict hashing all edge lengths
    """
    _edge_length_to_face = {}
    _edge_length_to_edge = {}

    for f in faces:
        tp = TopologyExplorer(f)
        for e in tp.edges():
            length = round(length_from_edge(e), 3)
            _edge_length_to_face[length] = f
            _edge_length_to_edge[length] = e

    return _edge_length_to_face, _edge_length_to_edge
Ejemplo n.º 2
0
def import_into_gmsh_use_nativepointer(obj, geom_repr: str,
                                       model: gmsh.model) -> List[tuple]:
    from OCC.Extend.TopologyUtils import TopologyExplorer

    from ada import PrimBox

    ents = []
    if geom_repr == ElemType.SOLID:
        geom = obj.solid
        t = TopologyExplorer(geom)
        geom_iter = t.solids()
    elif geom_repr == ElemType.SHELL:
        geom = obj.shell if type(obj) not in (PrimBox, ) else obj.geom
        t = TopologyExplorer(geom)
        geom_iter = t.faces()
    else:
        geom = obj.line
        t = TopologyExplorer(geom)
        geom_iter = t.edges()

    for shp in geom_iter:
        ents += model.occ.importShapesNativePointer(int(shp.this))

    if len(ents) == 0:
        raise ValueError("No entities found")

    return ents
 def test_edge_to_bezier(self):
     b = BRepPrimAPI_MakeTorus(30, 10).Shape()
     t = TopologyExplorer(b)
     for ed in t.edges():
         is_bezier, bezier_curve, degree = edge_to_bezier(ed)
         self.assertTrue(isinstance(is_bezier, bool))
         if not is_bezier:
             self.assertTrue(degree is None)
             self.assertTrue(bezier_curve is None)
         else:
             self.assertTrue(isinstance(degree, int))
def build_curve_network(event=None):
    '''
    mimic the curve network surfacing command from rhino
    '''
    print('Importing IGES file...')
    iges_file = os.path.join('..', 'assets', 'models', 'curve_geom_plate.igs')
    iges = read_iges_file(iges_file)

    print('Building geomplate...')
    topo = TopologyExplorer(iges)
    edges_list = list(topo.edges())
    face = build_geom_plate(edges_list)
    print('done.')
    display.EraseAll()
    display.DisplayShape(edges_list)
    display.DisplayShape(face)
    display.FitAll()
    print('Cutting out of edges...')
Ejemplo n.º 5
0
 def test_discretize_edge(self):
     tor = BRepPrimAPI_MakeTorus(50, 20).Shape()
     topo = TopologyExplorer(tor)
     for edge in topo.edges():
         pnts = discretize_edge(edge)
         self.assertTrue(pnts)
 def test_discretize_edge(self):
     tor = BRepPrimAPI_MakeTorus(50, 20).Shape()
     topo = TopologyExplorer(tor)
     for edge in topo.edges():
         pnts = discretize_edge(edge)
         self.assertTrue(pnts)
Ejemplo n.º 7
0
def mesh_model(model, res_path, convert=True, all_edges=True):
    fil = model.split("/")[-1][:-5]
    folder = "/".join(model.split("/")[:-1])
    with fileinput.FileInput(model, inplace=True) as fi:
        for line in fi:
            print(line.replace(
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-06 )",
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-17 )"
            ),
                  end='')

    occ_steps = read_step_file(model)
    bt = BRep_Tool()

    for occ_cnt in range(len(occ_steps)):
        if convert:
            try:
                nurbs_converter = BRepBuilderAPI_NurbsConvert(
                    occ_steps[occ_cnt])
                nurbs_converter.Perform(occ_steps[occ_cnt])
                nurbs = nurbs_converter.Shape()
            except:
                print("Conversion failed")
                continue
        else:
            nurbs = occ_steps[occ_cnt]

        mesh = BRepMesh_IncrementalMesh(occ_steps[occ_cnt], 0.9, False, 0.5,
                                        True)
        mesh.Perform()
        if not mesh.IsDone():
            print("Mesh is not done.")
            continue

        occ_topo = TopologyExplorer(nurbs)
        occ_top = Topo(nurbs)
        occ_topo1 = TopologyExplorer(occ_steps[occ_cnt])
        occ_top1 = Topo(occ_steps[occ_cnt])

        d1_feats = []
        d2_feats = []
        t_curves = []
        tr_curves = []
        stats = {}
        stats["model"] = model
        total_edges = 0
        total_surfs = 0
        stats["curves"] = []
        stats["surfs"] = []
        c_cnt = 0
        t_cnt = 0

        # Iterate over edges
        for edge in occ_topo.edges():
            curve = BRepAdaptor_Curve(edge)
            stats["curves"].append(edge_map[curve.GetType()])
            d1_feat = convert_curve(curve)

            if edge_map[curve.GetType()] == "Other":
                continue

            for f in occ_top.faces_from_edge(edge):
                if f == None:
                    print("Broken face")
                    continue
                su = BRepAdaptor_Surface(f)
                c = BRepAdaptor_Curve2d(edge, f)
                t_curve = {
                    "surface": f,
                    "3dcurve": edge,
                    "3dcurve_id": c_cnt,
                    "2dcurve_id": t_cnt
                }
                t_curves.append(t_curve)
                tr_curves.append(convert_2dcurve(c))
                t_cnt += 1

            d1_feats.append(d1_feat)
            c_cnt += 1
            total_edges += 1

        patches = []
        faces1 = list(occ_topo1.faces())
        # Iterate over faces
        for fci, face in enumerate(occ_topo.faces()):
            surf = BRepAdaptor_Surface(face)
            stats["surfs"].append(surf_map[surf.GetType()])
            d2_feat = convert_surface(surf)

            if surf_map[surf.GetType()] == "Other":
                continue

            for tc in t_curves:
                if tc["surface"] == face:
                    patch = {
                        "3dcurves": [],
                        "2dcurves": [],
                        "orientations": [],
                        "surf_orientation": face.Orientation(),
                        "wire_ids": [],
                        "wire_orientations": []
                    }

                    for wc, fw in enumerate(occ_top.wires_from_face(face)):
                        patch["wire_orientations"].append(fw.Orientation())
                        if all_edges:
                            edges = [
                                i for i in WireExplorer(fw).ordered_edges()
                            ]
                        else:
                            edges = list(occ_top.edges_from_wire(fw))
                        for fe in edges:
                            for ttc in t_curves:
                                if ttc["3dcurve"].IsSame(fe) and tc[
                                        "surface"] == ttc["surface"]:
                                    patch["3dcurves"].append(ttc["3dcurve_id"])
                                    patch["2dcurves"].append(ttc["2dcurve_id"])
                                    patch["wire_ids"].append(wc)
                                    orientation = fe.Orientation()
                                    patch["orientations"].append(orientation)

                    patches.append(patch)
                    break

            location = TopLoc_Location()
            facing = (bt.Triangulation(faces1[fci], location))
            if facing != None:
                tab = facing.Nodes()
                tri = facing.Triangles()
                verts = []
                for i in range(1, facing.NbNodes() + 1):
                    verts.append(list(tab.Value(i).Coord()))

                faces = []
                for i in range(1, facing.NbTriangles() + 1):
                    index1, index2, index3 = tri.Value(i).Get()
                    faces.append([index1 - 1, index2 - 1, index3 - 1])

                os.makedirs(res_path, exist_ok=True)
                igl.write_triangle_mesh(
                    "%s/%s_%03i_mesh_%04i.obj" % (res_path, fil, occ_cnt, fci),
                    np.array(verts), np.array(faces))
                d2_feat["faces"] = faces
                d2_feat["verts"] = verts
            else:
                print("Missing triangulation")
                continue

            d2_feats.append(d2_feat)
            total_surfs += 1

        bbox = get_boundingbox(occ_steps[occ_cnt], use_mesh=False)
        xmin, ymin, zmin, xmax, ymax, zmax = bbox[:6]
        bbox1 = [
            "%.2f" % xmin,
            "%.2f" % ymin,
            "%.2f" % zmin,
            "%.2f" % xmax,
            "%.2f" % ymax,
            "%.2f" % zmax,
            "%.2f" % (xmax - xmin),
            "%.2f" % (ymax - ymin),
            "%.2f" % (zmax - zmin)
        ]
        stats["#edges"] = total_edges
        stats["#surfs"] = total_surfs

        # Fix possible orientation problems
        if convert:
            for p in patches:

                # Check orientation of first curve
                if len(p["2dcurves"]) >= 2:
                    cur = tr_curves[p["2dcurves"][0]]
                    nxt = tr_curves[p["2dcurves"][1]]
                    c_ori = p["orientations"][0]
                    n_ori = p["orientations"][1]
                    if c_ori == 0:
                        pole0 = np.array(cur["poles"][0])
                        pole1 = np.array(cur["poles"][-1])
                    else:
                        pole0 = np.array(cur["poles"][-1])
                        pole1 = np.array(cur["poles"][0])

                    if n_ori == 0:
                        pole2 = np.array(nxt["poles"][0])
                        pole3 = np.array(nxt["poles"][-1])
                    else:
                        pole2 = np.array(nxt["poles"][-1])
                        pole3 = np.array(nxt["poles"][0])

                    d02 = np.abs(pole0 - pole2)
                    d12 = np.abs(pole1 - pole2)
                    d03 = np.abs(pole0 - pole3)
                    d13 = np.abs(pole1 - pole3)

                    amin = np.argmin([d02, d12, d03, d13])

                    if amin == 0 or amin == 2:  # Orientation of first curve incorrect, fix
                        p["orientations"][0] = abs(c_ori - 1)

                # Fix all orientations
                for i in range(len(p["2dcurves"]) - 1):
                    cur = tr_curves[p["2dcurves"][i]]
                    nxt = tr_curves[p["2dcurves"][i + 1]]
                    c_ori = p["orientations"][i]
                    n_ori = p["orientations"][i + 1]
                    if c_ori == 0:
                        pole1 = np.array(cur["poles"][-1])
                    else:
                        pole1 = np.array(cur["poles"][0])

                    if n_ori == 0:
                        pole2 = np.array(nxt["poles"][0])
                        pole3 = np.array(nxt["poles"][-1])
                    else:
                        pole2 = np.array(nxt["poles"][-1])
                        pole3 = np.array(nxt["poles"][0])

                    d12 = np.abs(pole1 - pole2)
                    d13 = np.abs(pole1 - pole3)

                    amin = np.min([d12, d13])

                    if amin == 1:  # Incorrect orientation, flip
                        p["orientations"][i + 1] = abs(n_ori - 1)

        features = {
            "curves": d1_feats,
            "surfaces": d2_feats,
            "trim": tr_curves,
            "topo": patches,
            "bbox": bbox1
        }

        os.makedirs(res_path, exist_ok=True)
        fip = fil + "_features2"
        with open("%s/%s_%03i.yml" % (res_path, fip, occ_cnt), "w") as fili:
            yaml.dump(features, fili, indent=2)

        fip = fil + "_features"
        with open("%s/%s_%03i.yml" % (res_path, fip, occ_cnt), "w") as fili:
            features2 = copy.deepcopy(features)
            for sf in features2["surfaces"]:
                del sf["faces"]
                del sf["verts"]
            yaml.dump(features2, fili, indent=2)


#        res_path = folder.replace("/step/", "/stat/")
#        fip = fil + "_stats"
#        with open("%s/%s_%03i.yml"%(res_path, fip, occ_cnt), "w") as fili:
#            yaml.dump(stats, fili, indent=2)

    print("Writing results for %s with %i parts." % (model, len(occ_steps)))
Ejemplo n.º 8
0
def mesh_model(model, max_size=1e-5, tolerance=1e-7, repair=False, terminal=1):
    # In/Output definitions
    fil = model.split("/")[-1][:-5]
    folder = "/".join(model.split("/")[:-1])
    scale_factor = 1000.0
    verts = []
    norms = []
    faces = []
    curvs = []
    vert_map = {}
    d1_feats = []
    d2_feats = []
    t_curves = []
    #norm_map = {}
    with fileinput.FileInput(model, inplace=True) as fi:
        for line in fi:
            print(line.replace(
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-06 )",
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-17 )"
            ),
                  end='')

    stats = {}

    # OCC definitions
    occ_steps = read_step_file(model)
    stats["#parts"] = len(occ_steps)
    stats["model"] = model
    print("Reading step %s with %i parts." % (model, len(occ_steps)))
    #tot = 0
    #for s in occ_steps:
    #    occ_topo = TopologyExplorer(s)
    #    print(s)
    #    print(len(list(occ_topo.edges())))
    #    tot += len(list(occ_topo.edges()))
    occ_cnt = 0
    bbox = get_boundingbox(occ_steps[occ_cnt], use_mesh=True)
    diag = np.sqrt(bbox[6]**2 + bbox[7]**2 + bbox[8]**2)
    max_length = diag * max_size  #, 9e-06
    tolerance = diag * tolerance
    #print(fil, diag, max_length, tolerance)
    stats["bbox"] = bbox
    stats["max_length"] = float(max_length)
    stats["tolerance"] = float(tolerance)
    stats["diag"] = float(diag)

    occ_topo = TopologyExplorer(occ_steps[occ_cnt])
    occ_top = Topo(occ_steps[occ_cnt])
    occ_props = GProp_GProps()
    occ_brt = BRep_Tool()

    # Gmsh definitions
    gmsh.initialize()
    gmsh.clear()
    gmsh.option.setNumber("General.Terminal", terminal)
    gmsh.option.setNumber("Geometry.Tolerance", tolerance)
    gmsh.option.setNumber("Geometry.OCCFixDegenerated", 0)
    gmsh.option.setNumber("Geometry.OCCFixSmallEdges", 0)
    gmsh.option.setNumber("Geometry.OCCFixSmallFaces", 0)
    gmsh.option.setNumber("Geometry.OCCSewFaces", 0)
    gmsh.option.setNumber("Mesh.CharacteristicLengthMax", max_length)
    gmsh.open(model)

    # Gmsh meshing
    #gmsh.model.mesh.generate(1)
    #gmsh.model.mesh.refine()
    #gmsh.model.mesh.refine()
    gmsh.model.mesh.generate(2)
    #gmsh.write("results/" + file + ".stl")
    gmsh_edges = gmsh.model.getEntities(1)
    gmsh_surfs = gmsh.model.getEntities(2)
    #print("O", tot, "G", len(gmsh_edges))
    #continue
    gmsh_entities = gmsh.model.getEntities()
    #gmsh.model.occ.synchronize()
    #print(dir(gmsh.model.occ))
    total_edges = 0
    total_surfs = 0
    for l in range(len(occ_steps)):
        topo = TopologyExplorer(occ_steps[l])
        total_edges += len(list(topo.edges()))
        total_surfs += len(list(topo.faces()))

        vol = brepgprop_VolumeProperties(occ_steps[l], occ_props, tolerance)
        #print(dir(occ_props), dir(occ_props.PrincipalProperties()), dir(occ_props.volume()), occ_props.Mass())
        sur = brepgprop_SurfaceProperties(occ_steps[l], occ_props, tolerance)
        #print(vol, "Test", sur)

    stats["#edges"] = total_edges
    stats["#surfs"] = total_surfs
    stats["volume"] = vol
    stats["surface"] = sur
    stats["curves"] = []
    stats["surfs"] = []
    stats["#points"] = 0
    print("Number of surfaces: %i, Number of curves: %i" %
          (total_surfs, total_edges))
    #print(total_edges, total_surfs, len(gmsh_edges), len(gmsh_surfs))
    if not total_edges == len(gmsh_edges):
        print("Skipping due to wrong EDGES", model)
        return
    if not total_surfs == len(gmsh_surfs):
        print("Skipping due to wrong SURFS", model)
        return

    #print("Reading curvature")
    v_cnt = 1
    v_nodes = []
    occ_offset = 0
    invalid_model = False
    c_cnt = 0

    #v_cont_cnt = 0
    #print(len(list(occ_topo.edges())), len(list(occ_topo.solids())), len(list(occ_topo.faces())), len(list(occ_topo.vertices())))
    for e in gmsh_entities[:]:
        #print(e)
        nodeTags, nodeCoords, nodeParams = gmsh.model.mesh.getNodes(
            e[0], e[1], True)
        elemTypes, elemTags, elemNodeTags = gmsh.model.mesh.getElements(
            e[0], e[1])
        n_id = e[1] - occ_offset
        #print(e, occ_offset, n_id)
        #print(e, nodeTags, nodeCoords, nodeParams, gmsh.model.getType(e[0], e[1]), elemTypes, elemTags, elemNodeTags)
        if e[0] == 0:  # Process points
            #print(e[1], nodeCoords)
            vert_map[e[1]] = v_cnt
            verts.append([
                nodeCoords[0] * 1000.0, nodeCoords[1] * 1000.0,
                nodeCoords[2] * 1000.0
            ])
            v_cnt += 1
            stats["#points"] += 1

            #pass
        if e[0] == 1:  # Process contours
            if n_id - 1 == len(list(occ_topo.edges())):
                #print("CNT", occ_cnt)
                occ_cnt += 1
                occ_offset = e[1] - 1
                n_id = 1
                occ_topo = TopologyExplorer(occ_steps[occ_cnt])
                occ_top = Topo(occ_steps[occ_cnt])
                #print("Defunct curve", n_id, len(list(occ_topo.edges())))
                #continue
            #print(n_id)
            curve = BRepAdaptor_Curve(list(occ_topo.edges())[n_id - 1])
            # Add type and parametric nodes/indices
            #print("type", edge_map[curve.GetType()])
            if gmsh.model.getType(e[0], e[1]) == "Unknown":
                #print("Skipping OtherCurve", nodeTags)
                continue

            for i, n in enumerate(nodeTags):
                if n >= v_cnt:
                    vert_map[n] = v_cnt
                    verts.append([
                        nodeCoords[i * 3] * 1000.0,
                        nodeCoords[i * 3 + 1] * 1000.0,
                        nodeCoords[i * 3 + 2] * 1000.0
                    ])
                    v_cnt += 1
                else:
                    print(n, v_cnt)

            #print(v_ind, type(v_ind), v_par, type(v_par))
            stats["curves"].append(edge_map[curve.GetType()])
            #print(n_id, edge_map[curve.GetType()], gmsh.model.getType(e[0], e[1]))
            #print(list(occ_topo.edges()), n_id-1)
            c_type = edge_map[curve.GetType()]  #gmsh.model.getType(e[0], e[1])
            if not gmsh.model.getType(e[0], e[1]) == edge_map[curve.GetType()]:
                print("Skipped due to non matching edges ", model,
                      gmsh.model.getType(e[0], e[1]),
                      edge_map[curve.GetType()])
                #invalid_model = True
                #break

            d1_feat = convert_curve(curve)

            edg = list(occ_topo.edges())[n_id - 1]

            for f in occ_top.faces_from_edge(edg):
                #ee = (e)
                #print(dir(ee))
                #d1_feat = {}
                su = BRepAdaptor_Surface(f)
                c = BRepAdaptor_Curve2d(edg, f)
                t_curve = {
                    "surface": f,
                    "3dcurve": c_cnt,
                    "2dcurve": convert_2dcurve(c)
                }
                #print(edge_map[c.GetType()], surf_map[su.GetType()], edge_map[curve.GetType()])
                #d1f = convert_2dcurve(c)
                #print(d1f)
                #ccnt += 1
                #print(d1_feat)
                t_curves.append(t_curve)

            if len(elemNodeTags) > 0:
                #v_ind = [int(elemNodeTags[0][0]) - 1] # first vertex
                v_ind = [int(nodeTags[-2]) - 1]
                for no in nodeTags[:-2]:
                    v_ind.append(int(no) - 1)  # interior vertices
                v_ind.append(int(nodeTags[-1]) - 1)
                #v_ind.append(int(elemNodeTags[0][-1]) - 1) # last vertex
                d1_feat["vert_indices"] = v_ind
                #v_par = [float(curve.FirstParameter())] # first param
                v_par = [float(nodeParams[-2] * scale_factor)]
                for no in nodeParams[:-2]:
                    v_par.append(float(no * scale_factor))  # interior params
                v_par.append(float(nodeParams[-1] * scale_factor))
                #v_par.append(float(curve.LastParameter())) # last param
                d1_feat["vert_parameters"] = v_par
            else:
                print("No nodetags", edge_map[curve.GetType()], elemNodeTags)

            #print("VERTS", len(d1_feat["vert_indices"]), len(d1_feat["vert_parameters"]))
            d1_feats.append(d1_feat)
            c_cnt += 1
            #t_curve = curve.Trim(curve.FirstParameter(), curve.LastParameter(), 0.0001).GetObject()
            #print(curve.FirstParameter(), curve.LastParameter())

    #print("Processing surfaces")
    gmsh_entities = gmsh.model.getEntities(2)
    n_cnt = 1
    occ_offset = 0
    occ_cnt = 0
    occ_topo = TopologyExplorer(occ_steps[occ_cnt])
    occ_top = Topo(occ_steps[occ_cnt])
    f_cnt = 0
    f_sum = 0
    first_face = True
    mean_curv = 0.0
    curv_cnt = 0
    gaus_curv = 0.0
    s_cnt = 0

    for e in gmsh_entities[:]:
        #print(e)
        nodeTags, nodeCoords, nodeParams = gmsh.model.mesh.getNodes(
            e[0], e[1], True)
        elemTypes, elemTags, elemNodeTags = gmsh.model.mesh.getElements(
            e[0], e[1])
        n_id = e[1] - occ_offset
        #print(e, occ_offset, n_id)
        #print(e, nodeTags, nodeCoords, nodeParams, gmsh.model.getType(e[0], e[1]), elemTypes, elemTags, elemNodeTags)
        if e[0] == 2:
            #print(e, gmsh.model.getType(e[0], e[1]), elemTypes)
            if n_id - 1 == len(list(occ_topo.faces())):
                #print("CNT", occ_cnt)
                occ_cnt += 1
                occ_offset = e[1] - 1
                n_id = 1
                occ_topo = TopologyExplorer(occ_steps[occ_cnt])
                occ_top = Topo(occ_steps[occ_cnt])
            if "getNormals" in dir(gmsh.model):
                nls = gmsh.model.getNormals(e[1], nodeParams)
            else:
                nls = gmsh.model.getNormal(e[1], nodeParams)
            curvMax, curvMin, dirMax, dirMin = gmsh.model.getPrincipalCurvatures(
                e[1], nodeParams)
            #surf = BRepAdaptor_Surface(list(occ_topo.faces())[n_id-1])
            norm_map = {}
            for i, n in enumerate(nodeTags):
                norms.append([nls[i * 3], nls[i * 3 + 1], nls[i * 3 + 2]])
                curvs.append([
                    curvMin[i], curvMax[i], dirMin[i * 3], dirMin[i * 3 + 1],
                    dirMin[i * 3 + 2], dirMax[i * 3], dirMax[i * 3 + 1],
                    dirMax[i * 3 + 2]
                ])
                curv_cnt += 1
                mean_curv += (curvMin[i] + curvMax[i]) / 2.0
                gaus_curv += (curvMin[i] * curvMax[i])
                norm_map[n] = n_cnt
                n_cnt += 1
                if n in vert_map.keys():
                    v = verts[vert_map[n] - 1]
                    #print("Vert contained", n)
                    #v_cont_cnt += 1
                    #                    assert(v[0] == nodeCoords[i*3] * 1000.0 and v[1] == nodeCoords[i*3+1] * 1000.0 and v[2] == nodeCoords[i*3+2] * 1000.0)
                    continue
                else:
                    vert_map[n] = v_cnt
                #occ_node = surf.Value(nodeParams[i], nodeParams[i+1])
                #vertices.append([occ_node.X(), occ_node.Y(), occ_node.Z()])
                verts.append([
                    nodeCoords[i * 3] * 1000.0, nodeCoords[i * 3 + 1] * 1000.0,
                    nodeCoords[i * 3 + 2] * 1000.0
                ])
                #print("S", occ_node.Coord(), [nodeCoords[i*3]*1000, nodeCoords[i*3+1]*1000, nodeCoords[i*3+2]*1000])
                #print(occ_node.Coord(), nodeCoords[i*3:(i+1)*3])
                v_cnt += 1

            d2_faces = []
            for i, t in enumerate(elemTypes):
                for j in range(len(elemTags[i])):
                    faces.append([
                        vert_map[elemNodeTags[i][j * 3]],
                        vert_map[elemNodeTags[i][j * 3 + 1]],
                        vert_map[elemNodeTags[i][j * 3 + 2]],
                        norm_map[elemNodeTags[i][j * 3]],
                        norm_map[elemNodeTags[i][j * 3 + 1]],
                        norm_map[elemNodeTags[i][j * 3 + 2]]
                    ])
                    d2_faces.append(f_cnt)
                    f_cnt += 1
            #print(len(list(occ_topo.faces())), n_id-1)
            surf = BRepAdaptor_Surface(list(occ_topo.faces())[n_id - 1])
            #print("type", edge_map[curve.GetType()])
            #if gmsh.model.getType(e[0], e[1]) == "Unknown":
            #    print("Skipping OtherCurve", nodeTags)
            #    continue
            #print(surf)
            g_type = gmsh_map[gmsh.model.getType(e[0], e[1])]
            if g_type != "Other" and not g_type == surf_map[surf.GetType()]:
                print("Skipped due to non matching surfaces ", model, g_type,
                      surf_map[surf.GetType()])
                #invalid_model = True
                #break

            stats["surfs"].append(surf_map[surf.GetType()])

            d2_feat = convert_surface(surf)
            d2_feat["face_indices"] = d2_faces

            for tc in t_curves:
                if tc["surface"] == list(occ_topo.faces())[n_id - 1]:
                    tc["surface"] = s_cnt

            if len(elemNodeTags) > 0:
                #print(len(elemNodeTags[0]), len(nodeTags), len(nodeParams))
                v_ind = []  #int(elemNodeTags[0][0])] # first vertex
                for no in nodeTags:
                    v_ind.append(int(no) - 1)  # interior vertices
                #v_ind.append(int(elemNodeTags[0][-1])) # last vertex
                d2_feat["vert_indices"] = v_ind
                v_par = []  #float(surf.FirstParameter())] # first param
                for io in range(int(len(nodeParams) / 2)):
                    v_par.append([
                        float(nodeParams[io * 2] * scale_factor),
                        float(nodeParams[io * 2 + 1] * scale_factor)
                    ])  # interior params
                #v_par.append(float(surf.LastParameter())) # last param
                d2_feat["vert_parameters"] = v_par
            else:
                print("No nodetags", edge_map[curve.GetType()], elemNodeTags)

            f_sum += len(d2_feat["face_indices"])
            d2_feats.append(d2_feat)
            s_cnt += 1

    if invalid_model:
        return

    stats["#sharp"] = 0
    stats["gaus_curv"] = float(gaus_curv / curv_cnt)
    stats["mean_curv"] = float(mean_curv / curv_cnt)

    if not f_sum == len(faces):
        print("Skipping due to wrong FACES", model)
        return
    if True:
        vert2norm = {}
        for f in faces:
            #print(f)
            for fii in range(3):
                if f[fii] in vert2norm:
                    vert2norm[f[fii]].append(f[fii + 3])
                else:
                    vert2norm[f[fii]] = [f[fii + 3]]
        for d1f in d1_feats:
            sharp = True
            for vi in d1f["vert_indices"][1:-1]:
                #print(vi, vert2norm.keys())
                nos = list(set(vert2norm[vi + 1]))
                if len(nos) == 2:
                    n0 = np.array(norms[nos[0]])
                    n1 = np.array(norms[nos[1]])
                    #print(np.linalg.norm(n0), np.linalg.norm(n1))
                    if np.abs(n0.dot(n1)) > 0.95:
                        sharp = False
                        #break
                else:
                    sharp = False
            if sharp:
                stats["#sharp"] += 1
            d1f["sharp"] = sharp

    stats["#verts"] = len(verts)
    stats["#faces"] = len(faces)
    stats["#norms"] = len(norms)

    #with open("results/" + file + ".json", "w") as fil:
    #    json.dump(d1_feats, fil, sort_keys=True, indent=2)
    #with open("results/" + file + "_faces.json", "w") as fil:
    #   json.dump(d2_feats, fil, sort_keys=True, indent=2)

    features = {"curves": d1_feats, "surfaces": d2_feats, "trim": t_curves}
    if True:
        res_path = folder.replace("/step/", "/feat/")
        fip = fil.replace("_step_", "_features_")
        print("%s/%s.yml" % (res_path, fip))
        with open("%s/%s.yml" % (res_path, fip), "w") as fili:
            yaml.dump(features, fili, indent=2)

        res_path = folder.replace("/step/", "/stat/")
        fip = fil.replace("_step_", "_stats_")
        with open("%s/%s.yml" % (res_path, fip), "w") as fili:
            yaml.dump(stats, fili, indent=2)

        print("Generated model with %i vertices and %i faces." %
              (len(verts), len(faces)))
        res_path = folder.replace("/step/", "/obj/")
        fip = fil.replace("_step_", "_trimesh_")
        with open("%s/%s.obj" % (res_path, fip), "w") as fili:
            for v in verts:
                fili.write("v %f %f %f\n" % (v[0], v[1], v[2]))
            for vn in norms:
                #print(np.linalg.norm(vn))
                fili.write("vn %f %f %f\n" % (vn[0], vn[1], vn[2]))
            for vn in curvs:
                fili.write(
                    "vc %f %f %f %f %f %f %f %f\n" %
                    (vn[0], vn[1], vn[2], vn[3], vn[4], vn[5], vn[6], vn[7]))
            for f in faces:
                fili.write("f %i//%i %i//%i %i//%i\n" %
                           (f[0], f[3], f[1], f[4], f[2], f[5]))

        faces = np.array(faces)
        face_indices = faces[:, :3] - 1
        norm_indices = faces[:, 3:] - 1
    gmsh.clear()
    gmsh.finalize()
    #print(curvs)
    return {
        "statistics": stats,
        "features": features,
        "vertices": np.array(verts),
        "normals": np.array(norms),
        "curvatures": np.array(curvs),
        "face_indices": face_indices,
        "normal_indices": norm_indices,
        "trim": t_curves
    }