Exemple #1
0
    def save(self, base_path: str, save_to_path: str) -> None:
        from PIL import Image

        points = []

        for i in range(len(self.path) - 1):
            cur = self.path[i].pos
            nxt = self.path[i + 1].pos

            if cur.y == nxt.y:
                # Ys equal - horizontal line
                for x in range(min(cur.x, nxt.x), max(cur.x, nxt.x) + 1):
                    points.append(Point(x, cur.y))
            elif cur.x == nxt.x:
                # Xs equal - vertical line
                for y in range(min(cur.y, nxt.y), max(cur.y, nxt.y) + 1):
                    points.append(Point(cur.x, y))

        length = len(points)

        colors = []
        for i in range(length):
            r = int((i / length) * 240)
            colors.append((r, 0, 240 - r))

        img = Image.open(base_path)
        rgb_img = Image.new("RGBA", img.size)
        rgb_img.paste(img)

        for i, point in enumerate(points):
            rgb_img.putpixel((point.x, point.y), colors[i])

        rgb_img.save(save_to_path)
def readPointsFile(name, type='XY', delimeter="\t"):
    ###############################
    # reading an array of points from a file
    # input:   name     (name of the file with the points)
    #          type     (how the points are defined with: XYZ, ZY, RZ (radius and z-coordinate)
    # output:  pts      (array of points)

    pts =[]
    f = open(name, "r")
    lines = f.readlines()
    for x in lines:
        if type=='XYZ':
            tmp =  Point(x=float(x.split(delimeter)[0]), y=float(x.split(delimeter)[1]), z=float(x.split(delimeter)[2]))
        elif type=='RZ':
            tmp =  Point(rad=float(x.split(delimeter)[0]), z=float(x.split(delimeter)[1]), theta=float(x.split(delimeter)[2]))
        elif type=='RTHETA':
            tmp =  Point(rad=float(x.split(delimeter)[0]), z=float(x.split(delimeter)[2]), theta=float(x.split(delimeter)[1]))
        elif type == 'XY':
            tmp = Point(x=float(x.split(delimeter)[0]), y=float(x.split(delimeter)[1]))
        else:
            print("In readPointsFile, %s is an invalid type... (XYZ, RZ, XY) Exiting... " % (type))
            sys.exit()
        # pts= np.append(pts, tmp)
        pts.append(tmp)
    f.close()

    return pts
Exemple #3
0
def test_one_station_same_location():
    device = Device(Point(0, 0))
    station = Station(Point(0, 0), 10)
    stations = [station]
    best_station, power = device.best_station(stations)
    assert best_station == station
    assert power == 100
    def test_secp256r1():
        curve_secp256r1 = CurveFactory.get_curve_by_name('secp256r1')

        point1 = Point(
            0xfff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a1460297556,
            0xae12777aacfbb620f3be96017f45c560de80f0f6518fe4a03c870c36b075f297,
            curve_secp256r1)

        point2 = Point(
            0x2f01e5e15cca351daff3843fb70f3c2f0a1bdd05e5af888a67784ef3e10a2a01,
            0x5c4da8a741539949293d082a132d13b4c2e213d6ba5b7617b5da2cb76cbde904,
            curve_secp256r1)

        # results are obtained from http://extranet.cryptomathic.com/elliptic/index
        addition_result = Point(
            0x499fdf9e895e719cfd64e67f07d38e3226aa7b63678949e6e49b241a60e823e4,
            0xcac2f6c4b54e855190f044e4a7b3d464464279c27a3f95bcc65f40d403a13f5b,
            curve_secp256r1)

        doubling_result = Point(
            0xd01115d548e7561b15c38f004d734633687cf4419620095bc5b0f47070afe85a,
            0xa9f34ffdc815e0d7a8b64537e17bd81579238c5dd9a86d526b051b13f4062327,
            curve_secp256r1)

        multiplication_result = Point(
            0x68809a32574292480e99bd0527e7b31a55d184759f90e05dd8c2413de25eefeb,
            0x12125af69bf7814f4040634090331e9c7a894139e67ad9a739bd429a1a667b,
            curve_secp256r1)

        CurveTests.test_doubling(point1, doubling_result)
        CurveTests.test_addition(point1, point2, addition_result)

        n = 0xaa93b72f52fa105d1bb0bdfb1f349f6c9e6f067fdb557bfe4175815bd68c68b9
        CurveTests.test_multiplication(n, point1, multiplication_result)
