def mult(num, point: Point, curve: Curve): if curve.p != 2: assert point.is_on_curve(curve) if point.is_infinity: return point if num < 0: return mult(-num, point.point_neg(curve), curve) result = Point() addend = point while num: if num & 1: result = add(result, addend, curve) addend = add(addend, addend, curve) num >>= 1 if curve.p != 2: assert result.is_on_curve(curve) return result
def draw(map, start, stop): global RectSize width = map.width height = map.height image = Image.new('RGB', (width * RectSize, height * RectSize), color='white') drawer = ImageDraw.Draw(image) for y in range(height): for x in range(width): node = map.getNode(Point(x, y)) point = Point(x * RectSize, (height - y - 1) * RectSize) drawRect(node, point, drawer) if node.getPoint() == start: drawText(node, point, drawer, 'S') elif node.getPoint() == stop: drawText(node, point, drawer, 'E') if node.getState() == 'c' or node.getState() == 'o': drawCost(node, point, drawer) drawTriangle(node, point, drawer) saveFile(image)
def _from_multiple_throws(throws: List[Throw], d_facing: float) -> 'IntersectionWithError': best_guess = intersect_multiple(throws) guesses = 10 other_guesses = [] deviations = np.clip(np.random.standard_normal((guesses, len(throws))), -2, 2) for _deviations in deviations: _guess = intersect_multiple([ dataclasses.replace(throw, facing=throw.facing + d_facing * _deviations[i]) for i, throw in enumerate(throws) ]) other_guesses.append(_guess) return IntersectionWithError( Point(x=best_guess.x, z=best_guess.z), x_range=( min(_guess.x for _guess in other_guesses), max(_guess.x for _guess in other_guesses), ), z_range=( min(_guess.z for _guess in other_guesses), max(_guess.z for _guess in other_guesses), ), )
def intersect_2(throw_1: Throw, throw_2: Throw) -> Point: heading_1 = throw_1.heading cos_1 = cos(heading_1) sin_1 = sin(heading_1) heading_2 = throw_2.heading cos_2 = cos(heading_2) sin_2 = sin(heading_2) assert heading_1 != heading_2, f"Throw headings must not be aligned, lines do not intersect. ({heading_1} and {heading_2})" dx = throw_2.point.x - throw_1.point.x dz = throw_2.point.z - throw_1.point.z if abs(cos_1) > 0.01: k = sin_1 / cos_1 den = cos_2 * k - sin_2 t = (dz - dx * k) / den else: k = cos_1 / sin_1 den = sin_2 * k - cos_2 t = (dx - dz * k) / den x = throw_2.point.x + t * cos_2 z = throw_2.point.z + t * sin_2 t_1 = (x - throw_1.point.x) / cos_1 t_2 = (z - throw_1.point.z) / sin_1 assert t > 0 and t_1 > 0 and t_2 > 0, f"Calculated intersection goes backwards (scales: {t:}, {t_1}, {t_2})" return Point(x, z)
def _from_2_throws(throw_1: Throw, throw_2: Throw, d_facing: float) -> 'IntersectionWithError': best_guess = intersect_2(throw_1, throw_2) other_guesses = [] throw_1_minus = dataclasses.replace(throw_1, facing=throw_1.facing - d_facing) throw_1_plus = dataclasses.replace(throw_1, facing=throw_1.facing + d_facing) throw_2_minus = dataclasses.replace(throw_2, facing=throw_2.facing - d_facing) throw_2_plus = dataclasses.replace(throw_2, facing=throw_2.facing + d_facing) for _throw_1, _throw_2 in [ (throw_1_minus, throw_2_minus), (throw_1_plus, throw_2_minus), (throw_1_minus, throw_2_plus), (throw_1_plus, throw_2_plus), ]: _guess = intersect_2(_throw_1, _throw_2) other_guesses.append(_guess) return IntersectionWithError( Point(x=best_guess.x, z=best_guess.z), x_range=( min(_guess.x for _guess in other_guesses), max(_guess.x for _guess in other_guesses), ), z_range=( min(_guess.z for _guess in other_guesses), max(_guess.z for _guess in other_guesses), ), )
def add(point1: Point, point2: Point, curve: Curve): if point1.is_infinity: return point2 if point2.is_infinity: return point1 x1, y1 = point1.x, point1.y x2, y2 = point2.x, point2.y if x1 == x2 and (y1 != y2 or x1 == 0 and curve.t == 'N'): return Point() k = curve.get_k(x1, y1, x2, y2) x, y = curve.get_x3_y3(k, x1, y1, x2) result = Point(x, y) return result
def drawing(self): description = "---" for z in range(self.cube_dimension): columns = [] for x in range(self.cube_dimension): rows = [] for y in range(self.cube_dimension): rows.append("1" if Point(x, y, z) in self.filled_points else "0") columns.append(", ".join(rows)) description += "\n".join(columns) + "\n---\n" return description
class Piece(): DIMENSIONS = Point( 2, 6, 2, ) @staticmethod def get_dimensions(): return Point(Piece.Z, Piece.Y, Piece.X) def __init__(self, name, file_name, board_size, is_inverted=False): self.name = name self.file_name = file_name self.board_size = board_size self.is_inverted = is_inverted self.piece_matrix = self._get_piece_matrix() self.padded_matrix = self._get_padded_matrix() self.inversion = None def _get_padded_matrix(self): blank_matrix = utilities.generate_3d_matrix(False, self.board_size) dim = Piece.DIMENSIONS start = INSERTION_POINT # hack away! for z in range(dim.Z): for y in range(dim.Y): for x in range(dim.X): z_board = start.Z + z y_board = start.Y + y x_board = start.X + x blank_matrix[z_board][y_board][ x_board] = self.piece_matrix[z][y][x] return blank_matrix def _get_piece_matrix(self): piece_matrix = read.read_block(self.file_name) if self.is_inverted: piece_matrix = rotation.rotate_3d_matrix(rotation.z_180, piece_matrix, PIECE_CENTER) return piece_matrix
def ok(self, event=None): x_entry = self.x_entry.get() z_entry = self.z_entry.get() facing_entry = self.facing_entry.get() errors = [] if not x_entry: errors.append("x_entry is empty") else: try: x_entry_float = float(x_entry) except ValueError: errors.append( f"x_entry ({x_entry}) cannot be converted to float") if not z_entry: errors.append("z_entry is empty") else: try: z_entry_float = float(z_entry) except ValueError: errors.append( f"z_entry ({z_entry}) cannot be converted to float") if not facing_entry: errors.append("facing_entry is empty") else: try: facing_entry_float = float(facing_entry) if facing_entry_float > 180 or facing_entry_float < -180: errors.append( f"facing_entry ({facing_entry}) should be between -180 and 180." ) except ValueError: errors.append( f"facing_entry ({facing_entry}) cannot be converted to float" ) if errors: error_message = f"Rejecting throw entry due to errors: {', '.join(errors)}" logger.error(error_message) messagebox.showerror("Invalid entry", error_message) return self.withdraw() self.update_idletasks() self.callback( Throw( point=Point(x_entry_float, z_entry_float), facing=facing_entry_float, )) self.cancel()
def walk_position_indices(position): origin = position.origin dim = position.dimensions z_range = _get_range(origin.Z, dim.Z) y_range = _get_range(origin.Y, dim.Y) x_range = _get_range(origin.X, dim.X) for z in z_range: for y in y_range: for x in x_range: yield Point(z, y, x)
def neighborBlock(node, deltaPoint, map): x = deltaPoint.x y = deltaPoint.y neighborList = [] if (abs(x) + abs(y)) == 2: neighborList = [Point(x, 0), Point(0, y)] for point in neighborList: neighborPoint = node.getPoint() + point neighbor = map.getNode(node.getPoint() + point) if neighbor is None: continue if neighbor.isBlock() is True: return True return False
def main(): print('This program which sum and multiply elliptical curve points') files = glob(os.path.join('tests', '*')) if len(argv) > 1: files = argv[1:] for file_name in files: with open(file_name, 'r', encoding='utf-8') as f: params = f.readlines() params = [x.replace(os.linesep, '').replace('\n', '').replace('\ufeff', '') for x in params] if params[0] == '2S' or params[0] == '2N': p, t, c, poly, idx = 2, params[0][1], int_n(params[4]), int_n(params[5]), 6 else: p, t, c, idx = int_n(params[0]), '-', 0, 4 n = int_n(params[1]) a, b = [int_n(x) for x in params[2:4]] curve = Curve(a=a, b=b, c=c, p=p, n=n, t=t) if p == 2: curve.set_poly(Poly(poly)) answer = [] for s in params[idx:]: args = s.split(' ') op = args[0] base = args[1][:2] if len(args[1]) >= 2 else 10 if op == 'у' or op == 'y': x, y, k = [int_n(x) for x in args[1:]] answer.append(mult(k, Point(x, y), curve).to_string(base) + os.linesep) else: x1, y1, x2, y2 = [int_n(x) for x in args[1:]] answer.append(add(Point(x1, y1), Point(x2, y2), curve).to_string(base) + os.linesep) cur_file_name = os.path.join('tests_answer', os.path.join(*os.path.split(file_name)[1:])) with open(cur_file_name, 'w', encoding='cp866') as f: f.writelines(answer) print(os.linesep + 'Check directory with name: tests_answer' + os.linesep)
def intersect_multiple(throws: List[Throw]) -> Point: denominator = np.zeros((2, 2), dtype=np.float) numerator = np.zeros((2, 1), dtype=np.float) for throw in throws: throw_heading_normal = throw.heading + pi / 2 _cos = cos(throw_heading_normal) _sin = sin(throw_heading_normal) unit_normal = np.array([_cos, _sin]).reshape((2, 1)) denominator += unit_normal @ unit_normal.T numerator += unit_normal @ unit_normal.T @ np.array( [throw.point.x, throw.point.z]).reshape((2, 1)) intersection_array = (np.linalg.inv(denominator) @ numerator).flatten() return Point(intersection_array[0], intersection_array[1])
def find_all_rays(TXx, TXy, RXx, RXy, MURS, COINS, COINS_DIFFRACTION): #revoie tous les rayons RAYS_REFLEXION = rayons_reflexion(Point(TXx, TXy), Point(RXx, RXy), MURS) RAYS_DIRECT = rayon_direct(Point(TXx, TXy), Point(RXx, RXy), MURS) RAYS_DIFFRACTION = diffraction_rays(Point(TXx, TXy), Point(RXx, RXy), MURS, COINS_DIFFRACTION) return [RAYS_DIRECT, RAYS_REFLEXION, RAYS_DIFFRACTION]
def lookAround(node, map): childDelta = [ Point(1, 0), Point(1, -1), Point(0, -1), Point(-1, -1), Point(-1, 0), Point(-1, 1), Point(0, 1), Point(1, 1) ] openList = [] for delta in childDelta: childPoint = node.getPoint() + delta childNode = map.getNode(childPoint) if childNode is None: continue if neighborBlock(node, delta, map) is True: continue if childNode.isBlock(): continue elif childNode.isClose(): continue elif childNode.isEmpty(): childNode.setParent(node) childNode.setOpen() openList.append(childNode) elif childNode.isOpen(): currentCostG = childNode.costG() newCostG = childNode.calcCostG(node) if currentCostG > newCostG: childNode.setParent(node) else: print('error!') return openList
def show(self): text = [] for y in range(self.height): line = [] for x in range(self.width): node = self.getNode(Point(x, self.height - y - 1)) if node.getState() == 'o': line.append(str(node.costG()) + ", ") else: line.append(str(node.getState()) + ", ") line.append('\n') text += line print("".join(text))
def rotate_3d_matrix(rotation_matrix, matrix, center=None): z_len = len(matrix) y_len = len(matrix[0]) x_len = len(matrix[0][0]) result = [[[0 for z in y] for y in z] for z in matrix] for z in range(z_len): for y in range(y_len): for x in range(x_len): mapped_point = apply_point_rotation(rotation_matrix, Point(z, y, x), center) mZ = mapped_point.Z mY = mapped_point.Y mX = mapped_point.X result[mZ][mY][mX] = matrix[z][y][x] return result
def __init__(self, data, width, height, stop): self.map = [] self.width = width self.height = height index = 0 for d in data: x = index % self.width y = height - 1 - (index // self.width) point = Point(x, y) h = (abs(stop.x - point.x) + abs(stop.y - point.y)) * 10 node = Node(point, h) if d == -1: node.setBlock() self.map.append(node) index += 1
from classes.point import Point from classes.direction import Direction from copy import deepcopy # shifted works point = Point(1, 1, 1) point.shift(Direction.right) assert point == Point(2, 1, 1) point = Point(1, 1, 1) point.shift(Direction.left) assert point == Point(0, 1, 1) point = Point(1, 1, 1) point.shift(Direction.up) assert point == Point(1, 2, 1) point = Point(1, 1, 1) point.shift(Direction.down) assert point == Point(1, 0, 1) point = Point(1, 1, 1) point.shift(Direction.away) assert point == Point(1, 1, 2) point = Point(1, 1, 1) point.shift(Direction.toward) assert point == Point(1, 1, 0) # copy works point_a = Point(1, 1, 1)
def x_clockwise(point): return Point(point.Y, -point.Z, point.X)
def x_counterclockwise(point): return Point(-point.Y, point.Z, point.X)
def y_180(point): return Point( -point.Z, point.Y, -point.X, )
def y_clockwise(point): return Point( -point.X, point.Y, point.Z, )
0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] """ """ data = [ 0, -1, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0] """ data = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] width = 8 height = 6 start = Point(2, 3) stop = Point(6, 3) map = Map(data, width, height, stop) node = aStar(start, stop, map) while node: print(node.getPoint()) node = node.getParent()
def z_180(point): return Point( point.Z, -point.Y, -point.X, )
from classes.point import Point from classes.direction import Direction from classes.cube import Cube from copy import deepcopy # Fill works cube = Cube() cube.fillPoint(Point(1, 1, 1)) cube.fillPoint(Point(2, 2, 2)) cube.shift(Direction.right) assert (cube.filled_points == set([Point(2, 1, 1), Point(3, 2, 2)])) # isValid works cube = Cube() assert (cube.isValid()) cube.fillPoint(Point(4, 0, 0)) assert (not cube.isValid()) # pointIsValid works cube = Cube() assert (cube.pointIsValid(Point(0, 0, 0))) assert (not cube.pointIsValid(Point(4, 0, 0))) assert (not cube.pointIsValid(Point(0, 0, -1))) # pointIsFilled works cube = Cube() cube.fillPoint(Point(1, 1, 1)) assert (cube.pointIsFilled(Point(1, 1, 1))) assert (not cube.pointIsFilled(Point(0, 0, 0))) # fillDirection works with first insert
def add_point(self, x, y): self.points.append(Point(x, y))
def drawTriangle(node, point, drawer): if node.getParent() is None: return global RectSize centerX = point.x + (RectSize / 2) centerY = point.y + (RectSize / 2) + 15 crossLength = RectSize * 0.25 angleLength = crossLength * 0.707 lineStart = None lineEnd = None diff = node.getPoint() - node.getParent().getPoint() diffList = { str(Point(1, 0)): [Point(-crossLength, 0), Point(crossLength, 0)], str(Point(-1, 0)): [Point(crossLength, 0), Point(-crossLength, 0)], str(Point(0, 1)): [Point(0, crossLength), Point(0, -crossLength)], str(Point(0, -1)): [Point(0, -crossLength), Point(0, crossLength)], str(Point(1, 1)): [Point(-angleLength, angleLength), Point(angleLength, -angleLength)], str(Point(1, -1)): [Point(-angleLength, -angleLength), Point(angleLength, angleLength)], str(Point(-1, -1)): [Point(angleLength, -angleLength), Point(-angleLength, angleLength)], str(Point(-1, 1)): [Point(angleLength, angleLength), Point(-angleLength, -angleLength)] } findDiff = diffList[str(diff)] if findDiff is None: return lineStart = findDiff[0] + Point(centerX, centerY) lineEnd = findDiff[1] + Point(centerX, centerY) if lineStart is not None and lineEnd is not None: radius = 5 leftUp = (lineStart.x - radius, lineStart.y - radius) rightDown = (lineStart.x + radius, lineStart.y + radius) drawer.line([(lineStart.x, lineStart.y), (lineEnd.x, lineEnd.y)], fill="red", width=4) drawer.ellipse([leftUp, rightDown], fill='red')
def z_clockwise(point): return Point( point.Z, point.X, -point.Y, )
def y_counterclockwise(point): return Point( point.X, point.Y, -point.Z, )