Пример #1
0
    def predict(self, x):
        """Predict x array

        :param x: data with coordinates to be predicted
            :type: list, tuple, np.array
            :example:
                [[1, 2], [2, 3], [3, 4], [4, 5]]
        :return: x predicts
            :type: list
            :example:
                [[1], [0], [0], [1]]
        """

        predicts = []
        for coordinates in x:
            predict_point = Point(coordinates)

            # euclidean distance from predict_point to all in self._fit_data
            distances = []
            for data_point, data_label in self._fit_data:
                distances.append((predict_point.distance(data_point), data_label))

            # k points with less distances
            distances = sorted(distances, key=itemgetter(0))[:self.k]
            # label of k points with less distances
            predicts.append(list(max(distances, key=itemgetter(1))[1]))

        return predicts
Пример #2
0
    def getLineIntersection(self, line):
        #https://math.stackexchange.com/questions/228841/how-do-i-calculate-the-intersections-of-a-straight-line-and-a-circle
        #Line: y = mx + c
        #Circle: (x-p)**2 + (y-q)**2 = r**2

        m = line.getSlope()
        c = line.getYIntercept()
        p = self.pos.x
        q = self.pos.y
        r = self.radius

        A = (m**2 + 1)
        B = 2 * ((m * c) - (m * q) - p)
        C = (q**2 - r**2 + p**2 - 2 * c * q + c**2)

        i = B**2 - (4 * A * C)
        if i < 0:  #For some reason if i is less than 0, there are no points.
            return None
        elif i == 0:  #If i is 0 apparently there is point (the line is tangent)
            x1 = (-B + sqrt(B**2 - 4 * A * C)) / (2 * A)
            y1 = (m * x1) + c
        elif i > 0:  #If i is greater than 0, there are two points of intersection
            x1 = (-B + (+sqrt(B**2 - 4 * A * C))) / (2 * A)
            y1 = (m * x1) + c

            x2 = (-B + (-sqrt(B**2 - 4 * A * C))) / (2 * A)
            y2 = ((m * x2) + c)
            return [
                Point(int(x1), int(y1), self.parent),
                Point(int(x2), int(y2), self.parent)
            ]
Пример #3
0
    def getLineSegment(self, bounds):
        x1 = self.getX(-bounds)
        y1 = self.getY(x1)

        x2 = self.getX(bounds)
        y2 = self.getY(x2)
        return LineSegment(Point(x1, y1), Point(y1, y2), self.parent)
Пример #4
0
    def pairwise_distances(points, centroids):
        """Create pairwise distance between points and the centroids

        :param points:
            :type: list, tuple, np.array
            :example:
                [[1, 2], [2, 3], [3, 4], [4, 5]]
        :param centroids:
            :type: list, tuple, np.array
            :example:
                [[0, 0], [3, 3]]
        :return: distance
            :type: list
            :example:
                [[14.866068747318506, 1.0, 0.0],
                 [14.212670403551895, 1.4142135623730951, 1.0],
                 [14.142135623730951, 0.0, 1.0], ... ]
        """

        distances = list()
        for index, point in enumerate(points):
            distances.append([])
            point = Point(point)
            for centroid in centroids:
                centroid = Point(centroid)
                distance = centroid.distance(point)
                distances[index].append(distance)
        return distances
Пример #5
0
 def test_init(self):
     start = Point(2, 2)
     end = Point(8, 4)
     ray = Ray(start, end)
     # Checking
     self.assertEqual(ray.start, start)
     self.assertEqual(ray.end, end)
Пример #6
0
    def test_corner_shell(self):
        test_cases = {
            Rectangle(Field(0, 0), Field(5, 5)):
            Rectangle(Point(-0.5, -0.5), Point(5.5, 5.5)),
            Rectangle(Field(2, 2), Field(4, 4)):
            Rectangle(Point(1.5, 1.5), Point(4.5, 4.5))
        }

        for case, expected in test_cases.items():
            self.assertEqual(case.corner_shell(), expected)
Пример #7
0
    def startInteractiveShell(self):
        vars = globals()
        ai = self.ai

        self.rect1 = Rect(Point(0, 0), Point(100, 100))
        self.rect2 = Rect(Point(50, 50), Point(150, 150))
        rect1 = self.rect1
        rect2 = self.rect2

        vars.update(locals())
        shell = InteractiveConsole(vars)
        shell.interact()