def createCurve(pt, n, ang=-20, HD = None):
    ###############################
    # circular curve consisting of n points
    # input:   pt (starting point: x,y,z)
    #          n  (numb of points in the curve)
    #          ang(angle in degrees till the curve goes)
    #          HD (height distribution
    # output:  x  (x array of the points)
    #          y  (y array of the points)
    #          z  (z array of the points)
    # description: the curve start in pt and then
    # it is rotated by "angle" degrees.

    x   = np.zeros(n)
    y   = np.zeros(n)
    z   = np.zeros(n)
    for i in range(n):
        tmp = Point(x=pt.X, y=pt.Y, z=pt.Z)
        tmp.rotZ(i*ang/n)
        x[i] = tmp.X
        y[i] = tmp.Y
        z[i] = tmp.Z
        if HD:
            z[i] = getHeight(tmp, HD)

    return x, y, z
Exemple #6
0
    def __init__(self, x, y) -> None:
        self.pos = Point(x, y)

        self.global_goal = float("inf")
        self.local_goal = float("inf")

        self.neighbours = []
        self.parent = None
Exemple #7
0
def test_two_stations_one_with_same_location():
    device = Device(Point(0, 0))
    station1 = Station(Point(10, 10), 10)
    station2 = Station(Point(0, 0), 10)
    stations = [station1, station2]
    best_station, power = device.best_station(stations)
    assert best_station == station2
    assert power == 100
Exemple #8
0
def test_two_stations_out_of_reach():
    device = Device(Point(20, 20))
    station1 = Station(Point(0, 0), 10)
    station2 = Station(Point(10, 10), 10)
    stations = [station1, station2]
    best_station, power = device.best_station(stations)
    assert best_station == None
    assert power == 0
Exemple #9
0
 def __contains__(self, point):
     """
     :type point: Point
     """
     o1 = Point.test_orientation(self.a, self.b, point)
     o2 = Point.test_orientation(self.b, self.c, point)
     o3 = Point.test_orientation(self.c, self.a, point)
     return o1 == 0 or o2 == 0 or o3 == 0 or o1 == o2 == o3
Exemple #10
0
def mouse_handler_line(event, x, y, flags, data):
    matrix = data['matrix']
    img = data['img'].copy()

    world_coords = Point([x, y]).to_world(matrix)
    x = world_coords.x

    p1 = Point([x, 0]).to_pixel(matrix)
    p2 = Point([x, 68]).to_pixel(matrix)

    cv2.line(img, (p1.x, p1.y), (p2.x, p2.y), (50, 50, 220), 2)
    cv2.imshow("Image", img)
Exemple #11
0
    def test_start_initial_point(self):
        axe_x = 0
        axe_y = 0
        facing = 'N'
        pattern = '.*{}.*{}.*{}'.format(axe_x,axe_y,facing)

        end_point = Point()

        point = Point()
        rover = Rover(Point(),facing)

        result = re.match(str(pattern),str(rover))
        self.assertTrue(result)  
Exemple #12
0
def main():
    w = 100
    h = 100

    maze = Maze(w, h)
    maze.generate(Point.random(w, h))
    # maze.print()
    maze.save('Maze.png')

    a_star = AStar('Maze.png')
    path = a_star.solve(Point(1, 1), Point(w * 2 - 1, h * 2 - 1))

    # path.print()
    path.save('Maze.png', 'MazePath.png')
