def __init__(this, vertices, params,cbe = [],valorCBE=10, plot=False): this.bordesCBE = cbe this.valorCBE= valorCBE this.params = params super().__init__(vertices) this.seg = [] for i in range(len(this.vertices)-1): this.seg.append([i,i+1]) this.seg.append([i+1,0]) this.original = dict(vertices=np.array(this.vertices),segments=np.array(this.seg)) this.triangular = tr.triangulate(this.original,this.params) if plot: tr.compare(plt, this.original, this.triangular) count = 0 for i in this.triangular['segments']: if count > 1: if np.sum(np.isin(np.array(this.cbe)[:,0], i[0]))<1: this.cbe.append([i[0],0]) if np.sum(np.isin(np.array(this.cbe)[:,0], i[1]))<1: this.cbe.append([i[1],0]) else: this.cbe.append([i[0],0]) if np.sum(np.isin(np.array(this.cbe)[:,0], i[1]))<1: this.cbe.append([i[1],0]) count+=1 this.diccionarios = this.triangular['triangles'].tolist() this.tipos = np.zeros([len(this.diccionarios)]).astype(str) this.tipos[:] = 'T1V' this.gdls = this.triangular['vertices'].tolist()
def areaRefiner(this,model,norm): X1 = 'X1' X2 = 'Y1' X3 = 'X2' X4 = 'Y2' X5 = 'X2' X6 = 'Y3' X7 = 'X4' X8 = 'Y4' X9 = 'X5' X10 = 'Y5' X11 = 'X6' X12 = 'Y6' X13 = 'CX' X14 = 'CY' X15 = 'XE1' X16 = 'YE1' X17 = 'XE2' X18 = 'YE2' X19 = 'XE3' X20 = 'YE3' X21 = 'CB' dt = pd.DataFrame.from_records(this.generarDatos()) dt.columns = [X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14,X15,X16,X17,X18,X19,X20,X21] xs = norm(dt) ys = model(xs.values) this.triangular['triangle_max_area'] = ys tnueva = tr.triangulate(this.triangular,'ra') tr.compare(plt,this.triangular,tnueva) this.triangular = tnueva this.diccionarios = this.triangular['triangles'].tolist() this.tipos = np.zeros([len(this.diccionarios)]).astype(str) this.tipos[:] = 'T1V' this.gdls = this.triangular['vertices'].tolist() this.cbe = this.generarCB(this.bordesCBE,this.valorCBE)
def main(): A = dict(vertices=np.array(( (0, 0), (1, 0), (1, 1), (0.5, 0.5), (0, 1), )), segments=[ (0, 1), (1, 2), (2, 3), (3, 4), (4, 0), ]) B = tr.triangulate(A, opts="pa0.03") print(B) print(len(B['vertices'])) print(len(B['vertex_markers'])) print(len(B['triangles'])) tr.compare(plt, A, B) plt.savefig('tri.png')
def Imesh(tf,tw,a,b,params,plot=True): corners = [[0,0],[a,0],[a,tf],[a/2+tw/2,tf],[a/2+tw/2,tf+b],[a,tf+b],[a,2*tf+b],[0,2*tf+b],[0,tf+b],[a/2-tw/2,tf+b],[a/2-tw/2,tf],[0,tf]] seg = [] for i in range(len(corners)-1): seg.append([i,i+1]) seg.append([i+1,0]) A = dict(vertices=np.array(corners),segments=np.array(seg)) B = tr.triangulate(A,params) if plot: tr.compare(plt, A, B) return B,corners
def triangulate(self): segments = [(i, i + 1) for i in range(len(self.outline) - 1)] segments.append((len(self.outline) - 1, 0)) A = {"vertices": self.outline, "segments": segments} B = triangle.triangulate(A, 'qp') self.vertices = B["vertices"] self.triangles = B["triangles"] triangle.compare(plt, A, B)
def create_mesh(self): self.set_points() self.set_boundary_nodes() self.set_segments() if 'holes' in self._model: self.set_holes() geometry = {'vertices': self._points, 'vertex_markers': self._boundary_nodes, 'segments': self._segments, 'holes': self._holes} else: geometry = {'vertices': self._points, 'vertex_markers': self._boundary_nodes, 'segments': self._segments} self._t = tr.triangulate(geometry, self._options) self._mesh = self.export_mesh() tr.compare(plt, geometry, self._t) if self.show_plot: plt.show() return self._mesh
def triangulate(vertices, max_triangle_area=None, split_boundary=False, plot_result=False): """ Triangulate the interior of a closed polygonal curve using the triangle library (Python wrapper around Shewchuk's Triangle mesh generator) Parameters ---------- vertices : array, shape (N, 2) Coordinates of the curve's vertices max_triangle_area : None or float Maximum area allowed for triangles, see Shewchuk's Triangle mesh generator, defaut None (no constraint) split_boundary : bool Whether to allow boundary segments to be splitted or not, defaut False plot_result : bool If True, the resulting triangulation is shown along with the input, defaut False Returns ------- raw_mesh : dict Output mesh, see the documentation of the triangle library """ # vertices and segments define a planar straight line graph (vertices are assumed to be given ordered) segments = np.array([[i, (i + 1) % len(vertices)] for i in range(len(vertices))]) triangle_input = dict(vertices=vertices, segments=segments) opts = 'qpe' if max_triangle_area is not None: opts = opts + 'a{}'.format(max_triangle_area) if not split_boundary: opts = opts + 'Y' raw_mesh = triangle.triangulate(triangle_input, opts) if plot_result: triangle.compare(plt, triangle_input, raw_mesh) plt.show() return raw_mesh
def build_hyd_sub_mesh(bshow, nbpointhyd, nbpointsub, seedhyd=None, seedsub=None): ''' Building 2 TIN (Triangular Irregular Network) one hydraulic the other substrate :param bshow: if True show using :param nbpointhyd: a given number of hydraulic nodes/points :param nbpointsub: a given number of substrate nodes/points :param seedhyd: a fixed seed for randomisation of hydraulic nodes :param seedsub: a fixed seed for randomisation of substrate nodes :return: x,y for hydraulic nodes/points, TIN description of hydraulic meshes (3 indexes of nodes per line defining a mesh) , x,y for substrate nodes/points, TIN description of substrate meshes (3 indexes of nodes per line defining a mesh) , sub_data: substrate data for each substrate mesh ''' if seedhyd != None: np.random.seed(seedhyd) hyd_xy = np.random.rand(nbpointhyd, 2) * 100 # pavé [0,100[X[0,100[ # print('seedhyd', np.random.get_state()[1][0]) # TODO supprimer les doublons A = dict(vertices=hyd_xy) # A['vertices'].shape : (4, 2) B = tr.triangulate(A) # type(B) class 'dict'> # eventuellement check si hyd_xy a changé..... if bshow: tr.compare(plt, A, B) plt.show() if seedsub != None: np.random.seed(seedsub) sub_xy = np.random.rand(nbpointsub, 2) * 100 # pavé [0,100[X[0,100[ # print('seedsub', np.random.get_state()[1][0]) # TODO supprimer les doublons C = dict(vertices=sub_xy) D = tr.triangulate(C) # eventuellement check si sub_xy a changé..... if bshow: tr.compare(plt, C, D) plt.show() if seedsub != None: np.random.seed(seedsub) datasub = np.random.randint(2, 9, size=(len(D['triangles']), 1)) datasub = np.hstack((datasub, datasub)) return B['vertices'], B['triangles'], D['vertices'], D['triangles'], datasub
coordsModelo = modelo.geometria.original['vertices'].flatten().tolist() cx = [np.average(e.coords[:, 0])] cy = [np.average(e.coords[:, 1])] coords = e.coords.flatten().tolist() cb = [np.any(np.isin(e.gdl, np.array(modelo.cbe)[:, 0])) * 1] y = [e.areaOptima] fila = coordsModelo + coords + cx + cy + cb + y m.append(fila) return m import os path = os.getcwd() for i in range(300, 400): try: ModeloL, ModeloH = generarPares(geom=1, da1=10, da2=80, bcb=[0, 1, 2])[0] errores, U, UG = L1error(ModeloH, ModeloL) areas = areaCorrection(ModeloL, errores, K=0.002, alpha=1, area0=0.5) areasR = areasRefinado(ModeloL, areas) ModeloL.geometria.triangular['triangle_max_area'] = np.array( areasR).reshape([len(areasR), 1]) tnueva = tr.triangulate(ModeloL.geometria.triangular, 'ra') tr.compare(plt, ModeloL.geometria.triangular, tnueva) plt.savefig('PROBLEMA' + format(i) + '.png') np.savetxt(path + "/PROBLEMA" + format(i) + ".csv", np.array(extraerFila(ModeloL)), delimiter=",") except: print('Fallo')
import matplotlib.pyplot as plt import triangle as tr box = tr.get_data('box') t = tr.triangulate(box, 'pc') tr.compare(plt, box, t) plt.show()
import matplotlib.pyplot as plt import triangle as tr d0 = tr.get_data('dots') d1 = tr.triangulate(d0) tr.compare(plt, d0, d1) plt.show()
for i in range(100): x = random.randint(-20, 20) y = random.randint(-20, 20) list_of_vertices.append([x, y]) print(list_of_vertices) s = [] for i in range(100): for j in range(100): s.append([i, j]) A = dict(vertices=list_of_vertices, segments=s) t = triangle.triangulate(A, 'e') edges = t['edges'].tolist() for i, item in enumerate(edges): item.append(distance(Point(list_of_vertices[item[0]][0], list_of_vertices[item[0]][1]), Point(list_of_vertices[item[1]][0], list_of_vertices[item[1]][1]))) print(edges) triangle.compare(plt, A, t) plt.show() # print(t.values()) # A = dict(vertices=list_of_vertices) # t = triangle.delaunay(list_of_vertices) # print(t.tolist()) # plt.show() f = open('graph1.wug', 'w') # f.write('// WEIGHTED UNDIRECTED GRAPH FILE\n// Structure:\n// (node-1)(space)(node-2)(space)(distance)\n') for i, item in enumerate(edges):
import matplotlib.pyplot as plt import triangle as tr spiral = tr.get_data('spiral') t = tr.triangulate(spiral) tr.compare(plt, spiral, t) plt.show()
def serialize(self, int_colors=False): d = {} d["name"] = self.name d["res_id"] = self.res_id d["enclosure_point"] = self.enclosure_point.serialize() d["enclosure_radius"] = self.enclosure_radius d["min_bounds"] = self.min_bounds.serialize() d["max_bounds"] = self.max_bounds.serialize() d["points"] = serialize_list(self.points) d["normals"] = serialize_list(self.normals) d["edges"] = self.edges d["polys"] = serialize_list(self.polys) if int_colors: d["colors"] = [c.color_long for c in self.colors] else: d["colors"] = serialize_list(self.colors) d["vectors"] = serialize_list(self.vectors) d["unique_edges"] = serialize_list(self.unique_edges) try: import triangle import triangle.plot import matplotlib.pyplot as plt import numpy as np except ImportError: print( "triangle, matplotlib and/or numpy libraries not found, will not output triangulations" ) return d d["triangles_poly"] = list() d["triangles_verts_poly"] = list() # print(self.name) for poly in self.polys: # print(poly) normal_rec = self.normals[poly.normal_index] normal_idx = normal_rec.normal_index normal = np.array(self.vectors[normal_idx].as_list_3()) verts = [] edges = [] # last = first + poly.edge_count for idx in range(0, poly.edge_count): e = self.unique_edges[self.edges[poly.first_edge + idx]] if e.a not in verts: verts.append(e.a) if e.b not in verts: verts.append(e.b) myidx_a = verts.index(e.a) myidx_b = verts.index(e.b) edges.append([myidx_a, myidx_b]) points = [ np.array( [self.points[x].x, self.points[x].y, self.points[x].z]) for x in verts ] # grab two points from this poly to calculate the # plane this face is in p0 = np.array(points[0]) p1 = np.array(points[1]) p = [p0 - p1] u = p / np.linalg.norm(p) v = np.cross(u, normal) def flatten_3to2(vec3): return np.array( [np.dot(vec3 - p0, u[0]), np.dot(vec3 - p0, v[0])]) face_points = np.array([flatten_3to2(x) for x in points]) if (self.name == "Subway" or self.name == "EURO"): # uhh yeah. # this is for a shape # that crashed the triangulator continue num_face_points = len(face_points) # print(F"face_points length: {num_face_points}") if (num_face_points < 3): # can't triangulate less than 3 points continue #if (num_face_points == 3): # print(verts) # 3 points don't need to get passed to triangulator # n = len(d["triangles_verts_poly"]) # d["triangles_poly"].append([[0, 1, 2]]) # d["triangles_verts_poly"].append(verts) # d["triangles_poly"].append([[2, 1, 0]]) # d["triangles_verts_poly"].append(verts) # continue # create input for triangle library the_dict = dict(vertices=face_points, segments=edges) # do triangulation in planar straignt line graph mode result = triangle.triangulate(the_dict, 'p') if "triangles" not in result: # the triangulator didn't work for some reason continue vert_diff = len(result["vertices"]) - len(the_dict["vertices"]) if vert_diff > 0: #print(d["points"]) # print(F"We need to add {vert_diff} vertices to this shape.") # print("This can happen because of self-intersecting polygons.") #verts = [] for vert in result["vertices"]: if vert in the_dict["vertices"]: continue # turn 2d point back into 3d point with previous constants new_vert_3 = p0 + (vert[0] * u) + (vert[1] * v) new_vert_3 = np.append(new_vert_3, [[1]]) new_vert_3 = new_vert_3.tolist() # add to shape points d["points"].append(new_vert_3) # add index to this face verts.append(len(d["points"]) - 1) # we'll use this to count how many shape edges we hit casting a # ray in an arbitrary direction from the center point of each triangle. # this allows us to remove triangles that are part of a "hole" in the # geometry def line_ray_intersection_point(rayOrigin, rayDirection, point1, point2): v1 = rayOrigin - point1 v2 = point2 - point1 v3 = np.array([-rayDirection[1], rayDirection[0]]) t1 = np.cross(v2, v1) / np.dot(v2, v3) t2 = np.dot(v1, v3) / np.dot(v2, v3) if t1 >= 0.0 and t2 >= 0.0 and t2 <= 1.0: return [rayOrigin + t1 * rayDirection] return [] # calculate which triangles to remove triangles_to_remove = [] for tidx, t in enumerate(result["triangles"]): tpoints = np.array([result["vertices"][x] for x in t]) tavg = np.mean(tpoints, axis=0) total_intersects = 0 for edge in edges: # check ray from center of all points # out to +x for each edge intersects = line_ray_intersection_point( tavg, np.array([1, 0]), # positive x ray face_points[edge[0]], face_points[edge[1]]) num_intersects = len(intersects) if num_intersects == 0: # ray doesn't intersect continue if num_intersects > 0: total_intersects += num_intersects # if we intersected an EVEN number of edges, remove that triangle if total_intersects % 2 == 0: # print("removing triangle inside hole: %d" % tidx) triangles_to_remove.append(tidx) # remove hole triangles if len(triangles_to_remove) > 0: result["triangles"] = np.delete(result["triangles"], triangles_to_remove, axis=0) # below used for debug new_tris = result["triangles"].tolist() if vert_diff > 0: print(d["max_bounds"]) print(f"Adding extra verticies to {self.name}") the_dict["triangles"] = new_tris the_dict["vertices"] = np.array( [flatten_3to2(np.array(x[:3])) for x in d["points"]]) if DEBUG_ADDED_VERTS: triangle.compare(plt, the_dict, result) plt.show() # print(self.name) d["triangles_poly"].append(new_tris) d["triangles_verts_poly"].append(verts) return d
import matplotlib.pyplot as plt import triangle as tr def bndry(dict): return {k: dict[k] for k in ('vertices', 'segments')} face = tr.get_data('face.1') A = tr.triangulate(face, 'rc') B = tr.triangulate(face, 'rpc') tr.compare(plt, bndry(A), bndry(B)) plt.show()
import matplotlib.pyplot as plt import numpy as np import triangle as tr N = 32 theta = np.linspace(0, 2 * np.pi, N, endpoint=False) pts = np.stack([np.cos(theta), np.sin(theta)], axis=1) A = dict(vertices=pts) B = tr.triangulate(A, 'q') tr.compare(plt, A, B) plt.show()
import matplotlib.pyplot as plt import triangle as tr pts = tr.get_data('diamond_02_00009')['vertices'] t = dict(vertices=pts) d = tr.get_data('diamond_02_00009.1.v') tr.compare(plt, t, d) plt.show()
# # small_edges.add((edge_idx0, edge_idx1)) # if np.linalg.norm(p1 - p0) < 80: # small_edges.add((edge_idx0, edge_idx1)) # # print('g') # else: # large_edges.add((edge_idx0, edge_idx1)) # plt.figure() # plt.plot(z[:, 0], z[:, 1], '.') # for i, j in small_edges: # plt.plot(z[[i, j], 0], z[[i, j], 1], 'b') # # for i, j in large_edges: # # plt.plot(z[[i, j], 0], z[[i, j], 1], 'black') # plt.show() ptr = [x for x in tri['triangles'] if (x != [0, 0, 0]).all()] tri['triangles'] = ptr triangle.compare(plt, tri, data) plt.show() centers = [] (w, h, z1) = img.shape z = np.array(z) for i in tri['triangles']: centers.append(np.sum(z[i], axis=0, dtype='int') / 3.0) colors = np.array([(x - w / 2.)**2 + (y - h / 2.)**2 for x, y in centers]) plt.tripcolor(z[:, 0], z[:, 1], tri['triangles'].copy(), facecolors=colors, edgecolors='k') plt.gca().set_aspect('equal') plt.show() print('end')
pointsetinterior = hole[:-1] pointsetinteriorrings = pointsetinteriorrings + pointsetinterior segmentlistholeset = segmentlistholeset + segmentindexlisthole x = [p[0] for p in pointsetinterior] y = [p[1] for p in pointsetinterior] centroid = ([[sum(x) / len(pointsetinterior), sum(y) / len(pointsetinterior)]]) centroidlist = centroidlist + centroid segmentset = segmentindexlist+segmentlistholeset vertexset = pointsetexterior+pointsetinteriorrings points = dict(vertices = (vertexset)) input = dict(segments = segmentset, vertices = (vertexset), holes = centroidlist) # print(input) triangulation = triangle.triangulate(input, 'p') triangle.compare(plt, points, triangulation) # plt.show() else: points = dict(vertices = (pointsetexterior)) # print(points) input = dict(segments = segmentindexlist, vertices = (pointsetexterior)) # print(input) triangulation = triangle.triangulate(input, 'p') triangle.compare(plt, points, triangulation) # print(triangulation['vertices']) # print(triangulation['triangles']) # plt.show() t = triangulation # cj_dict = json.load(open( os.path.join("..\_data", "building_output.obj"), "w+" ))
import matplotlib.pyplot as plt import triangle as tr face = tr.get_data('face') t = tr.triangulate(face, 'p') tr.compare(plt, face, t) plt.show()