Пример #8
0
    def test_conversion2(self):
        r = Rectangle(Field(1, 1), Field(5, 5))
        results = {
            "(1,1)": (0.5, 0.5),
            "(1,5)": (0.5, 5.5),
            "(5,1)": (5.5, 0.5),
            "(5,5)": (5.5, 5.5)
        }

        for c in r.corners():
            r = results[c.__str__()]
            self.assertEqual(Point(r[0], r[1]), Point.corner_to_point(c))
Пример #9
0
 def _visibility_map_for_point(source, area):
     visible = np.zeros((area.main.width(), area.main.height()), dtype=bool)
     for x in range(area.main.width()):
         for y in range(area.main.height()):
             visible[x, y] = True if Ray(source, Point(x, y),
                                         area=area).valid() else False
     return visible
Пример #10
0
    def calculate(self):
        logging.debug("calculate")
        # calculate path of star given center / reference and star origin and path
        path = points.path(self.reference, self.star, self.star.line,
                           self.width, self.height)
        logging.debug("calculated path=%d" % len(path))

        for index, entry in enumerate(path):
            data = self.calculate_for(index, entry.x, entry.y)
            self.data.append(data)

        if self.is_raw:
            # DEBUG: Draw the reference in green
            for point in points.neighbors(self.reference, self.width,
                                          self.height):
                self.raw_data[point.y][point.x] = [0, 255, 0]

            # DEBUG: Draw the star in red
            for index, entry in enumerate(path):
                origin = Point(entry.x, entry.y, self.star.line.width)
                for point in points.neighbors(origin, self.width, self.height):
                    self.raw_data[point.y][point.x] = [255, 0, 0]

            # DEBUG: Draw the path in yellow
            for index, entry in enumerate(path):
                self.raw_data[entry.y][entry.x] = [255, 255, 0]

            # DEBUG: Draw the start in blue
            for point in points.neighbors(self.star, self.width, self.height):
                self.raw_data[point.y][point.x] = [0, 0, 255]

            self.raw_image.close()
Пример #11
0
 def aligned_faces(self, color: Color, position: Point, direction: Direction, face: Direction):
     result = 0
     current_position = copy(position)
     while current_position in self.cases and self.cases[current_position].color == color \
             and self.cases[current_position].is_side_free(face):
         result += 1
         current_position += Point.direction(direction)
     return result
Пример #12
0
def getPointFromTwoLines(l1, l2):
    line1 = l1
    line2 = l2

    p = line1.intersection(line2)

    intersection = Point(p.x, p.y)

    return intersection
Пример #13
0
 def test_angle(self):
     origin = Point(5, 5)
     test_cases = {
         Point(10, 5): 0,
         Point(5, 10): np.pi/2,
         Point(0, 5): np.pi,
         Point(5, 0): -np.pi*1/2,
         Point(10, 10): np.pi*1/4,
         Point(0, 10): np.pi*3/4,
         Point(0, 0): np.pi*5/4,
         Point(10, 0): -np.pi*1/4,
     }
     for value, result in test_cases.items():
         value.set_origin(origin)
         self.assertAlmostEqual(value.angle, result, 8)
Пример #14
0
    def test_simple(self):
        a = self.gen_area()

        v = ViewGenerator(a)
        v.shine_from(Point(4, 4))

        # Just for printing
        printer = TextPrinter(a)
        printer.set_view(v.lm)
        printer.to_file("view.txt")
Пример #15
0
 def play(self, color: Color, position: Point):
     if position in self.cases:
         return Exception('position is already taken')
     fresh_cube = Cube(color, position)
     self.cases[position] = fresh_cube
     surrounding_position = position.surrounding()
     for key, value in surrounding_position.items():
         if key in self.cases:
             fresh_cube.occupied_side(value)
             self.cases[key].occupied_side(value.get_inverse())
     return self.win(color, position)
Пример #16
0
 def build_shadow_map(area):
     map = {}
     for x in range(area.main.width()):
         for y in range(area.main.height()):
             # We might have found ourself inside a rectangle
             if not area.rectangle_of(x, y):
                 map[(x, y)] = LightMap._visibility_map_for_point(
                     Point(x, y), area)
             else:
                 map[(x, y)] = np.zeros(
                     (area.main.width(), area.main.height()), dtype=bool)
     return map