Exemple #13
0
 def compute_means(self, clusters):
     means = []
     for cluster in clusters.values():
         mean_point = Point(0.0, 0.0)
         cnt = 0.0
         for point in cluster:
             #print "compute: point(%f,%f)" % (point.latit, point.longit)
             mean_point.latit += point.latit
             mean_point.longit += point.longit
             cnt += 1.0
         mean_point.latit = mean_point.latit / cnt
         mean_point.longit = mean_point.longit / cnt
         means.append(mean_point)
     return means
def getLineDistance(IN, pt1, pt2, n):
    ###############################
    #  calculating the distance for the area calculation
    # input:   IN       (input file)
    #          pt1  (Starting point of the line: x,y,z)
    #          pt2  (Ending point of the line: x,y,z)
    # output:  area     (arc lenght, not actually an area)
    # observations: this function was made specially for the rotor channel were the arc is not complete due to the blades!

    radRotorLE =  float(IN['radLERotor'])
    radRotorTE =  float(IN['radTERotor'])

    radius= (pt1.rad+pt2.rad)*0.5

    if (radius > radRotorTE) and (radius < radRotorLE):
        # This only applies for the rotor channel because the height changes in a line
        hd = readPointsFile(IN['fileHD'], 'RZ')

        pt   = pt2 - pt1
        vec  = np.array([float(pt.X), float(pt.Y), float(pt.Z)]) / n
        magn = pt.magnitude()
        area = np.zeros(n)
        for i in range(n):
            tmp     = Point(x=float(pt1.X) + (i * vec[0]), y=float(pt1.Y) + (i * vec[1]), z=float(pt1.Y) + (i * vec[2]))
            area[i] = getHeight(tmp, hd) * magn/n
    else:

        area= pt1.distance2D(pt2)/ n

    return area
Exemple #15
0
def main():
    points_df = pd.read_csv(args.data)
    points = [
        Point(p[1]['Latitude'], p[1]['Longitude'], p[1]['Regression'],
              p[1]['City']) for p in points_df.iterrows()
    ]

    delaunay_diagram = DelaunayDiagram(points=points)
    starting_point = initiate(points, args.seed, args.minimal_regression)
    points_set = PointsSet(delaunay_diagram=delaunay_diagram,
                           initial_point=starting_point,
                           minimal_point_density=float(args.minimal_density),
                           minimal_regression=float(args.minimal_regression))
    simulated_annealing = SimulatedAnnealing(
        points_set=points_set,
        temperature=float(args.temperature),
        max_iterations=int(args.max_iterations),
        seed=int(args.seed))
    result, best = simulated_annealing.calculate()
    simulated_annealing.save_history()

    print()
    print("Final result ({}) points:".format(len(result.points)))
    print(*result.points, sep=",\n")
    print()
    print("Best result ({}) points:".format(len(best)))
    print(*best, sep=",\n")
 def __init__(self, size, p, a, b, gx, gy, order):
     self.size = size
     self.p = p
     self.a = a
     self.b = b
     self.generator = Point(gx, gy, self)
     self.order = order
Exemple #17
0
    def __init__(self,
                 capacity=60,
                 consumption=0.6,
                 location=Point(0, 0),
                 model='Mercedes'):
        """
        The initializer.

        :param capacity: Capacity of fuel tank of car. By default: 60.
        :type capacity: Any string or numerical type that can be converted to float
        :param consumption: Consumption of fuel by car: liter/km. By default: 0.6.
        :type consumption: Any string or numerical type that can be converted to float
        :param location: Initial location of car
        :type location: Point
        :param model: Name of car
        :type model: str
        :raise ValueError: If capacity or fuel consumption can't be converted to float
        :raise TypeError: If location is not of Point type
        :raise TypeError: If model is not of str type

        :fuel amount: Initial fuel amount is float 0.0
        """

        self._fuel_capacity = fabs(self._validate_float(capacity))
        self._fuel_consumption = fabs(self._validate_float(consumption))
        self._location = self._validate_point(location)
        self._model = self._validate_string(model)
        self._fuel_amount = float(0.0)
    def add_points(self, p1, p2):
        assert isinstance(p1, Point) and isinstance(p2, Point)

        slope = self.calculate_differentiation(p1, p2)
        x = (slope * slope - p1.x - p2.x) % self.p
        y = (slope * (p1.x - x) - p1.y) % self.p
        return Point(x, y, self)
