def main(): # угол поворота angle = 0.05 cube = init_cube() # Единичный вектор angle_dir = 35 dir_p1 = Point(0, 0, 0) dir_p2 = Point(cos(radians(angle_dir)), sin(radians(angle_dir)), 0) dir = Vector3d(dir_p1, dir_p2, 0) line = [Point(dir_p1.x + 100, dir_p1.y + 100), Point(dir_p2.x * 800, dir_p2.y * 800)] while True: for i in pygame.event.get(): if i.type == pygame.QUIT: sys.exit() sc.fill(BLUE) # projection_cube = orthogonal_projection(cube) # projection_line = orthogonal_projection(line) center = Point(0, 0, 600) projection_cube = center_projection(cube, center) projection_line = center_projection(line, center) draw_cube(sc, list(map(lambda point: [point.x, point.y], projection_cube))) draw_lines(sc, list(map(lambda point: [point.x, point.y], projection_line)), RED) for i in range(0, len(cube)): cube[i] = rotation(cube[i], dir, angle) pygame.display.update() clock.tick(FPS)
def alg_Cyrus_Beck(segment, points): reverse_if_left_orientation(points) A = segment[0] B = segment[1] # инициализируем пределы значений параметра, предполагая что отрезок полностью видимый # T = {t0 = 0, t1 = 1} tA = 0 tB = 1 for i in range(len(points)): # зациклинность массива # edge = PiPi+1 try: edge = points[i], points[i + 1] except: edge = points[i], points[0] # --- # находи нормаль normal = Point(edge[1].y - edge[0].y, edge[0].x - edge[1].x) t1 = (normal.x * (edge[1].x - A.x) + normal.y * (edge[1].y - A.y)) t2 = (normal.x * (B.x - A.x) + normal.y * (B.y - A.y)) if t2 != 0: t = t1 / t2 else: continue scalar_product = get_scalar_product(Point(B.x - A.x, B.y - A.y), normal) # Если тип точки потенциально вход. то: if scalar_product > 0: tA = max(tA, t) else: tB = min(tB, t) if tA > tB: return 0, 0 return tA, tB
def main(): # Координаты точек вершин первого многоугольника P = [Point(-5.0, 0.6), Point(-2, 2.1), Point(-7, 3.6), Point(-8, 2.1)] # P = [Point(5, -1), Point(8, 1), Point(8, 4), Point(6, 6), Point(3, 6), Point(1, 3), Point(2, 1)] # Координаты точек вершин второго многоугольника Q = [ Point(1, 2), Point(3, 0), Point(8, 0), Point(10, 2), Point(8, 4), Point(3, 4) ] # Q = [Point(16, 2), Point(21, 4), Point(20, 6), Point(16, 9), Point(13, 7), Point(13, 4)] reverse_polygon(P) reverse_polygon(Q) # Задаем направление точкам speed = 0.25 for point in P: point.set_direction([Vector2d(speed * 1, 0), speed]) for point in Q: point.set_direction([Vector2d(speed * -1, 0), speed]) plot_task(P, Q)
def plot_task(cube, dir_p1, dir_p2, angle): dir = Vector3d(dir_p1, dir_p2, 0) line = [Point(dir_p1.x, dir_p1.y), Point(dir_p2.x * 800, dir_p2.y * 800)] while True: for i in pygame.event.get(): if i.type == pygame.QUIT: sys.exit() sc.fill(BLUE) # ортогональная проекция. new_basis - i столбец - координаты нового i базисного вектора new_basis = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] new_origin = [-100, 0, 0] # projection_cube = orth_proj(cube, new_basis, new_origin) # projection_line = orth_proj(line, new_basis, new_origin) center = Point(0, 0, 1000) projection_cube = center_proj(cube, center, new_basis, new_origin) projection_line = center_proj(line, center, new_basis, new_origin) draw_cube(sc, list(map(lambda point: [point.x, point.y], projection_cube))) draw_lines(sc, list(map(lambda point: [point.x, point.y], projection_line)), RED) for i in range(0, len(cube)): cube[i] = rotation(cube[i], dir, angle) pygame.display.update() clock.tick(FPS)
class SingleLinkageClusteringTest(unittest.TestCase): points = { 'P1': Point('P1', [1.5, 1.5]), 'P2': Point('P2', [2., 1.]), 'P3': Point('P3', [3., 3.]), 'P4': Point('P4', [4., 5.]), 'P5': Point('P5', [5., 3.]) } correct_clusterings = [{ 'C1': Cluster('C1', [points['P1']]), 'C2': Cluster('C2', [points['P2']]), 'C3': Cluster('C3', [points['P3']]), 'C4': Cluster('C4', [points['P4']]), 'C5': Cluster('C5', [points['P5']]) }, { 'C1': Cluster('C1', [points['P1'], points['P2']]), 'C3': Cluster('C3', [points['P3']]), 'C4': Cluster('C4', [points['P4']]), 'C5': Cluster('C5', [points['P5']]) }, { 'C1': Cluster('C1', [points['P1'], points['P2']]), 'C3': Cluster('C3', [points['P3'], points['P5']]), 'C4': Cluster('C4', [points['P4']]) }, { 'C1': Cluster('C1', [points['P1'], points['P2'], points['P3'], points['P5']]), 'C4': Cluster('C4', [points['P4']]) }, { 'C1': Cluster('C1', [ points['P1'], points['P2'], points['P3'], points['P5'], points['P4'] ]) }] def test_first_clustering_version_with_toy_case(self): slc = SingleLinkageClusteringV1(self.points.values()) clusterings = slc.clustering(k=1) self.assertEqual(clusterings, self.correct_clusterings) def test_second_clustering_version_with_toy_case(self): slc = SingleLinkageClusteringV2(self.points.values()) clusterings = slc.clustering(k=1) self.assertEqual(clusterings, self.correct_clusterings) def test_third_clustering_version_with_toy_case(self): slc = SingleLinkageClusteringV3(self.points.values()) clusterings = slc.clustering(k=1) self.assertEqual(clusterings, self.correct_clusterings) def test_fourth_clustering_version_with_toy_case(self): slc = SingleLinkageClusteringV4(self.points.values(), 2, 3, dimension_size=6) clusterings = slc.clustering(k=1) self.assertEqual(clusterings, self.correct_clusterings)
def point_on_line(point, p1, p2): p_max = Point(max(p1.x, p2.x), max(p1.y, p2.y)) p_min = Point(min(p1.x, p2.x), min(p1.y, p2.y)) if define_orientation( p1, p2, point ) == "on" and p_min.x <= point.x <= p_max.x and p_min.y <= point.y <= p_max.y: return True else: return False
def main(): # угол поворота angle = 0.05 cube = init_cube() # Единичный вектор angle_dir = 35 dir_p1 = Point(0, 0, 0) dir_p2 = Point(cos(radians(angle_dir)), sin(radians(angle_dir)), 0) plot_task(cube, dir_p1, dir_p2, angle)
def center_arc(pt1, pt2, bulge): if bulge > 0.: inc_angle = 4. * np.arctan(bulge) elif bulge < 0.: inc_angle = -4. * np.arctan(bulge) chord = Vector([pt2[i] - pt1[i] for i in range(3)]) mid = Point([0.5 * (pt1[i] + pt2[i]) for i in range(3) ]) vec = (chord.norm * 0.5 * bulge * cross(chord, Vector((0., 0., 1.))).unit()) summit = Point([mid[i] + vec[i] for i in range(3) ]) radius = chord.norm / (2. * np.sin(inc_angle/2.)) vec = radius * Vector([mid[i] - summit[i] for i in range(3)]).unit() center = Point([summit[i] + vec[i] for i in range(3) ]) return center
def _add_point(self, x, y): """ Creates new Point at given coordinate if it does not already exist :return: Point at given coordinates """ if y in self._points: if x not in self._points[y]: self._points[y][x] = Point(x, y) else: self._points[y] = {} self._points[y][x] = Point(x, y) return self._points[y][x]
def rotation(point, n, angle): s = sin(angle / 2) n_q = get_quaternion(cos(angle / 2), Point(n.x * s, n.y * s, n.z * s)) n_q_conj = get_conj_quaternion(n_q) p_q = get_quaternion(0, point) return quaternions_multiplication(quaternions_multiplication(n_q, p_q), n_q_conj)[1]
def center_projection(points, center): projection = [] for p in points: x = p.x * (center.z / (center.z - p.z)) + center.x * (p.z / (center.z - p.z)) y = p.y * (center.z / (center.z - p.z)) + center.y * (p.z / (center.z - p.z)) projection.append(Point(x, y)) return projection
def get_intersection(p1, p2, p3, p4): # p = p3 + t(p4 - p3) n = Vector2d(-(p2.y - p1.y), p2.x - p1.x) t = (Vector2d.scalar_product(n, Vector2d( p3, p1))) / (Vector2d.scalar_product(n, Vector2d(p3, p4))) p = Vector2d(p3, p4) return Point(p3.x + t * p.x, p3.y + t * p.y)
def get_max_point(polygon): max_x = polygon[0].x max_y = polygon[0].y for i in range(0, len(polygon)): if polygon[i].x > max_x: max_x = polygon[i].x if polygon[i].y > max_y: max_y = polygon[i].y return Point(max_x, max_y)
def get_min_point(polygon): min_x = polygon[0].x min_y = polygon[0].y for i in range(0, len(polygon)): if polygon[i].x < min_x: min_x = polygon[i].x if polygon[i].y < min_y: min_y = polygon[i].y return Point(min_x, min_y)
def __init__(self, point1, point2, point3=Point(0, 0, 0)): if type(point1) == Point: self.x = point2.x - point1.x self.y = point2.y - point1.y self.z = point2.z - point1.z else: self.x = point1 self.y = point2 self.z = point3
def quaternions_multiplication(q1, q2): p0 = q1[0] * q2[0] - q1[1].x * q2[1].x - q1[1].y * q2[1].y - q1[1].z * q2[ 1].z p1 = q1[0] * q2[1].x + q1[1].x * q2[0] + q1[1].y * q2[1].z - q1[1].z * q2[ 1].y p2 = q1[0] * q2[1].y + q1[1].y * q2[0] + q1[1].z * q2[1].x - q1[1].x * q2[ 1].z p3 = q1[0] * q2[1].z + q1[1].z * q2[0] + q1[1].x * q2[1].y - q1[1].y * q2[ 1].x return get_quaternion(p0, Point(p1, p2, p3))
def __init__(self, cell): super().__init__(cell) self.body = [Point(0, 1), Point(1, 1), Point(1, 0), Point(2, 0)] self.bodies = [ self.body, [ Point(1, 2), Point(1, 1), Point(0, 1), Point(0, 0), ] ]
def orthogonal_projection(points): new_basis = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] new_origin = [-100, 0, 0] projection = [] for p in points: new_x = new_basis[0][0] * (p.x - new_origin[0]) + new_basis[1][0] * (p.y - new_origin[1]) + new_basis[2][0] * ( p.z - new_origin[2]) new_y = new_basis[0][1] * (p.x - new_origin[0]) + new_basis[1][1] * (p.y - new_origin[1]) + new_basis[2][1] * ( p.z - new_origin[2]) projection.append(Point(new_x, new_y)) return projection
def orth_proj(points, new_basis, new_origin): projection = [] for p in points: matrix = multiply_matrix(new_basis, [[p.x - new_origin[0]], [p.y - new_origin[1]], [p.z - new_origin[2]]]) new_x = matrix[0][0] new_y = matrix[1][0] new_z = matrix[2][0] projection.append(Point(new_x, new_y, new_z)) return projection
def center_proj(points, center, new_basis, new_origin): new_points = orth_proj(points, new_basis, new_origin) new_center = orth_proj([center], new_basis, new_origin)[0] projection = [] for p in new_points: x = p.x * (new_center.z / (new_center.z - p.z)) + new_center.x * ( p.z / (new_center.z - p.z)) y = p.y * (new_center.z / (new_center.z - p.z)) + new_center.y * ( p.z / (new_center.z - p.z)) projection.append(Point(x, y)) return projection
def define_circle(p1, p2, p3): # Returns the center and radius of the circle passing the given 3 points. # In case the 3 points form a line, returns (None, infinity). temp = p2[0] * p2[0] + p2[1] * p2[1] bc = (p1[0] * p1[0] + p1[1] * p1[1] - temp) / 2 cd = (temp - p3[0] * p3[0] - p3[1] * p3[1]) / 2 det = (p1[0] - p2[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p2[1]) if abs(det) < 1.0e-6: return (None, np.inf) # Center of circle cx = (bc * (p2[1] - p3[1]) - cd * (p1[1] - p2[1])) / det cy = ((p1[0] - p2[0]) * cd - (p2[0] - p3[0]) * bc) / det radius = np.sqrt((cx - p1[0])**2 + (cy - p1[1])**2) return (Point(cx, cy), radius)
def __init__(self, cw, b_tl, b_tr, b_br, b_bl): """ :param cw: CWrapper object :param b_tl: top-left point of a box :param b_tr: top-right point of a box :param b_br: bottom-right point of a box :param b_bl: bottom-left point of a box """ self._cw = cw self.boundary = [b_tl, b_tr, b_br, b_bl] # box fitted into boundaries self._rigid = [b_tl.copy(), b_tr.copy(), b_br.copy(), b_bl.copy()] self.boundary[0].link(self._rigid[0]) self.boundary[1].link(self._rigid[1]) self.boundary[2].link(self._rigid[2]) self.boundary[3].link(self._rigid[3]) # homography matrices self.H = None H_A = [] H_B = [None] * 8 for s in self._rigid: H_A.append([s.ix, s.iy, 1, 0, 0, 0, None, None]) H_A.append([0, 0, 0, s.ix, s.iy, 1, None, None]) self.H_A = np.array(H_A) self.H_B = np.array(H_B) # centroids cache self._qc = Point(0, 0) # target centroid self._pc = Point(0, 0) # source centroid, same during whole object live self.compute_source_centroid()
def parser(points): print("⚙️ Parsing process"+utils.OKGREEN, os.getpid(), utils.ENDC + "started") trips = [] # Add the point to an existing trip or creating a new one if it doesn't exist for point in points: new_point = Point(point[0], point[2], point[3], point[4]) exists = False for trip in trips: if (trip.id == point[1]): trip.points.append(new_point) exists = True if (exists == False): new_trip = Trip(point[1], [new_point]) trips.append(new_trip) return trips
def init_cube(): start_point = Point(300, 200, 100) side_length = 50 # Куб cube = [ start_point, Point(start_point.x + side_length, start_point.y, start_point.z), Point(start_point.x, start_point.y + side_length, start_point.z), Point(start_point.x + side_length, start_point.y + side_length, start_point.z), Point(start_point.x, start_point.y, start_point.z + side_length), Point(start_point.x + side_length, start_point.y, start_point.z + side_length), Point(start_point.x, start_point.y + side_length, start_point.z + side_length), Point(start_point.x + side_length, start_point.y + side_length, start_point.z + side_length) ] return cube
def calculateDistanceMap(macarte: numpy.array, murs) -> int: ## <DONTCOPY> ## from classes.Point import Point from classes.Game import Game from classes.Debug import Debug import time ## </DONTCOPY> ## #Pathfinding.distanceMap = {{None} * len(macarte[0])} * len(macarte) #Pathfinding.distanceMap = numpy.empty((len(macarte), len(macarte[0]), len(macarte), len(macarte[0])), dtype=object) Pathfinding.distanceMap = {} nbCalcMap = 0 totalCalcExpected = 0 casesOk = [] for x in range(len(macarte)): Pathfinding.distanceMap[x] = {} for y in range(len(macarte[0])): if macarte[x][y] not in murs: Pathfinding.distanceMap[x][y] = None casesOk.append((x, y)) totalCalcExpected += 1 else: Pathfinding.distanceMap[x][y] = None for x, y in casesOk: if not Game.check_timeout(): tmp = Pathfinding.buildDistanceMap(macarte, Point(x, y), [False], 15) assert tmp[x][y] == 0 Pathfinding.distanceMap[x][y] = tmp nbCalcMap += 1 else: Debug.msg( f"checkDistanceMap stopped at {x},{y} ({round(nbCalcMap*100/totalCalcExpected)} %) with {time.time() - Game.startTime}" ) return nbCalcMap return nbCalcMap
def convex_hull(points): if(len(points) < 2): print("insufficient points") return 0 pointsCopy = points.copy() pointsCopy.sort(key=sorter) hull = [] point_to_add = points[0] endpoint = Point(0, 0) while endpoint != pointsCopy[0]: hull.append(point_to_add) endpoint = pointsCopy[0] temp_line = Line_Segment(hull[-1], endpoint) for a_point in pointsCopy: if lr(temp_line, a_point) == 1 or point_to_add == endpoint: endpoint = a_point temp_line = Line_Segment(hull[-1], endpoint) point_to_add = endpoint return hull
p.reflect_direction() for p in points_set: p.move() plt.scatter(p.x, p.y) plt.draw() plt.gcf().canvas.flush_events() sleep(0.0001) plt.ioff() plt.show() if __name__ == '__main__': points_set = [ Point(1, 1), Point(4, 3), Point(2, 2), Point(4, 5), Point(9, 3), Point(6, 4), Point(3, 0), Point(8, 1), Point(2, 4), Point(1.5, 3), Point(7, 3), Point(10, 7), Point(4, 5) ] # Set points direction
#! /usr/bin/pythonw from classes.CompteBancaire import CompteBancaire from classes.Point import Point from classes.Personne import Personne from classes.DateDeNaissance import DateDeNaissance from classes.Employe import Employe from classes.Chef import Chef #Exercice compte bancaire compte1 = CompteBancaire() compte1.depot(900) compte1.affichage() print('\n') #Exercice point point1 = Point(10, -34.5) point1.toString() print('\n') #Exercice heritage personne = Personne("AZIS", "Widad", DateDeNaissance(28, 6, 1997).toString()) personne.afficher() print('\n') employe = Employe("Ilyass", "Math", DateDeNaissance(20, 7, 1995).toString(), 1265.50) employe.afficher() print('\n') chef = Chef("Ilyan", "Ti", DateDeNaissance(1, 7, 1980).toString(), 3865.548, "Chef") chef.afficher()
# Сортировка всех точек points.sort(key=lambda point: (point.y, point.x)) # Строим Ттреугольник на первых 3 точках points[0].bind(points[1]) points[1].bind(points[2]) points[2].bind(points[0]) convex_hall = points[:3] # Далее идем по остальным точ# convex_hall = add_point(convex_hall, points[3]) for i in range(3, len(points)): convex_hall = add_point(convex_hall, points[i]) return points if __name__ == "__main__": fig, ax = plt.subplots() # points1 = [Point(0, 8.5), Point(8.2, 0), Point(8, 4), Point(14, 4), Point(19, 5.5), Point(3, 11), Point(7, 12), # Point(12, 11.5), Point(17, 9), Point(19, 5.5)] coords = [(35, 425), (123, 365), (240, 192), (480, 67), (512, 212), (671, 161), (897, 431), (800, 383), (674, 377), (553, 445), (454, 542), (374, 452), (266, 394), (344, 374)] points2 = [Point(coord[0], coord[1]) for coord in coords] # draw_graph(create_triangulation(points1)) # for point in points1: # plt.plot(point.x, point.y, 'ro') # plt.show() draw_graph(create_triangulation(points2)) for point in points2: plt.plot(point.x, point.y, 'ro') plt.show()
plt.gcf().canvas.flush_events() sleep(0.0001) # Сохраняем анимацию animation = camera.animate() animation.save('animation.gif', writer='imagemagick') plt.ioff() plt.show() if __name__ == '__main__': pylab.xlim(-1, 24) pylab.ylim(-2, 10) first_polygon = [ Point(5, -1), Point(2, 1), Point(1, 3), Point(3, 6), Point(6, 6), Point(8, 4), Point(8, 1) ] # Set Direction speed = 0.25 for point in first_polygon: point.set_direction([Vector2d(speed * 1, 0), speed]) second_polygon = [ Point(16, 2), Point(13, 4),