Пример #17
0
 def __initialize_points(self):
     print("Initializing points...")
     positions, labels = make_blobs(n_samples=self.__number_points, centers=self.__number_clusters,
                                    center_box=(self.__min_range, self.__max_range),
                                    n_features=self.__number_dimensions, random_state=0)
     print("Positions: ")
     print(positions)
     print("Labels: ")
     print(labels)
     for position in positions:
         point = Point(position)
         self.__points.append(point)
Пример #18
0
    def test_collides(self):
        ray = Ray(Point(2, 2), Point(20, 20))
        test_cases = {
            Rectangle(Field(0, 5), Field(3, 5)): False,
            Rectangle(Field(0, 5), Field(2, 6)): False,
            Rectangle(Field(0, 2), Field(2, 3)): True,
            Rectangle(Field(0, 3), Field(3, 4)): True,
            Rectangle(Field(0, 3), Field(2, 3)): False,
            Rectangle(Field(2, 0), Field(3, 2)): True,
            Rectangle(Field(5, 0), Field(8, 5)): True,
            Rectangle(Field(0, 0), Field(24, 24)): True,
            Rectangle(Field(8, 8), Field(24, 24)): True,
            Rectangle(Field(22, 22), Field(24, 24)): False,
            Rectangle(Field(0, 5), Field(6, 5)): True,
            Rectangle(Field(0, 0), Field(4, 4)): True,
            Rectangle(Field(3, 3), Field(4, 4)): True,
            Rectangle(Field(3, 3), Field(5, 5)): True,
            Rectangle(Field(0, 6), Field(8, 8)): True
        }

        for rectangle, result in test_cases.items():
            self.assertEqual(ray.collides(rectangle), result)
Пример #19
0
def click_brightness_curve(file, center, star):
    """Simple program that prints the input variables"""
    click.echo(file.name)
    file_data = open(file.name, "rb").read()

    click.echo('(x: %d, y: %d) - radius: %d' % center)
    click.echo('(x: %d, y: %d) - length: %d, width: %d' % star)

    center_model = Point(center[0], center[1], center[2])
    star_model = Star(star[0], star[1], star[2], star[3])

    brightness_curve = BrightnessCurve(io.BytesIO(file_data), True,
                                       center_model, star_model)
    brightness_curve.calculate()
    click.echo(brightness_curve.json())
Пример #20
0
    def fit(self, x, y):
        """Train knn model with x data

        :param x: data with coordinates
            :type: list, tuple, np.array
            :example:
                [[1, 2], [2, 3], [3, 4], [4, 5]]
        :param y: labels to x data set
            :type: list, tuple, np.array
            :example:
                [[1], [0], [0], [1]]
        :return: None
        """

        assert len(x) == len(y)
        # [(Point(1, 2), [0]), (Point(0, -1), [0]), (Point(5, 5), [1])]
        self._fit_data = [(Point(coordinates), label) for coordinates, label in zip(x, y)]
Пример #21
0
    def calculate_for(self, index, x, y):
        """
        Calculate the values for the point
        """
        origin = Point(x, y, self.star.line.width)
        neighbors = []
        for point in points.neighbors(origin, self.width, self.height):
            value = self.raw_data[point.y][point.x]
            if isinstance(value, numpy.ndarray):
                neighbors.append(mean(value))
            else:
                neighbors.append(value)

        min_value = min(neighbors)
        max_value = max(neighbors)
        average_value = mean(neighbors)
        median_value = median(neighbors)

        return Data(index, float(average_value), float(median_value),
                    float(min_value), float(max_value), origin)
Пример #22
0
    async def __main(self):
        while self.running:
            async with aiohttp.ClientSession() as session:
                try:
                    # Осуществляем запрос и получаем результат
                    data_package = await self.__fetch(session,
                                                      MAIN_DATA_SOURCE)
                    points = list()
                    if await PackageDataValidator.validate(data_package):
                        # Обрезаем ненужный мусор
                        data_package = data_package[5:-3]

                        # Производим преобразование пакета из строки в соответствующие типы
                        data = ast.literal_eval(data_package)

                        rates = data['Rates']
                        cur_time = datetime.now()

                        for rate in rates:
                            # Извлекаем тип валюты
                            symbol = rate['Symbol']

                            if symbol in IDS.keys():
                                point = Point(
                                    id=IDS[symbol],
                                    timestamp=int(cur_time.timestamp()),
                                    value=round((float(rate["Bid"]) +
                                                 float(rate["Ask"])) / 2, 4))
                                # Добавляем значение в базу
                                await PointDao.insert(point)
                                points.append(point)
                                # print(point.__dict__)
                    PointsHelper().set(points)
                except Exception as ex:
                    print('LoaderService.__main Exception:{}'.format(ex))
                # Выжидаем секунду
                await asyncio.sleep(1)