def createLine(pt1, pt2, n,  HD = None):
    ###############################
    # line consisting of n points
    # input:   pt1  (Starting point of the line: x,y,z)
    #          pt2  (Ending point of the line: x,y,z)
    #          n    (numb of points in the curve)
    # output:  x    (x array of the points)
    #          y    (y array of the points)
    #          z  (z array of the points)
    # observations: this function can only be used for the stator due to the height distribution!!

    pt  = pt2 - pt1
    vec = np.array([float(pt.X), float(pt.Y)])/n
    x   = np.zeros(n)
    y   = np.zeros(n)
    z   = np.zeros(n)
    for i in range(n):
        tmp = Point(x=float(pt1.X) + (i*vec[0]), y=float(pt1.Y) + (i*vec[1]), z=pt1.Z)
        x[i] = tmp.X
        y[i] = tmp.Y
        z[i] = tmp.Z
        if HD:
            z[i] = getHeight(tmp, HD)

    return x, y, z
Exemple #20
0
def ecc_generate():
    if request.method == 'GET':
        return render_template('ecc/generate/index.html')

    coef = int(request.form['x-coef'])
    const = int(request.form['const'])
    modulo = int(request.form['modulo'])
    if not is_prime(modulo):
        return "Error: Modulo must be prime"
    curve = EllipticCurve(coef, const, modulo)

    base_x = int(request.form['bpoint-x'])
    base_y = int(request.form['bpoint-y'])
    bpoint = Point(base_x, base_y, modulo)
    if not curve.contains(bpoint):
        return "Error: The base point is not a point in the curve"

    private_key = randrange(1, MAX_KEY)
    public_key = curve.multiply(private_key, bpoint)

    filename = request.form['filename']
    public_file = FileStorage(stream=BytesIO(public_key.print().encode()),
                              filename=filename + '.pub')
    public_file.save('static/' + public_file.filename)
    private_file = FileStorage(stream=BytesIO(str(private_key).encode()),
                               filename=filename + '.pri')
    private_file.save('static/' + private_file.filename)
    return render_template('ecc/generate/result.html')
Exemple #21
0
def locate_point_in_triangulation(points, target):
    """
    :param: points: List of points. The first 3 points must form a triangle
    (must not be collinear) and all the other points must be inside that
    triangle. If either of these is not true, the function returns 1 (failure).
    :type: points list of (float, float)
    :param: target: Point to be located within the triangulation of `points`.
    :type: target (float, float)
    :return: 0 on success, 1 on failure
    :rtype: int
    """

    points = [Point(p[0], p[1]) for p in points]
    target = Point(target[0], target[1])

    if len(points) < 3:
        return 1  # Invalid number of points.

    if Point.are_collinear(*points[:3]):
        return 1  # The first 3 points must form a triangle.

    base = Triangle(*points[:3])

    for point in points[3:]:
        if point not in base:
            # All subsequent points must be inside the triangle
            # formed by the first 3.
            return 1

    # The input is valid. Running the triangulation algorithm
    triangles = triangulate(base, points[3:])

    # Draw the triangulation and locate the target on the graphic:
    start_draw()
    shaded = False
    for triangle in triangles:
        if target in triangle and not shaded:
            draw_triangle_shade(triangle)
            shaded = True
    for triangle in triangles:
        draw_triangle(triangle)
    print(target.x, target.y)
    draw_point(target)
    end_draw()

    return 0
