def __init__(self, v0=[0, 40], v1=[40, 40], v2=[10, 0]): if (self.__checkPoint(v0) or self.__checkPoint(v1) or self.__checkPoint(v2)): print("input point error") return 0 self.v = [v0, v1, v2] self.x_min = min(v0[0], v1[0], v2[0]) self.x_max = max(v0[0], v1[0], v2[0]) self.y_min = min(v0[1], v1[1], v2[1]) self.y_max = max(v0[1], v1[1], v2[1]) self.edge = [ edge.edge(self.v[1], self.v[2]), edge.edge(self.v[0], self.v[2]), edge.edge(self.v[0], self.v[1]) ] if (self.edge[0].len >= max(self.edge[1].len, self.edge[2].len)): self.longEdge = self.edge[0] self.longVtx = [self.v[0], self.v[1], self.v[2]] elif (self.edge[1].len >= self.edge[2].len): self.longEdge = self.edge[1] self.longVtx = [self.v[1], self.v[2], self.v[0]] else: self.longEdge = self.edge[2] self.longVtx = [self.v[2], self.v[0], self.v[1]] return
def triangle_triangle_intersect(self,triangle,includeboundary=True,errtol=1e-12): #This method returns whether an inputted triangle intersects the triangle object or not. #Distinction is made whether to include the boundaries of the triangle objects or not. if len(self.edges)==0: self.edges=[edge(self.points[0],self.points[1]),edge(self.points[0],self.points[2]),edge(self.points[1],self.points[2])] if len(triangle.edges)==0: triangle.edges=[edge(triangle.points[0],triangle.points[1]),edge(triangle.points[0],triangle.points[2]),edge(triangle.points[1],triangle.points[2])] return any([triangle.edge_triangle_intersect(e,includeboundary=includeboundary,errtol=errtol) for e in self.edges]) or any([self.edge_triangle_intersect(e,includeboundary=includeboundary,errtol=errtol) for e in triangle.edges])
def edge_triangle_intersect(self,edgeVar,includeboundary=True,errtol=1e-12): #This method returns whether an edge intersects the triangle object or not. #Distinction is made whether to include the boundaries of the triangle and edge objects or not. if len(self.edges)==0: self.edges=[edge(self.points[0],self.points[1]),edge(self.points[0],self.points[2]),edge(self.points[1],self.points[2])] if includeboundary: if any([self.point_triangle_intersect(p,errtol=errtol) for p in edgeVar.points]): return True else: if any([edgeVar.edge_edge_intersect(e,errtol=errtol) for e in self.edges]): return True return False else: if any([self.point_triangle_intersect(p,includeboundary=False,errtol=errtol) for p in edgeVar.points]): return True else: p1bool1=any([e.point_edge_intersect(edgeVar.points[0],errtol=errtol) for e in self.edges]) p1bool2=any([p.is_point(edgeVar.points[0]) for p in self.points]) if p1bool1 and not p1bool2: state1=1 elif p1bool2: state1=2 else: state1=3 p2bool1=any([e.point_edge_intersect(edgeVar.points[1],errtol=errtol) for e in self.edges]) p2bool2=any([p.is_point(edgeVar.points[1]) for p in self.points]) if p2bool1 and not p2bool2: state2=1 elif p2bool2: state2=2 else: state2=3 state=state1*state2 if state==1 or state==2: if any([e.point_edge_intersect(edgeVar.points[0],errtol=errtol) and e.point_edge_intersect(edgeVar.points[1],errtol=errtol) for e in self.edges]): return False else: return True elif state==3: if any([self.edges[0].point_edge_intersect(p,errtol=errtol) for p in edgeVar.points]): return self.edges[1].edge_edge_intersect(edgeVar,includeboundary=False,errtol=errtol) or self.edges[2].edge_edge_intersect(edgeVar,includeboundary=False,errtol=errtol) elif any([self.edges[1].point_edge_intersect(p,errtol=errtol) for p in edgeVar.points]): return self.edges[0].edge_edge_intersect(edgeVar,includeboundary=False,errtol=errtol) or self.edges[2].edge_edge_intersect(edgeVar,includeboundary=False,errtol=errtol) else: return self.edges[0].edge_edge_intersect(edgeVar,includeboundary=False,errtol=errtol) or self.edges[1].edge_edge_intersect(edgeVar,includeboundary=False,errtol=errtol) elif state==6: return any([edgeVar.edge_edge_intersect(e,includeboundary=False,errtol=errtol) for e in self.edges]) elif state==9: if any([edgeVar.edge_edge_intersect(e,includeboundary=False,errtol=errtol) for e in self.edges]): return True return False
def generateKeywordGraph(self, searchResult, kw): art = ArticleNode() dummyThiccGraph = {'nodes': [], 'edges': []} nodeList = [] edgelist = [] xie = 0 yie = 0 #print("graphGenerator: " + str(searchResult)) for x in searchResult: xie += 1 yie += 1 randColor = "#{:06x}".format(random.randint(0, 0xFFFFFF)) testNode = node(str(x), str(x), 2, random.randint(-100, 100), random.randint(-100, 100), randColor) nodeList.append(testNode) for z in searchResult[x]: if (x == "Undefined"): articleNode = node(str(z), str(z), 1, random.randint(-100, 100), random.randint(-100, 100), randColor) nodeList.append(articleNode) articleEdge = edge(str(z), str(x)) edgelist.append(articleEdge) print("Category: " + str(x) + " article: " + str(z)) else: label = "Title: " + str( z.getTitle()) + " ArticleID: " + str( z.getInfo()) + " SubCategory: " + str( z.getSubCat()) articleNode = node(str(z.getInfo()), label, 1, random.randint(-100, 100), random.randint(-100, 100), randColor) nodeList.append(articleNode) articleEdge = edge(str(z.getInfo()), str(x)) edgelist.append(articleEdge) print("Category: " + str(x) + " article: " + str(z.getInfo())) randColor0 = "#{:06x}".format(random.randint(0, 0xFFFFFF)) nodObj = node(kw, kw, 3, 0, 0, randColor0) nodeList.insert(0, nodObj) for x in searchResult: testEdge = edge(str(x), kw) edgelist.append(testEdge) dummyThiccGraph['nodes'] = [node.__dict__ for node in nodeList] dummyThiccGraph['edges'] = [edge.__dict__ for edge in edgelist] output = dummyThiccGraph print(dummyThiccGraph['nodes']) with open(os.path.join('static', 'testjson.json'), 'w') as outfile: outfile.write(json.dumps(output, indent=4)) return output
def addEdge(self, ed, w = 1.0, d = False): if not ed: return if self.isEdgePresent(ed): return if type(ed) == str: e = ed.split() h = self.getNode(e[0]) t = self.getNode(e[1]) if not h: self.addNode(e[0]) h = self.getNode(e[0]) if not t: self.addNode(e[1]) t = self.getNode(e[1]) ed = edge.edge(e[0], e[1], w, d) h.addEdge(ed) t.addEdge(ed) else: h = self.getNode(ed.head) t = self.getNode(ed.tail) if not h: self.addNode(ed.head) h = self.getNode(ed.head) if not t: self.addNode(ed.tail) t = self.getNode(ed.tail) h.addEdge(ed) t.addEdge(ed) self.edges.append(ed) self.numedges += 1 return
def createEdgeObjects(verticeList): edgeList =[] for u in verticeList: neighborList = u.get_neighbors() for n in neighborList: newEdge = edge(u, n[0], n[1]) edgeList.append(newEdge) return edgeList
def reverseEdge(self, ed): h = ed.tail t = ed.head d = ed.directed w = ed.weight self.removeEdge(ed) self.addEdge(edge.edge(h, t, w, d)) return
def generate(branch): pushMatrix() x = branch.x y = branch.y sz = branch.sz cnt = branch.cnt a = branch.a translate(x, y) line(0, 0, 0, -sz) if cnt < total: translate(0, -sz) rotate(a) e1 = Edge.edge(0, 0, sz * (0.67), cnt + 1, a, total) generate(e1) rotate(2 * -a) e2 = Edge.edge(0, 0, sz + (0.67), cnt + 1, a, total) generate(e1) popMatrix()
def add_edge(self, u, v, w=0): if u == v: raise ValueError("u == v") self.e += 1 #define two edges u->v and v->u e = edge(u,v,w) re = edge(v,u,0) #adding reverse edge e.re = re re.re = e #add edges self.adj_list[u].append(e) self.adj_list[v].append(re) #setting default flows self.flow[e]=0 self.flow[re]=0
def create_edge (self, label=""): ''' Convenience routine for creating an edge between the last two added nodes. ''' if not len(self.history) == 2: return e = edge(self.history[0].id, self.history[1].id, label) self.add_edge(e) return e
def create_edge(self, label=""): ''' Convenience routine for creating an edge between the last two added nodes. ''' if not len(self.history) == 2: return e = edge(self.history[0].id, self.history[1].id, label) self.add_edge(e) return e
def createGraph(self, edgelist, numnodes = -1): if not numnodes == -1: for i in range(1, numnodes + 1): self.addNode(str(i)) for i in edgelist: if not i: break ed = i.split() #if self.isEdgePresent(ed[0] + " " + ed[1]): # continue #if not self.getNode(ed[0]): # self.addNode(node.node(ed[0])) #if not self.getNode(ed[1]): # self.addNode(node.node(ed[1])) if self.weighted: e = edge.edge(ed[0], ed[1], float(ed[2]), self.directed) else: e = edge.edge(ed[0], ed[1], directed = self.directed) self.addEdge(e) return
def getEdgeList(self, prov_json_file): edgeJsonList = [] edgeLabel = [] loopCounter = 0 edgeList = [] json_data = open(prov_json_file).read() provJsonData = json.loads(json_data) #finds edge labes with names wasAssociatedWith, #wasGeneratedBy, and used... edge_label = ['wasAssociatedWith', 'wasGeneratedBy', 'used'] # edgeJsonList.append(provJsonData['wasAssociatedWith']) # edgeJsonList.append(provJsonData['wasGeneratedBy']) # edgeJsonList.append(provJsonData['used']) for label in edge_label: if label in provJsonData: edgeJsonList.append(provJsonData[label]) #list of edge label values edgeLabel.append('wasAssociatedWith') edgeLabel.append('wasGeneratedBy') edgeLabel.append('used') #print(edgeLabel) #creates an edge object with the source and destionation nodes #from the prov json graph and stores the edge object in a list. for i in range(len(edgeJsonList)): for data, value in edgeJsonList[i].items(): key_list = list(value.keys()) destination_node = value[key_list[0]] source_node = value[key_list[1]] #creates edge objects edgeVal = edge(source_node, destination_node, edgeLabel[i]) #print(edgeVal.toString()) #adds edge to a list #print(loopCounter) edgeList.append(edgeVal) #loopCounter += 1 return edgeList
def set_weight_undirect_graph(graph): e1 = edge(0,1,0.1) e2 = edge(0,2,0.5) e3 = edge(0,3,0.2) e4 = edge(1,2,0.1) e5 = edge(1,3,1.1) e6 = edge(2,3,0.1) e7 = edge(2,4,1.5) e8 = edge(3,4,0.3) graph.add_edge(e1) graph.add_edge(e2) graph.add_edge(e3) graph.add_edge(e4) graph.add_edge(e5) graph.add_edge(e6) graph.add_edge(e7) graph.add_edge(e8)
def draw_line(): global node_set, eid A = simpledialog.askinteger("Input Node A", "Input Node A ID") B = simpledialog.askinteger("Input Node B", "Input Node B ID") weight = simpledialog.askinteger("Weight", "Input Weight") nodeA = search_node(A, node_set) nodeB = search_node(B, node_set) if (nodeA and nodeB): new_edge = edge(eid, nodeA, nodeB, weight) eid += 1 new_edge.draw(canvas) if(cycle_detect(nodeA, nodeB)): messagebox.showinfo("Cycle", "Oops, a Cycle") nodeA.connect(nodeB) append_tree(nodeA.getTree()) nodeA.getTree().add_edge(new_edge)
def edge_list_create(self, vectorlist): # This is a helper function to run the Kruskal algorithm. It creates edge objects from the adjacency # matrix of the graph. These edge objects hold the weight of each edge, along with pointer to their start # and ending vector objects. # # Since the graph is undirected, the actual order of these vectors is not important. However, # if one wanted to apply another algorithmic approach to finding a minimum spanning tree within a graph # this could be useful. # Initialize an empty list edgelist = [] # Create a copy of the adjacency matrix dimensions with a False boolean in all positions. # This matrix will be used to ensure that duplicate edges are not added to our edgelist. This is # useful for the Kruskal algorithm as we can override the standard compare function (cmp) to # sort the edgelist, and since it will have no duplicates, we can sort it without having to do # any additional steps edge_check = [[False for x in range(self.max_vert)] for y in range(self.max_vert)] # Initialize integer for looping i = 0 # For each vertex in the simple graph do the following: while i < self.max_vert: # Get a list of adjacent vertices for x in self.get_adjacent(i): # Check to see if the edge has already been added if edge_check[i][x] == False: # If it has not, create a new edge and add it to the edge list new_edge = edge(self.ad_matrix[i][x], vectorlist[i], vectorlist[x]) edgelist.append(new_edge) # Mark both edges in the matrix as true, so a duplicate will not be added edge_check[i][x] == True edge_check[x][i] == True # Increase constant i to move onto the next position in the main adjacency matrix i += 1 # Return the created edgelist that has no duplicate edge objects return edgelist
def __createEdgesDictionary(self, v1, v2, create=True): newEdge = False v1Id = v1.getId() v2Id = v2.getId() if v2Id not in self.__edges[v1Id]: self.__edges[v1Id] = {} self.__edges[v1Id][v2Id] = {} newEdge = True if v1Id not in self.__edges[v2Id]: newEdge = True if create == False: self.__edges[v1Id][v2Id] = {} if newEdge and create: a = edge.edge(v1, v2) self.__edges[v1Id][v2Id] = a self.__edges[v2Id][v1Id] = a v1.addEdge(a) v2.addEdge(a) self.__edgeslist.append(a) return self.__edges[v1Id][v2Id]
def drawSpin(self, color='b', linewidth=1.0, lineratio=1.0): currT = self.origT width = linewidth for i in range(self.iter): ratioX = abs(currT.v[1][0] - currT.v[2][0])*self.ratio ratioY = abs(currT.v[1][1] - currT.v[2][1])*self.ratio if(currT.v[1][0] > currT.v[2][0]): newX = currT.v[1][0] - ratioX else: newX = currT.v[1][0] + ratioX if(currT.v[1][1] > currT.v[2][1]): newY = currT.v[1][1] - ratioY else: newY = currT.v[1][1] + ratioY newPoint = [newX, newY] newEdge = edge.edge(currT.v[0], newPoint) newEdge.draw(color, width) width = width*lineratio newT = triangle.triangle(newPoint, currT.v[2], currT.v[0]) currT = newT return
def getEdgeList(self, prov_json_file): """Converts a provenance graph file into an edge list. Creates a list of labeled, directed edges. """ edgeList = [] json_data = None with open(prov_json_file) as json_file: json_data = json_file.read() provJsonData = json.loads(json_data) # For edge labels given (wAW, wGB, u), create an edge object with # the source and destination nodes from the prov json graph and # store the edges in a list. edge_label = ['wasAssociatedWith', 'wasGeneratedBy', 'used'] for label in edge_label: for data, value in provJsonData[label].items(): keys = value.keys() destination_node = value[keys[0]] source_node = value[keys[1]] edgeVal = edge(source_node, destination_node, label) edgeList.append(edgeVal) return edgeList
def _insert_Vertex_Delaunay_(point, P, E, T): #This method inserts a vertex into already Delaunay triangulation so that the triangulation remains Delaunay. #The method first checks if the point has not been added before. matchbool = False for p in P: if p.is_point(point): matchbool = True break if not matchbool: polyedges = [] staredges = [] constraintpolypoints = [] #The method sees if the new point would fall into the circumcircle of any of the already-existing triangles. #The method then deletes those triangles. for i in range(len(T) - 1, -1, -1): if T[i].inCircumcircle(point, includeboundary=True): #Distinction is made whether the new point falls inside a triangle (in which case constraint edges are mostly ignored)... if T[i].point_triangle_intersect(point): for j in range(len(T[i].edges)): if T[i].edges[j].point_edge_intersect( point, includeboundary=False): if T[i].edges[j].constraint: constraintpolypoints += T[i].edges[j].points break for e in T[i].edges: if e not in polyedges: polyedges.append(e) for p in T[i].points: starE = edge(point, p) if all([not starE.is_edge(elem) for elem in staredges]): staredges.append(starE) for p in T[i].points: p.triangles.remove(T[i]) for e in T[i].edges: e.triangles.remove(T[i]) del T[i] else: #...or falls outside of a triangle, in which case the triangle is only deleted if the new edges that will be made by the insertion of the new point #do not intersect any constrained edges. intersectbool = False for j, e in enumerate(T[i].edges): for p in T[i].points: if not p.is_point(e.points[0]) and not p.is_point( e.points[1]): starE = edge(point, p) if starE.edge_edge_intersect( e, includeboundary=False): if all([ not starE.edge_edge_intersect( elem, includeboundary=False) for elem in E if elem.constraint ]): for k in range(j): if T[i].edges[k] not in polyedges: polyedges.append(T[i].edges[k]) for k in range(j + 1, 3): if T[i].edges[k] not in polyedges: polyedges.append(T[i].edges[k]) for elemP in T[i].points: starE = edge(point, elemP) if all([ not starE.is_edge(elem) for elem in staredges ]): staredges.append(starE) intersectbool = True for elemP in T[i].points: elemP.triangles.remove(T[i]) for elemE in T[i].edges: elemE.triangles.remove(T[i]) del T[i] break if intersectbool: break #When all the necessary triangles have been removed and after some structural clean up... for i in range(len(polyedges) - 1, -1, -1): if any([ polyedges[i].edge_edge_intersect(starE, includeboundary=False) for starE in staredges ]): polyedges[i].points[0].edges.remove(polyedges[i]) polyedges[i].points[1].edges.remove(polyedges[i]) E.remove(polyedges[i]) del polyedges[i] #... a new set of edges is made that connects the new point #to the rest of the triangulation and a new set of triangles is added #to the triangulation over the framework of the new connective edges. for e in polyedges: e1 = edge(e.points[0], point) e2 = edge(e.points[1], point) t = triangle(e.points[0], e.points[1], point) t.edges = [e] matchbool = False for elem in E: if e1.is_edge(elem): matchbool = True t.edges.append(elem) break if not matchbool: if e.points[0] in constraintpolypoints: e1.constraint = True E.append(e1) t.edges.append(e1) e1.update() e1.enclosed = True matchbool = False for elem in E: if e2.is_edge(elem): matchbool = True t.edges.append(elem) break if not matchbool: if e.points[1] in constraintpolypoints: e2.constraint = True E.append(e2) t.edges.append(e2) e2.update() e2.enclosed = True t.update() T.append(t) P.append(point)
del self.edgelist[:] del self.neighbours[:] del self.inedgelist[:] del self.outedgelist[:] self.degree = self.indegree = self.outdegree = 0 self.colour = "white" self.visited = "False" return if __name__ == "__main__": print node.__doc__ n1 = node('1') n2 = node('2') print "node names", n1.name, n2.name e = edge.edge('1', '2') n1.addEdge(e) e = edge.edge('2', '1') n2.addEdge(e) n1.addEdge(edge.edge('5', '1')) print "degrees", n1.degree, n2.degree e = edge.edge('4', '1', directed = True) n1.addEdge(e) e = edge.edge('1', '7', directed = True) n1.addEdge(e) print 'neighbourhood:', n1.getNeighbourhood() for e in n1.getEdgeList(): print e n1.removeEdge(edge.edge('1', '7', directed = True)) print 'neighbourhood:', n1.getNeighbourhood() for e in n1.getEdgeList():
## for i in ops.nodes: ## print i.name, i.degree ## print ops.isNodePresent('1') ## print ops.isNodePresent(node.node('7')) ## print ops.isNodePresent(node.node('3')) print '****' #ops.removeNode(node.node('5')) ops.createGraph(['7 8', '9 10']) #e1 = edge.edge('1', '2') #ops.addEdge(e1) ops.addEdge('4 6') #ops.addEdge(edge.edge('4', '6')) print "numedges", ops.numedges print "numnodes", ops.numnodes for i in ops.nodes: print i.name, i.degree for e in ops.edges: print e.head, e.tail print '****' print "ed: ", ops.isEdgePresent(edge.edge('1', '2')) ops.removeEdge(edge.edge('1', '2')) print "numedges", ops.numedges ops.removeNode(node.node('5')) for i in ops.edges: print i.head, i.tail, i.directed, i.weight for i in ops.nodes: print i.name, i.degree ops.resetGraph() for nd in ops.getNodes(): print 'nd', nd.name
def create_edge( self): return edge()
dc_length=968) dcc_15_layout = dcc_15.Layout() dcc_20 = my_dc(gap_inc_vec=[420.0, 430.0, 440.0, 450.0, 460.0], length_inc_vec=[110, 120, 130], name="ring6", width=20.0, dc_length=988) dcc_20_layout = dcc_20.Layout() marker = dicingMarker() marker_layout = marker.Layout() marker2 = label() marker2_layout = marker2.Layout() marker3 = edge() marker3_layout = marker3.Layout() pr = PlaceComponents( child_cells={ "comp1": dc_10, "comp2": dc_15, "comp3": dc_20, "comp4": dcc_10, "comp5": dcc_15, "comp6": dcc_20, "marker1": marker, "marker2": marker2, "marker3": marker3, }) pr_layout = pr.Layout(
import thirdparty.morphsnakes.morphsnakes as mh from matplotlib import pyplot as ppl def circle_levelset(shape, center, sqradius, scalerow=1.0): """Build a binary function with a circle as the 0.5-levelset.""" grid = np.mgrid[list(map(slice, shape))].T - center phi = sqradius - np.sqrt(np.sum((grid.T)**2, 0)) u = np.float_(phi > 0) return u img = cv2.imread('../data/interim/spim2/c397.jpg', 0) filtered = cv2.bilateralFilter(img, 9, 350, 350) edgeShape = edge.edge(filtered) k, dst = cv2.threshold(edgeShape, 4, 255, cv2.THRESH_BINARY) dilate = cv2.erode(dst, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)), iterations=1) closing = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)), iterations=1) final = cv2.dilate(closing, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=1) _, contours, _ = cv2.findContours(final, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
def set_negative_weight_direct_graph(graph): e1 = edge(0,1,0.1) e2 = edge(0,2,0.5) e3 = edge(0,3,-0.2) e4 = edge(1,2,0.1) e5 = edge(1,3,1.1) e6 = edge(2,3,0.1) e7 = edge(2,4,-1.5) e8 = edge(3,4,0.3) e9 = edge(4,3,0.2) e10 = edge(3,1,10.0) e11 = edge(2,1,1.1) graph.add_edge(e1) graph.add_edge(e2) graph.add_edge(e3) graph.add_edge(e4) graph.add_edge(e5) graph.add_edge(e6) graph.add_edge(e7) graph.add_edge(e8) graph.add_edge(e9) graph.add_edge(e10) graph.add_edge(e11)
def scan_triangulate(P, errtol=1e-12): #This method executes the scan triangulation algorithm that triangulates points by simply connecting them haphazardly. N = len(P) P.sort(key=lambda p: p.x) E = [] T = [] if N < 2: return E, T elif N == 2: e = edge(P[0], P[1]) e.index = 0 e.update() E.append(e) return E, T else: #Checks if set of points is colinear e0 = edge(P[0], P[1]) colinearbool = True for i in range(2, N): if abs(e0.cross(edge(P[0], P[i]))) > abs(errtol): colinearbool = False break if colinearbool: print("Error: point set is colinear, unable to make convex hull") E = [edge(P[i], P[i + 1]) for i in range(N - 1)] for i in range(N - 1): E[i].index = i return P, E, T #Makes the first triangle. startindex = -1 for i in range(2, N): t0 = triangle(P[0], P[1], P[i]) t0.index = 0 if t0.area() > abs(errtol): T.append(t0) e1 = edge(P[0], P[1]) e1.index = 0 e1.update() e2 = edge(P[0], P[i]) e2.index = 1 e2.update() e3 = edge(P[1], P[i]) e3.index = 2 e3.update() t0.edges = [e1, e2, e3] t0.update() E = [e1, e2, e3] startindex = i P[0].index = 0 P[1].index = 1 P[i].index = 2 break if startindex == -1: print("All points are colinear") else: point_index = 3 edge_index = 3 tri_index = 1 #Adds more triangles to the triangulation whenever possible. for i in range(2, N): if i != startindex: #Every point is added incrementally to the triangulation. P[i].index = point_index point_index += 1 newE = [] newEbool = [] for e in E: if not e.enclosed: #An edge is made to the added point and tested to be unique and not crossing any other edge. e1 = edge(e.points[0], P[i]) match1bool = False for j in range(len(newE)): if e1.is_edge(newE[j]): e1 = newE[j] e1bool = newEbool[j] match1bool = True break if not match1bool: e1bool = any([ elem.edge_edge_intersect(e1, includeboundary=False) for elem in E ]) #An edge is made to the added point and tested to be uniue and not crossing any other edge. e2 = edge(e.points[1], P[i]) match2bool = False for j in range(len(newE)): if e2.is_edge(newE[j]): e2 = newE[j] e2bool = newEbool[j] match2bool = True break if not match2bool: e2bool = any([ elem.edge_edge_intersect(e2, includeboundary=False) for elem in E ]) #If both edges are viable, a new triangle is made. if not e1bool and not e2bool: t = triangle(e.points[0], e.points[1], P[i]) t.edges = [e, e1, e2] if all([ not t.triangle_triangle_intersect( tri, includeboundary=False) for tri in T ]): t.index = tri_index tri_index += 1 e.enclosed = True if not match1bool: e1.update() newE.append(e1) newEbool.append(e1bool) e1.index = edge_index edge_index += 1 else: e1.enclosed = True if not match2bool: e2.update() newE.append(e2) newEbool.append(e2bool) e2.index = edge_index edge_index += 1 else: e2.enclosed = True t.update() T.append(t) E = E + newE return P, E, T
def addEdge(graph, from_node:int, to_node:int, cost:int): graph[from_node].append(edge( from_node, to_node, cost))
@author: aldo """ #%% import agent import edge from simulGivenRoutes import execute from getRoutes import getRoutes from itertools import product from copy import deepcopy from ARoptimization import ARoptim from ExpOptim import updatePosterior from ExpOptim import generateDraws #network creation network=[ [None] * 4 for i in range(4)] network[0][1]=edge.edge('x') network[1][2]=edge.edge('x') network[1][3]=edge.edge('x') network[3][2]=edge.edge('x') #agent creation agents=list() agents.append(agent.agent(0,2,1)) agents.append(agent.agent(1,2,2)) agents.append(agent.agent(1,2,3)) agents.append(agent.agent(1,2,1)) #%% #Experience #sensitivity to New information delta=0.1 #getting routes and costs routesAndCosts=getRoutes(network, agents, 10, cost=True)
def convex_hull(P, errtol=1e-12): #This method executes the quickhull algorithm that computes the convex hull of a number of points. N = len(P) if N <= 1: print( "Error: Unable to make a convex hull due to lack of sufficient points" ) return [] elif N == 2: return [edge(P[0], P[1])] else: #Checks if set of points is colinear e0 = edge(P[0], P[1]) colinearbool = True for i in range(2, N): if abs(e0.cross(edge(P[0], P[i]))) > abs(errtol): colinearbool = False break if colinearbool: print("Error: point set is colinear, unable to make convex hull") return [] #Finds the left_most and down_most point of the set. left_anchor = P[0] for i in range(1, N): if P[i].x < left_anchor.x: left_anchor = P[i] elif P[i].x == left_anchor.x and P[i].y < left_anchor.y: left_anchor = P[i] #Finds the right_most and up_most point of the set. right_anchor = P[0] for i in range(1, N): if P[i].x > right_anchor.x: right_anchor = P[i] elif P[i].x == right_anchor.x and P[i].y > right_anchor.y: right_anchor = P[i] #Finds the farthest points above the line between left_anchor and right_anchor. farthest_anchor = left_anchor height = 0 for p in P: res = -(right_anchor.y - left_anchor.y) * p.x + ( right_anchor.x - left_anchor.x ) * p.y - right_anchor.x * left_anchor.y + right_anchor.y * left_anchor.x if (right_anchor.x - left_anchor.x) * res > abs( errtol) and res > height + abs(errtol): farthest_anchor = p height = res #Sorting points that into an upper half, but only focussing on those that dont yet fall into the contructed convex hull. e0 = edge(left_anchor, right_anchor) upper_hull = [ edge(left_anchor, farthest_anchor), edge(farthest_anchor, right_anchor) ] exterior = [] tri = triangle(left_anchor, farthest_anchor, right_anchor) tri.edges = [e0] + upper_hull for p in P: if not p.is_point(left_anchor) and not p.is_point( farthest_anchor) and not p.is_point(right_anchor): res = -(right_anchor.y - left_anchor.y) * p.x + ( right_anchor.x - left_anchor.x ) * p.y - right_anchor.x * left_anchor.y + right_anchor.y * left_anchor.x if (right_anchor.x - left_anchor.x) * res > abs( errtol) and not tri.point_triangle_intersect( p, includeboundary=False): exterior.append(p) #Fully constructing the upper convex hull iteratively. counter = 0 while len(exterior) > 0 and counter < N: for i in range(len(upper_hull)): res1 = upper_hull[i].points[1].x - upper_hull[i].points[0].x if res1 != 0: #Again finds the farthest points below line between two connected points in the convex hull. farthest_anchor = upper_hull[i].points[0] height = 0 for p in exterior: res2 = -(upper_hull[i].points[1].y - upper_hull[i].points[0].y) * p.x + ( upper_hull[i].points[1].x - upper_hull[i].points[0].x ) * p.y - upper_hull[i].points[1].x * upper_hull[ i].points[0].y + upper_hull[i].points[ 1].y * upper_hull[i].points[0].x if res1 * res2 > abs( errtol) and res2 > height + abs(errtol): farthest_anchor = p height = res2 #If there exists a point outside the convex hull, change the hull to include it. if height > abs(errtol) or not farthest_anchor.is_point( upper_hull[i].points[0]): e1 = edge(upper_hull[i].points[0], farthest_anchor) e2 = edge(farthest_anchor, upper_hull[i].points[1]) upper_hull += [e1, e2] if height > abs(errtol): tri = triangle(upper_hull[i].points[0], upper_hull[i].points[1], farthest_anchor) for j in range(len(exterior) - 1, -1, -1): if tri.point_triangle_intersect( exterior[j], includeboundary=False): del exterior[j] exterior.remove(farthest_anchor) del upper_hull[i] break counter += 1 #Finds the farthest points below the line between left_anchor and right_anchor. farthest_anchor = right_anchor height = 0 for p in P: res = -(right_anchor.y - left_anchor.y) * p.x + ( right_anchor.x - left_anchor.x ) * p.y - right_anchor.x * left_anchor.y + right_anchor.y * left_anchor.x if (right_anchor.x - left_anchor.x ) * res < -abs(errtol) and res + abs(errtol) < height: farthest_anchor = p height = res #Sorting points that into a lower half, but only focussing on those that dont yet fall into the contructed convex hull. lower_hull = [ edge(left_anchor, farthest_anchor), edge(farthest_anchor, right_anchor) ] exterior = [] tri = triangle(left_anchor, farthest_anchor, right_anchor) tri.edges = [e0] + lower_hull for p in P: if not p.is_point(left_anchor) and not p.is_point( farthest_anchor) and not p.is_point(right_anchor): res = -(right_anchor.y - left_anchor.y) * p.x + ( right_anchor.x - left_anchor.x ) * p.y - right_anchor.x * left_anchor.y + right_anchor.y * left_anchor.x if (right_anchor.x - left_anchor.x ) * res < -abs(errtol) and not tri.point_triangle_intersect( p, includeboundary=False): exterior.append(p) #Fully constructing the lower convex hull iteratively. counter = 0 while len(exterior) > 0 and counter < N: for i in range(len(lower_hull)): res1 = lower_hull[i].points[1].x - lower_hull[i].points[0].x if res1 != 0: #Again finds the farthest points below line between two connected points in the convex hull farthest_anchor = lower_hull[i].points[0] height = 0 for p in exterior: res2 = -(lower_hull[i].points[1].y - lower_hull[i].points[0].y) * p.x + ( lower_hull[i].points[1].x - lower_hull[i].points[0].x ) * p.y - lower_hull[i].points[1].x * lower_hull[ i].points[0].y + lower_hull[i].points[ 1].y * lower_hull[i].points[0].x if res1 * res2 < -abs(errtol) and res2 + abs( errtol) < height: farthest_anchor = p height = res2 #If there exists a point outside the convex hull, change the hull to include it. if height < -abs(errtol) or not farthest_anchor.is_point( lower_hull[i].points[0]): e1 = edge(lower_hull[i].points[0], farthest_anchor) e2 = edge(farthest_anchor, lower_hull[i].points[1]) lower_hull += [e1, e2] if height < -abs(errtol): tri = triangle(lower_hull[i].points[0], lower_hull[i].points[1], farthest_anchor) for j in range(len(exterior) - 1, -1, -1): if tri.point_triangle_intersect( exterior[j], includeboundary=False): del exterior[j] exterior.remove(farthest_anchor) del lower_hull[i] break counter += 1 return upper_hull + lower_hull
def delaunize(P, E, T, errtol=1e-12): #This method takes a triangulation and executes the Lawson Flip algorithm on it to make the triangulation Delaunay. delaunaybool = False counter = 0 N = len(E) while not delaunaybool and counter < N * (N - 1) / 2 + 1: #While the triangulation it not yet Delaunay... delaunaybool = True for e in E: #...the algorithm finds an edge that is part of two triangles, and sees if the two enclosing triangles need to be flipped. if e.enclosed: p1 = e.triangles[0].points[0] if p1 in e.points: p1 = e.triangles[0].points[1] if p1 in e.points: p1 = e.triangles[0].points[2] p2 = e.triangles[1].points[0] if p2 in e.points: p2 = e.triangles[1].points[1] if p2 in e.points: p2 = e.triangles[1].points[2] #If the two triangles need to be Lawson flipped, the method reworks the triangulation so that the infastructure is maintained #and the two triangles are now flipped (and therefore are Delaunay). if e.triangles[0].inCircumcircle(p2): if all([ abs( edge(p1, e.points[i]).cross( edge(p2, e.points[i]))) > abs(errtol) for i in range(2) ]): t1 = e.triangles[0] t2 = e.triangles[1] for elem in t1.edges: elem.triangles.remove(t1) for elem in t1.points: elem.triangles.remove(t1) for elem in t2.edges: elem.triangles.remove(t2) for elem in t2.points: elem.triangles.remove(t2) for elem in e.points: elem.edges.remove(e) temppoints = [elem for elem in e.points] e.points = [p1, p2] tempt1edges = [ elem for elem in t1.edges if not e.is_edge(elem) ] tempt2edges = [ elem for elem in t2.edges if not e.is_edge(elem) ] if tempt1edges[0].edge_edge_intersect( tempt2edges[0], includeboundary=True): t1.edges = [tempt1edges[0], tempt2edges[0], e] t2.edges = [tempt1edges[1], tempt2edges[1], e] else: t1.edges = [tempt1edges[0], tempt2edges[1], e] t2.edges = [tempt1edges[1], tempt2edges[0], e] if temppoints[0] in tempt1edges[0].points: t1.points = [p1, p2, temppoints[0]] t2.points = [p1, p2, temppoints[1]] else: t1.points = [p1, p2, temppoints[1]] t2.points = [p1, p2, temppoints[0]] t1.update() t2.update() e.update() t1.triagarea = None t2.triagarea = None e.edgelength = None delaunaybool = False counter += 1
import cv2 import edge import numpy as np import scipy.ndimage as nd from thirdparty.chanvese.chanvese import chanvese img = nd.imread('../data/interim/spim2/c97.jpg', flatten=True) edgeShape = edge.edge( cv2.bilateralFilter(cv2.imread('../data/interim/spim2/c97.jpg', 0), 9, 350, 350)) k, dst = cv2.threshold(edgeShape, 4, 255, cv2.THRESH_BINARY) dilate = cv2.erode(dst, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2)), iterations=1) closing = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)), iterations=1) final = cv2.dilate(closing, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)), iterations=1) # cv2.imshow("final",final) # cv2.waitKey(0) _, contours, _ = cv2.findContours(final, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) mask = np.zeros(img.shape, np.uint8) cv2.drawContours(mask, contours, -1, (255), -1) cv2.imshow("final", mask) mask[mask > 0] = 1 cv2.waitKey(0)
def _patch_(P, E, T, constr, anchor, cavityPoints, involvedE): #This method patches an pseudo-Delaunay triangulation over a hole left by removing all the triangles that intersect a constrained edge. while not anchor.points[1].is_point(constr.points[0]): paths = [] for e in anchor.points[1].edges: if not e.enclosed and not e.is_edge(anchor): if e.points[1].is_point(anchor.points[1]): e.swap() paths.append(e) if len(paths) == 0: anchor.swap() cavityPoints.append(anchor.points[1]) elif len(paths) == 1: anchor = paths[0] cavityPoints.append(anchor.points[1]) else: cwIndex = 0 thetaprime = math.atan2(anchor.points[0].y - anchor.points[1].y, anchor.points[0].x - anchor.points[1].x) if thetaprime < 0: thetaprime += 2 * math.pi minAngle = math.atan2( paths[0].points[1].y - paths[0].points[0].y, paths[0].points[1].x - paths[0].points[0].x) - thetaprime while minAngle <= 0: minAngle += 2 * math.pi for i in range(1, len(paths)): res = math.atan2( paths[i].points[1].y - paths[i].points[0].y, paths[i].points[1].x - paths[i].points[0].x) - thetaprime while res <= 0: res += 2 * math.pi if res < minAngle: minAngle = res cwIndex = i anchor = paths[cwIndex] cavityPoints.append(anchor.points[1]) segments = [cavityPoints] segmentE = [constr] while len(segments) > 0: for i in range(len(segments) - 1, -1, -1): if len(segments[i]) == 3: e1 = segments[i][1].edges[0] e2 = segments[i][1].edges[1] ref1 = edge(segments[i][0], segments[i][1]) ref2 = edge(segments[i][-1], segments[i][1]) for j in range(len(segments[i][1].edges)): if segments[i][1].edges[j].is_edge(ref1): e1 = segments[i][1].edges[j] elif segments[i][1].edges[j].is_edge(ref2): e2 = segments[i][1].edges[j] involvedE += [e1, e2] tri = triangle(segments[i][0], segments[i][1], segments[i][-1]) tri.edges = [e1, e2, segmentE[i]] tri.update() T.append(tri) del segments[i] del segmentE[i] else: for j in range(1, len(segments[i]) - 1): tri = triangle(segments[i][0], segments[i][j], segments[i][-1]) validbool = True for k in range(1, len(segments[i]) - 1): if k != j and tri.inCircumcircle( segments[i][k], includeboundary=False): validbool = False break if validbool: if j == 1: e1 = segments[i][1].edges[0] ref1 = edge(segments[i][0], segments[i][1]) for k in range(1, len(segments[i][1].edges)): if segments[i][1].edges[k].is_edge(ref1): e1 = segments[i][1].edges[k] break e2 = edge(segments[i][1], segments[i][-1]) e2.update() E.append(e2) involvedE += [e1, e2] tri.edges = [e1, e2, segmentE[i]] tri.update() T.append(tri) segments[i] = segments[i][1:] segmentE[i] = e2 elif j == len(segments[i]) - 2: e1 = edge(segments[i][0], segments[i][-2]) e1.update() e2 = segments[i][-2].edges[0] ref2 = edge(segments[i][-2], segments[i][-1]) for k in range(1, len(segments[i][-2].edges)): if segments[i][-2].edges[k].is_edge(ref2): e2 = segments[i][-2].edges[k] break E.append(e1) involvedE += [e1, e2] tri.edges = [e1, e2, segmentE[i]] tri.update() T.append(tri) segments[i] = segments[i][0:-1] segmentE[i] = e1 else: e1 = edge(segments[i][0], segments[i][j]) e1.update() e2 = edge(segments[i][j], segments[i][-1]) e2.update() E += [e1, e2] involvedE += [e1, e2] tri.edges = [segmentE[i], e1, e2] tri.update() T.append(tri) segments.append(segments[i][j:]) segmentE.append(e2) segments[i] = segments[i][0:j + 1] segmentE[i] = e1 break
def delaunay_triangulate(P, constraints=[]): #This method uses the Bowyer-Watson Algorithm to iteratively insert points into an already Delaunay triangulation. maxX = P[0].x minX = P[0].x maxY = P[0].y minY = P[0].y for i in range(1, len(P)): if P[i].x > maxX: maxX = P[i].x elif P[i].x < minX: minX = P[i].x if P[i].y > maxY: maxY = P[i].y elif P[i].y < minY: minY = P[i].y cx = (maxX + minX) / 2 cy = (maxY + minY) / 2 r = math.sqrt((maxX - minX)**2 + (maxY - minY)**2) / 2 + 1 p01 = point(cx, cy + 2 * r) p02 = point(cx + math.sqrt(3) * r, cy - r) p03 = point(cx - math.sqrt(3) * r, cy - r) P.insert(0, p03) P.insert(0, p02) P.insert(0, p01) e01 = edge(p01, p02) e01.update() e02 = edge(p01, p03) e02.update() e03 = edge(p02, p03) e03.update() E = [e01, e02, e03] t0 = triangle(p01, p02, p03) t0.edges = [e01, e02, e03] t0.update() T = [t0] for p in P[3:]: _insert_Vertex_Delaunay_(p, P, E, T) for i in range(len(T) - 1, -1, -1): if (p01 in T[i].points) or (p02 in T[i].points) or (p03 in T[i].points): for elem in T[i].points: elem.triangles.remove(T[i]) for elem in T[i].edges: elem.triangles.remove(T[i]) elem.enclosed = False del T[i] for i in range(len(E) - 1, -1, -1): if (p01 in E[i].points) or (p02 in E[i].points) or (p03 in E[i].points): for elem in E[i].points: elem.edges.remove(E[i]) del E[i] del P[0] del P[0] del P[0] if constraints is not None: #constraintIndex=[] if isinstance(constraints, list) or isinstance( constraints, tuple) or isinstance(constraints, np.ndarray): if all([isinstance(constr, edge) for constr in constraints]): for i in range(len(constraints) - 1, -1, -1): matchbool = False for j in range(len(E)): if constraints[i].is_edge(E[j]): matchbool = True E[j].constraint = True #constraintIndex.append(j) break if matchbool: #print("Constraint "+constraints[i].to_string()+" is already included in the triangulation") del constraints[i] for i in range(len(constraints) - 1): for j in range(len(constraints) - 1, i, -1): if constraints[i].is_edge(constraints[j]): print("Constraint " + constraints[j].to_string() + " is already included in constraints set") del constraints[j] elif constraints[i].edge_edge_intersect( constraints[j], includeboundary=False): print("Constraint " + constraints[j].to_string() + " intersects with constraint " + constraints[i].to_string() + "; the former has been deleted") del constraints[j] for i in range(len(constraints) - 1, -1, -1): p1bool = False p2bool = False for p in P: if constraints[i].points[0].is_point(p): p1bool = True elif constraints[i].points[1].is_point(p): p2bool = True if p1bool and p2bool: break if not p1bool or not p2bool: print("One of the points in Constraint " + constraints[i].to_string() + " is not included in the triangulation") del constraints[i] for constr in constraints: constr.constraint = True #_constrained_(P,E,T,constraints,constraintIndex) _constrained_(P, E, T, constraints) return P, E, T
def makeMST(): wgraph = adjacencyListW.makeAdjListW() disj = [] #represents list of disjoint sets edgesList = []#stores list of edges mst=[] #stores mst #print('printing the disjoint set') for ver in wgraph: #making disjoint sets and sorting edges of each vertex discurr = [] #creating each disjoint set discurr.append(disjoint.disjVer(ver.name, discurr)) #print(str(discurr[0].name) + ' ', end='') disj.append(discurr) quickSort.sortQuicklyAtt(ver.adj, 0, len(ver.adj)-1)#sorting edges adj to each vertex #print() #print('done printing disjoint sets') for ver in wgraph: #making list of edges for i in ver.adj: #just for printing edges of vertices edgesList.append(edge.edge(disj[int(ver.name)-1][0], disj[int(i.name)-1][0], i.dist)) #print('printing in disj')#check again #for i in disj: # print(str(i[0].name) + ' ', end='') #print('done printing disjoint sets') ''' for i in edgesList: print(str(i.frm.name)+' '+str(i.to.name)+' '+str(i.dist)+' ,',end='') print() ''' quickSort.sortQuicklyAttr(wgraph, 0, len(wgraph)-1)#sorts all the vertices in adjacency list ''' print('after quick sort') for ver in wgraph: print(str(ver.name) + ' ', end='') for i in ver.adj: #just for printing edges of vertices print(str(i.name) + ' ' + str(i.dist) + ' ', end='') print() print('done printing after quick sort') for i in wgraph: #just for printing print(str(i.name) + ' ', end='') for j in i.adj: #just for printing print(str(j.dist) + ' ', end='') print() ''' quickSort.sortQuicklyAtt(edgesList, 0, len(edgesList)-1) print('printing sorted edges') for i in edgesList: print(str(i.frm.name)+' '+str(i.to.name)+' '+str(i.dist)+' ,',end='') print() print('done printing sorted edges') print('here comes the mst') for i in edgesList: if(i.frm.list != i.to.list): mst.append(i) toList = i.to.list #print('tolist '+str(toList)) for j in toList: j.list = i.frm.list i.frm.list.append(j) for i in mst: print(str(i.frm.name)+' '+str(i.to.name)+' '+str(i.dist)+' ,',end='') print()
dt = distance(pts[n], pts[n + 1]) except IndexError: dt = distance(pts[0], pts[-1]) coefs += dt * exp(complex(0, -k * t * 2 * pi / T)) * complex(pts[n][0], pts[n][1]) n += 1 t += dt return coefs / T if __name__ == '__main__': nb_cercles = 50 rayon_minimal = 0 path = 'ens.png' print("Détection d'un bord et des coordonnés de la courbe.") pts = curve(edge(path)) print("Séparation des x et y.") ptsx = [pt[0] for pt in pts] ptsy = [pt[1] for pt in pts] print("Calcul de la période.") T = periode(pts) print("Échantillonage des ts.") p = 1 # précision ts = [t / p for t in range(ceil(T * p) + 1)] print("Calcul des affixes des pts de la série de fourier complexe de la courbe.") zs = fourier_iter(ts, pts, T, N=nb_cercles, p=rayon_minimal)