def readEdgeFromTxt(self): edge_list = [] if self.txtpath: try: file = open(self.txtpath, "r") line = file.readline() print(line) s_list = line.split(",") for s in s_list: print(s) # print(len(s)) if s: # print(s[0]) s = s.strip() v_s = Vertex(-1, s[0]) v_e = Vertex(-1, s[1]) d = int(s[2]) edge = Edge(v_s, v_e, d) edge_list.append(edge) except IOError: return None else: # print(edge_list) return edge_list
def leg_dk(theta1, theta2, theta3, l1=L1, l2=L2, l3=L3, alpha=Alpha, beta=Beta): Angle = Vertex(theta1, theta2, theta3) #Modification od theta1 and theta2 according constraint theta2 += alpha theta3 = 90 - (alpha + beta + theta3) #print "Angles : " + str(theta1) + " ; " + str(theta2) + " ; " + str(theta3) theta1 = radians(theta1) theta2 = -radians(theta2) theta3 = -radians(theta3) #Storing all the sinus and cosinus into variable in order to simplify and run the calculation only once c_1 = cos(theta1) c_2 = cos(theta2) c_2_3 = cos(theta2 + theta3) s_1 = sin(theta1) s_2 = sin(theta2) s_2_3 = sin(theta2 + theta3) #calculation of the projections and the differences due to the robot setting projection = l1 + (l2 * c_2) + (l3 * c_2_3) #Calculation of the final position Final = Vertex((projection * c_1), (projection * s_1), ((l2 * s_2) + (l3 * s_2_3))) return Final
def TestCrossProduct(self, polygon): #This test should pass (point inside the polygon) v1 = polygon.first_node.vertex v2 = polygon.first_node.next_node.next_node.vertex mid_x = (v1.x + v2.x) / 2 mid_y = (v1.y + v2.y) / 2 midpoint = Vertex.Vertex(mid_x, mid_y) test = polygon.Collision(midpoint) if test: self.Update_Lists( True, "PASS::" + midpoint.Display() + " Collides with the polygon, that's good") else: self.Update_List( False, "FAIL::" + midpoint.Display() + " Does not collide with the polygon, that's bad") #This test should fail (point outside of the polygon) trajectory_x = -1 * (v2.x - v1.x) trajectory_y = -1 * (v2.y - v1.y) v3 = Vertex.Vertex(v1.x + trajectory_x, v1.y + trajectory_y) test = polygon.Collision(v3) if test: self.Update_Lists( False, "FAIL::" + v3.Display() + " Collides with the polygon, that's bad") else: self.Update_Lists( True, "PASS::" + v3.Display() + " Does not collide with the polygon, that's good") #This test should pass (Point on the edge of the polygon) v3 = polygon.first_node.vertex test = polygon.Collision(v3) if test: self.Update_Lists( True, "PASS::" + v3.Display() + " Collides with the polygon, that's good") else: self.Update_Lists( False, "FAIL::" + v3.Display() + " Does not collide with the polygon, that's bad")
def Collision(self, point): #print("Polygon::Collision::") if self.first_node is None: print("This polygon is empty") return next_node = self.first_node.next_node #print("\tfirst_node = " + self.first_node.vertex.Display()) #print("\tnext_node = " + next_node.vertex.Display()) tempx = next_node.vertex.x - self.first_node.vertex.x tempy = next_node.vertex.y - self.first_node.vertex.y a = Vertex.Vertex(tempx, tempy) #print("\ta = " + a.Display()) tempx = point.x - next_node.vertex.x tempy = point.y - next_node.vertex.y b = Vertex.Vertex(tempx, tempy) #print("\tb = " + b.Display()) test = self.Cross(a, b) if test < 0: #print("\t" + point.Display() + " does not collide") return False cur = next_node while cur is not self.first_node: if (cur.next_node is None): print("Something is wrong, next node is null") next_node = cur.next_node tempx = next_node.vertex.x - cur.vertex.x tempy = next_node.vertex.y - cur.vertex.y a = Vertex.Vertex(tempx, tempy) tempx = point.x - next_node.vertex.x tempy = point.y - next_node.vertex.y b = Vertex.Vertex(tempx, tempy) #print("\tTesting " + a.Display() + " x " + b.Display()) test = self.Cross(a, b) if test < 0: #print("\t" + point.Display() + " does not collide") return False cur = next_node return True
def __init__(self): hive = Vertex('v0') # the three arms arm1 = [Vertex('v' + str(i)) for i in range(1, 5)] arm2 = [Vertex('v' + str(i)) for i in range(5, 12)] arm3 = [Vertex('v' + str(i)) for i in range(12, 24)] # connects the arms to the hive hive.neighbors.extend([arm1[0], arm2[0], arm3[0]]) for arm in [arm1, arm2, arm3]: arm[0].neighbors.append(hive) for i in range(len(arm) - 1): arm[i].neighbors.append(arm[i + 1]) arm[i + 1].neighbors.append(arm[i]) self.list_of_vertices = [hive] + arm1 + arm2 + arm3
def __init__(self, num): super(GridGraph, self).__init__() vertex_matrix = [] v = 0 # creates an array of arrays of vertices for the grid for i in range(int(floor(sqrt(num)))): matrix = [] for k in range(int(ceil(sqrt(num)))): matrix.append(Vertex(name='v' + str(v))) v += 1 vertex_matrix.append(matrix) # connects vertices together in a grid-like format for k in range(len(vertex_matrix)): # iterate rows for i in range(len(vertex_matrix[k])): # iterate columns current_vertex = vertex_matrix[k][i] if i > 0: current_vertex.neighbors.append(vertex_matrix[k][i - 1]) if i < len(vertex_matrix[k]) - 1: current_vertex.neighbors.append(vertex_matrix[k][i + 1]) if k > 0: current_vertex.neighbors.append(vertex_matrix[k - 1][i]) if k < len(vertex_matrix) - 1: current_vertex.neighbors.append(vertex_matrix[k + 1][i]) self.list_of_vertices.extend(vertex_matrix[k])
def grilleToVertexMatrix(self): vertexMatrix = list() for i in range(0, len(self.grille)): vertexMatrix.append([]) for j in range(0, len(self.grille[0])): vertexMatrix[i].append(Vertex(self.grille[i][j])) return vertexMatrix
def dijkstra(self): que = Queue.Queue() # kolejka wierzchołków do sprawdzenia shortest_paths = [ ] # tablica przechowująca wierzchołki z indeksem, dystansem i poprzednikiem for i in range(self.vertices): que.insert(Vertex.Vertex(i, -1, inf, '')) que.set_distance(self.start, 0) while not que.is_empty(): current = que.remove() shortest_paths.append(current) for i in range(self.vertices): if que.contains( i ): # sprawdź, czy sprawdzany wierzchołek nie ma już wyliczonej najkrótszej ścieżki if current.distance + self.adjacency_matrix[ current.index][i] < que[ i].distance: # jeśli droga przez current jest krótsza: que.set_distance( i, current.distance + self.adjacency_matrix[current.index][i] ) # ustaw ją jako nowy dystans que.set_previous( i, current.index) # aktualizuj poprzednika que.set_path(i, f'{current.path}{current.index} -> ' ) # aktualizuj sciezke return shortest_paths
def read_from_off(self, path): with open(path) as f: counter = 0 h = 0 n = 0 m = 0 for line in f: if counter == 0: if line.split()[0] != 'OFF': print('This is not an OFF file') break elif counter == 1: (n, m, mm) = map(int, line.split()) elif counter < n + 2: (x, y, z) = map(float, line.split()) self.vertices.append(Vertex(p=Vector3D(x, y, z), index=counter - 2)) elif counter < n + m + 2: indices = [int(x) for x in line.split()] v = indices[0] indices = indices[1:] h = [] for i in range(v - 1): h.append(self.find_edge(indices[i], indices[i+1])) h.append(self.find_edge(indices[v - 1], indices[0])) for i in range(v - 1): h[i].nh = h[i + 1] h[i + 1].ph = h[i] h[v - 1].nh = h[0] h[0].ph = h[v - 1] face = Face(side=h[v - 1], n=v, index=len(self.faces)) self.faces.append(face) for i in range(v): h[i].polygon = face counter += 1
def __init__(self, class_fn, vertex_fn, edge_fn, feature_fn, meta_fn, train_fn, val_fn, test_fn): self.class_fn = class_fn self.vertex_fn = vertex_fn self.edge_fn = edge_fn self.feature_fn = feature_fn self.meta_fn = meta_fn self.train_fn = train_fn self.val_fn = val_fn self.test_fn = test_fn self.load_meta() self.load_edges() self.train = self.load_indices(self.train_fn) self.val = self.load_indices(self.val_fn) self.test = self.load_indices(self.test_fn) assert self.nVertices <= self.nPapers assert self.nNoFeatures >= 0 self.vertices = [] for index in range(self.nPapers): self.vertices.append(Vertex.Vertex(index)) self.load_name() self.load_class() self.load_feature() self.set_labels_and_masks() self.validate_data()
def leg_ik(x, y, z, l1=L1, l2=L2, l3=L3, alpha=Alpha, beta=Beta): l_proj = sqrt(x * x + y * y) d13 = l_proj - l1 d = sqrt(z * z + d13 * d13) if (d13 == 0): a = 0 else: a = atan(z / d13) if (d == 0): b = 0 else: b = al_kashi(l3, l2, d) if (x == 0): theta1 = 0 else: theta1 = atan(y / x) theta2 = b + a theta3 = pi - al_kashi(d, l3, l2) angle = Vertex(degrees(theta1), degrees(theta2), degrees(theta3)) print(str(angle))
def add_vertices(self): ''' Adds vertices to all the tiles that are correctly shared by neighboring tiles. Args: None Returns: None ''' for row in self.tile_array: for tile in row: for index, vertex in enumerate(tile.vertex_arr): if vertex is None: # initialize vertex and attach it to tile and vice versa vertex = tile.vertex_arr[index] = Vertex.Vertex() vertex.tile_arr[0] = tile if tile.tile_arr[index]: # for one neighbor (border tiles) attach vertex to neighbor and vice versa tile.tile_arr[index].vertex_arr[(index + 4) % 6] = vertex vertex.tile_arr[1] = tile.tile_arr[index] if tile.tile_arr[index - 1] is not None: # for two neighbors (center tiles) do the same again for vertices tile.tile_arr[index - 1].vertex_arr[(index + 2) % 6] = vertex vertex.tile_arr[2] = tile.tile_arr[index - 1]
def generateProjBn(self, height, projVec, baseVec): translateVec = [0, 0, 0] newCentroid = [0, 0, 0] print("Normal Vector: " + str(self.normalVector)) print("Base Vector: " + str(baseVec)) if self.checkIfVecEqual(baseVec, self.normalVector) == False: for y in range(3): print("y: " + str(y)) translateVec[y] = self.normalVector[y] - baseVec[y] else: translateVec = self.normalVector for z in range(3): newCentroid[z] = self.centroid[z] + translateVec[z] newCentroid = tuple(newCentroid) BnNew = B_n(self.numOfVertices, False, self.radius, newCentroid, self.normalVector, False) #This represent the top self.scaleVector(translateVec, height) iteratedTuple = [0, 0, 0] for x in range(self.numOfVertices): iteratedTuple[ 0] = self.verticesSet[x].vertexPosition[0] + translateVec[0] iteratedTuple[ 1] = self.verticesSet[x].vertexPosition[1] + translateVec[1] iteratedTuple[ 2] = self.verticesSet[x].vertexPosition[2] + translateVec[2] vertexNew = Vertex(self.numOfVertices, tuple(iteratedTuple), x + 1) BnNew.verticesSet.append(vertexNew) return BnNew
def randomPoints(n): arr = [] for i in range(n): vt = Vt.Vertex(rand.randrange(0, 100), rand.randrange(0, 100)) vt.x = vt.x * 10 vt.y = vt.y * 7.2 arr.append(vt) return arr
def __init__(self, aGraphName, aVertices, aEdges): self.Name = aGraphName self.Vertices = List[Vertex]([Vertex(vertex) for vertex in aVertices.split(',')]) self.Edges = [Edge for Edge in aEdges] self.Adj = {} self.__CreateAdjDict()
def add_vertex(self, element, coordinates): v = Vertex(element) self._structure[v] = dict() self._coordinates[v] = coordinates # add vertex v with associated coordinates to dict self._elements[element] = v # add vertex v to dict with element as key return v
def set_branch_bipartite(self, data, branch): start = 270 - 60 * int((data - 1) / 2) if (branch == 'left'): self.left_size = data self.erase_branch('left') for i in range(data): self.left_branch.append(VE.Vertex(self, 60, start + 60 * i, i, 'left')) for vertex in self.left_branch: games.screen.add(vertex) else: self.right_size = data self.erase_branch('right') for i in range(data): self.right_branch.append(VE.Vertex(self, 400, start + 60 * i, i, 'right')) for vertex in self.right_branch: games.screen.add(vertex)
def __init__(self, num): super(CompleteGraph, self).__init__() self.list_of_vertices = [Vertex(name='v' + str(i)) for i in range(num)] # connects all vertices to each other for i in range(len(self.list_of_vertices)): self.list_of_vertices[i].neighbors = self.list_of_vertices[ 0:i] + self.list_of_vertices[i + 1::]
def initSpace(xmax, ymax, points): point_list = [] for i in range(points): vertex = Vertex(randint(1, xmax - 1), randint(1, ymax - 1)) point_list.append(vertex) print("Tree initialized") return point_list
def getVertex(self, vertexName, propert, createNew=False): try: v = self.vertexMap.get(vertexName) if v is None and createNew: v = Vertex(vertexName, propert) self.vertexMap[vertexName] = v return v except KeyError as e: print("Exception ", e)
def __init__(self, num, sparseness=.5): # sparseness ranges from 0 to 1, with .5 being an average graph super(RandomGraph, self).__init__() self.list_of_vertices = [Vertex(name='v' + str(i)) for i in range(num)] for i in range(len(self.list_of_vertices)): self.list_of_vertices[i].neighbors = [] self.generate_connections(sparseness)
def get_vertices(self): Temp = {} for edge in self.edge_list: Temp[edge.start] = [] Temp[edge.end] = [] for edge in self.edge_list: Temp[edge.start].append(edge) Temp[edge.end].append(edge) for key, value in Temp.items(): self.vertices.append(Vertex.Vertex(key, value))
def __init__(self, vertices, aristas, dirigida): super(Graph, self).__init__() self.dirigida = dirigida self.vertices = [None] * vertices.__len__() for i in range(0, vertices.__len__()): self.vertices[i] = Vertex(vertices[i]) self.aristas = [None] * aristas.__len__() for i in range(0, aristas.__len__()): self.aristas[i] = Edge(aristas[i][0], aristas[i][1], aristas[i][2]) self.q = Queue.Queue() self.auxVertices = 0
def build_dcel(self, points): size = len(points) face = Face() self.faces.append(face) prev_left_edge = None prev_right_edge = None for i in range(size): point = points[i] vertex = Vertex() left = HalfEdge() right = HalfEdge() left.face = face left.next_hedge = None left.origin = vertex left.twin = right right.face = None right.next_hedge = prev_right_edge right.origin = None right.twin = left self.hedges.append(left) self.hedges.append(right) vertex.incident_edge = left vertex.point = point self.vertices.append(vertex) if prev_left_edge is not None: prev_left_edge.next_hedge = left if prev_right_edge is not None: prev_right_edge.origin = vertex prev_left_edge = left prev_right_edge = right first_left_edge = self.hedges[0] prev_left_edge.next_hedge = first_left_edge first_right_edge = self.hedges[1] first_right_edge.next_hedge = prev_right_edge prev_right_edge.origin = self.vertices[0] face.wedge = first_left_edge for hedge in self.hedges: hedge.next_hedge.prev_hedge = hedge
def initializeSelf(self): """ This initializes Bn with the norm vec where none of the positions of the vertices are given """ firstVpoint = self.getFirstPoint() v1 = Vertex(self.numOfVertices, firstVpoint, 1) self.verticesSet.append(v1) self.currentNumOfVertices += 1 self.generateVertices(self.verticesSet[0]) self.printVertexCoordinate()
def initializeFirst(self): """ THIS IS A GARBAGE FUNCTION. DONT USE AGAIN """ alpha = 2 * np.pi / self.numOfVertices if self.isFirst == False: return else: centroid = (0, 0, 0) #Always start at the origin v1 = Vertex(self.numOfVertices, (self.radius, 0, 0), 1) self.verticesSet.append(v1) xPos = 0 yPos = 0 vHolder = None for i in range(1, self.numOfVertices): xPos = self.radius * np.cos(i * alpha) yPos = self.radius * np.sin(i * alpha) vHolder = Vertex(self.numOfVertices, (xPos, yPos, 0), i + 1) self.verticesSet.append(vHolder)
def testKCenter(): vertices = [] for i in range(1, 1000): vertex = Vertex() vertex.pos.x = random.randint(-100, 100) vertex.pos.y = random.randint(-100, 100) vertices.append(vertex) kSet = solveKCenter(vertices, 10) graph = Graph(kSet) # For debugging print graph.toString()
def readCSV(archivo): graph = Graph() reader = csv.reader(open(os.getcwd() + "/ejemplos/" + archivo, 'r')) tipo = next(reader, None) if tipo == ['direct=1']: graph.set_dirigida(True) for row in enumerate(reader): if row[1][0] not in graph.get_etiquetas(): graph.add_vertice(Vertex(row[1][0], 1, [row[1][1][2::3]])) else: for vertice in graph.vertices(): if vertice.etiqueta == row[1][0]: vertice.add_vecino(row[1][1][2::3]) if row[1][1][2::3] not in graph.get_etiquetas(): graph.add_vertice(Vertex(row[1][1][2::3], 1, [row[1][0]])) else: for vertice in graph.vertices(): if vertice.etiqueta == row[1][1][2::3]: vertice.add_vecino(row[1][0]) graph.add_arista(Edges(row[1][0], row[1][1][2::3], row[1][2][1::])) return graph
def ReadInFromList(self, path): file = open(path, "r") contents = file.readlines() for i in range(len(contents)): x, y = map(int, contents[i].strip('()\n\s').split(',')) v = Vertex.Vertex(x, y) self.Add_Vertex(v) self.Connect() self.Display() file.close()
def scaleLine(self, length): PointO = np.array(self.vertexSource.vertexPosition) PointD = np.array(self.vertexSignaled.vertexPosition) dist = np.linalg.norm(PointO - PointD) print("Distance: " + str(dist)) print("Vec: " + str(PointO - PointD)) vecToScale = PointD - PointO self.scaleVector(vecToScale, length) print("Scaled Vec: " + str(vecToScale)) PointDnew = PointO + vecToScale idNew = self.vertexSignaled.vertexID self.newVertexSignaled = Vertex(self.vertexSource.numOfVertices, PointDnew, idNew)