Exemple #22
0
    def test_has_error_in_starting_point(self):
        axe_x = None
        axe_y = 'E'
        start_position = [axe_x, axe_y]

        init_point = lambda: Point([axe_x, axe_y])

        self.assertRaises(Exception, init_point)
def readPointCart(IN, name):
    ###############################
    # reading a single point from the input file
    # input:   IN   (input file)
    #          name (name of the point)
    # output:  point

    x0, y0, z0 = IN[name].split(",")
    return Point(x=float(x0), y=float(y0), z=float(z0))
Exemple #24
0
    def generate(self, start: Point) -> None:
        import random

        stack = [start]
        self[start.x, start.y] = Maze.VISITED

        def offset(ox, oy) -> tuple:
            return stack[-1].x + ox, stack[-1].y + oy

        while len(stack) > 0:
            neighbours = []

            if stack[-1].y > 0 and self[offset(0, -1)] & Maze.VISITED == 0:
                neighbours.append(0)
            if stack[-1].x < self.w - 1 and self[offset(
                    1, 0)] & Maze.VISITED == 0:
                neighbours.append(1)
            if stack[-1].y < self.h - 1 and self[offset(
                    0, 1)] & Maze.VISITED == 0:
                neighbours.append(2)
            if stack[-1].x > 0 and self[offset(-1, 0)] & Maze.VISITED == 0:
                neighbours.append(3)

            if len(neighbours) == 0:
                stack.pop()
            else:
                next_dir = random.choice(neighbours)

                if next_dir == 0:
                    self[offset(0, -1)] |= Maze.VISITED | Maze.PATH_S
                    self[offset(0, 0)] |= Maze.PATH_N
                    stack.append(Point(stack[-1].x + 0, stack[-1].y - 1))
                elif next_dir == 1:
                    self[offset(+1, 0)] |= Maze.VISITED | Maze.PATH_W
                    self[offset(0, 0)] |= Maze.PATH_E
                    stack.append(Point(stack[-1].x + 1, stack[-1].y + 0))
                elif next_dir == 2:
                    self[offset(0, +1)] |= Maze.VISITED | Maze.PATH_N
                    self[offset(0, 0)] |= Maze.PATH_S
                    stack.append(Point(stack[-1].x + 0, stack[-1].y + 1))
                elif next_dir == 3:
                    self[offset(-1, 0)] |= Maze.VISITED | Maze.PATH_E
                    self[offset(0, 0)] |= Maze.PATH_W
                    stack.append(Point(stack[-1].x - 1, stack[-1].y + 0))
Exemple #25
0
    def test_class_str(self):
        axe_x = 0
        axe_y = 0
        start_position = [axe_x, axe_y]
        pattern = '.*{}.*{}'.format(axe_x, axe_y)

        STRpoint = Point()

        result = re.match(str(pattern), str(STRpoint))
        self.assertTrue(result)
Exemple #26
0
 def __init__(self, map_location, virtualmap_location):
     with open(map_location, "r") as f:
         data = json.load(f)
     with open(virtualmap_location, "r") as vir:
         vir_data = json.load(vir)
     self.map_length_ = data["Length_of_map"]
     self.endpoint_ = data["end_point"]
     self.themap_ = []
     self.walls_ = vir_data["walls"]
     for row in range(self.map_length_):
         self.themap_.append([])
         for col in range(self.map_length_):
             n = Point([row, col], self.endpoint_)
             if row == 0:
                 n.walls_[2] = True
             if col == 0:
                 n.walls_[3] = True
             if row == self.map_length_ - 1:
                 n.walls_[0] = True
             if col == self.map_length_ - 1:
                 n.walls_[1] = True
             self.themap_[row].append(n)
     for wall in self.walls_:
         self.themap_[wall[0]][wall[1]].walls_[wall[2]] = True
         wall[0] += look_walls[wall[2]][0]
         wall[1] += look_walls[wall[2]][1]
         wall[2] = look_walls[wall[2]][2]
         if self.withinRange([wall[0], wall[1]]):
             self.themap_[wall[0]][wall[1]].walls_[wall[2]] = True
     #print("* * *\n*   *\n* * *")
     self.print()