Пример #23
0
def neighbors(point: Point, max_width, max_height):
    """
    Calculate all neighboring points of the given point within the points radius
    """
    points = []

    min_x = max(0, point.x - point.radius)
    max_x = min(point.x + point.radius + 1, max_width)

    min_y = max(0, point.y - point.radius)
    max_y = min(point.y + point.radius + 1, max_height)

    radius = point.radius

    # check all points in the square
    for x in range(min_x, max_x):
        for y in range(min_y, max_y):
            x_axis = x - point.x
            y_axis = y - point.y
            # check if the point is inside the circle
            if (x_axis * x_axis) + (y_axis * y_axis) <= (radius * radius):
                points.append(Point(x, y))

    return points
Пример #24
0
def path(center: Point, start: Point, line: Line, max_width: int,
         max_height: int):
    """
    Calculate the path from start with distance of line on the arc from center
    """
    x = float(start.x - center.x)
    y = float(start.y - center.y)

    radius = math.sqrt(math.pow(x, 2) + math.pow(y, 2)) + 1

    start_angle = math.acos(x / radius)
    arc = float(line.length) / radius
    if y <= 0:
        start_angle *= -1
    end_angle = start_angle - arc

    result = []
    # minimum step for start to end angle
    step = min_step(max_width, max_height)
    # calculate X and Y for each angle between start and end angle
    for angle in numpy.arange(min(start_angle, end_angle),
                              max(start_angle, end_angle), step):
        x = float(center.x) + radius * math.cos(angle)
        y = float(center.y) + radius * math.sin(angle)

        # check if point is inside the canvas
        if 0 <= x < max_width and 0 <= y < max_height:
            point = Point(int(x), int(y))

            # add the point to the list if not already present
            if not any(p.x == point.x and p.y == point.y for p in result):
                result.append(point)

    # list is in clockwise but we assume counter-clockwise so we reverse it
    result.reverse()
    return result
Пример #25
0
 def corner_shell(self):
     start = Point.map_to_point(self.bottom_left)
     end = Point.map_to_point(self.top_right)
     return Rectangle(start, end)
Пример #26
0
 def test_conversion(self):
     f = Field(5, 5)
     p = Point.field_to_point(f)
     self.assertEqual(p, Point(5, 5))
Пример #27
0
 def test_init(self):
     p = Point(3.0, 5.0)
     self.assertAlmostEqual(3.0, p.x, 6)
     self.assertAlmostEqual(5.0, p.y, 6)
Пример #28
0
    def test_valid(self):
        a = Area(Rectangle(Field(0, 0), Field(15, 15)), 1)
        rectangles = [
            Rectangle(Field(2, 2), Field(3, 3)),
            Rectangle(Field(2, 5), Field(3, 6)),
            Rectangle(Field(5, 2), Field(6, 3)),
            Rectangle(Field(5, 5), Field(6, 6))
        ]
        a += rectangles

        origin = Point(4, 4)

        test_cases = {
            Point(0, 0): False,
            Point(7, 0): False,
            Point(0, 7): False,
            Point(7, 7): False,
            Point(2, 2): False,
            Point(2, 6): False,
            Point(5, 6): False,
            Point(2, 9): False,
            Point(6, 10): False,
            Point(0, 4): True,
            Point(4, 0): True,
            Point(7, 4): True,
            Point(4, 7): True,
            Point(4, 4): True,
            Point(1, 4): True,
            Point(2, 4): True,
            Point(3, 4): True,
            Point(4, 7): True,
            Point(3, 9): True,
            Point(3, 10): True,
            Point(4, 10): True,
            Point(5, 10): True,
            Point(5, 2): False,
        }

        for target, expected in test_cases.items():
            ray = Ray(origin, target, area=a)
            self.assertEqual(ray.valid(), expected)
Пример #29
0
 def getIntersection(self, line):
     x = (self.intercept()-line.intercept())/(line.slope-self.slope)
     y = self.getSlope()*x + self.getYIntercept()
     return Point(x, y, self.parent)
Пример #30
0
 def begin(self, color):
     point = Point(0, 0, 0)
     self.cases[point] = Cube(color, point)