Exemple #27
0
def triangulate(exterior, interior):
    """
    :type exterior: Triangle
    :param interior: a List of points inside the `exterior` triangle.
    :type interior: list of Point
    :return: List of triangles representing a valid triangulation
             of the given points.
    :rtype: list of Triangle
    """
    origin, b, c = exterior.a, exterior.b, exterior.c

    triangles_containing_origin = []
    ordered_points = sorted(
        interior + [b, c], key=lambda p: atan2(p.y - origin.y, p.x - origin.x))
    # Rotate the array of points if the exterior points b and c do not "flank"
    # all the other points
    if (b, c) != (ordered_points[0], ordered_points[-1]) and \
            (c, b) != (ordered_points[0], ordered_points[-1]):
        for i in range(1, len(ordered_points)):
            if (b, c) == (ordered_points[i - 1], ordered_points[i]) or \
                    (c, b) == (ordered_points[i - 1], ordered_points[i]):
                ordered_points = ordered_points[i:] + ordered_points[:i]
                break
    for i in range(1, len(ordered_points)):
        triangles_containing_origin.append(
            Triangle(ordered_points[i - 1], ordered_points[i], origin))

    ear_clipped_triangles = []
    print(ordered_points[::-1])
    polygon = ordered_points[::-1]

    while len(polygon) != 3:
        for index in range(len(polygon)):
            predecessor = polygon[(index - 1) % len(polygon)]
            current = polygon[index]
            successor = polygon[(index + 1) % len(polygon)]
            if Point.test_orientation(predecessor, current, successor) == 1:
                t = Triangle(predecessor, current, successor)
                contains_points = False
                for p in polygon:
                    if p in t and p not in (predecessor, current, successor):
                        contains_points = True
                        break
                if not contains_points:
                    ear_clipped_triangles.append(t)
                    polygon = polygon[:index] + polygon[index + 1:]
                    break
    ear_clipped_triangles.append(Triangle(*polygon))

    return triangles_containing_origin + ear_clipped_triangles
Exemple #28
0
def invite(customers):
    """Return an array

    This function filters out customers that are farther than 100 km from the Dublin office
    """

    # Init variable to store invites
    invitees = []

    for customer in customers: # For each customer
        customer_location = Point(float(customer['latitude']), float(customer['longitude']))
        customer_distance_to_office = distance(customer_location, DUBLIN_OFFICE_LOCATION) # Calc distance to Dublin office
        if customer_distance_to_office <= 100.0: # If within 100 km invite customer to Dublin office
            invitees.append(customer)

    return invitees
Exemple #29
0
def main(dataset_fn, output_fn, clusters_no):
    geo_locs = []
    # read location data from csv file and store each location as a Point(latit,longit) object
    df = pd.read_csv(dataset_fn)
    for index, row in df.iterrows():
        loc_ = Point(float(row['LAT']),
                     float(row['LON']))  #tuples for location
        geo_locs.append(loc_)
    # run k_means clustering
    model = KMeans(geo_locs, clusters_no)
    flag = model.fit(True)
    if flag == -1:
        print("No of points are less than cluster number!")
    else:
        # save clustering results is a list of lists where each list represents one cluster
        model.save(output_fn)
Exemple #30
0
def mouse_handler_player(event, x, y, flags, data):
    matrix = data['matrix']
    img = data['img'].copy()

    p1 = Point([x, y]).to_world(matrix)
    p2 = Point([p1.x, p1.y, 1.8])

    p1 = p1.to_pixel(matrix)
    p2 = p2.to_pixel(matrix)

    cv2.line(img, (p1.x, p1.y), (p2.x, p2.y), (50, 50, 220), 2)
    cv2.imshow("Image", img)