Example #1
0
 def test_point_rotate(self):
     # Rotate point about origin
     p = Point(1.0, 3.0)
     p.rotate(angle=0.5)
     # Correct answer determined using AutoCAD software
     self.assertAlmostEqual(p.x, -0.56069405, places=3)
     self.assertAlmostEqual(p.y, 3.11217322, places=3)
Example #2
0
 def on_key_press(self, symbol, modifiers):
     # выход из приложения
     if symbol == key.ESCAPE:
         self.close()
     # удаление точки
     elif symbol == key.DELETE:
         self.boundary.delete()
     # уменьшение точек
     elif symbol == key.DOWN:
         Point.set_radius(Point.radius - 1)
     # увеличение точек
     elif symbol == key.UP:
         Point.set_radius(Point.radius + 1)
     # очищение boundary
     elif symbol == key.C:
         self.boundary.clear()
         self.container3D.clear()
     elif symbol == key.A:
         self.container3D.rotate(-180, 0)
     elif symbol == key.W:
         self.container3D.rotate(0, 180)
     elif symbol == key.D:
         self.container3D.rotate(180, 0)
     elif symbol == key.S:
         self.container3D.rotate(0, -180)
     elif symbol == key.Q:
         self.container3D.clear()
     elif symbol == key.P:
         print(datetime.now())
Example #3
0
def combine_chains(chain1: EpicycleChain1D,
                   chain2: EpicycleChain1D,
                   tag_name,
                   color='black'):
    assert chain1.canvas == chain2.canvas
    assert chain1.num_vectors == chain2.num_vectors
    rotation = (chain1.rotation + chain2.rotation) / 2
    result_chain = EpicycleChain1D(chain1.canvas,
                                   chain1.origin_point,
                                   rotation,
                                   tag_name=tag_name)

    N = chain1.num_vectors
    c = result_chain.canvas

    result_chain.vectors = [Vector(Point(0, 0), Point(0, 0)) for i in range(N)]
    result_chain.epicycles = [
        (
            c.create_line(0, 0, 0, 0, tag=tag_name,
                          fill=color),  # , arrow=tk.LAST),
            c.create_oval(0, 0, 0, 0, tag=tag_name, outline=color))
        for i in range(N)
    ]
    for i in range(N):
        result_chain.vectors[i] = chain1.vectors[i] + chain2.vectors[i]
    result_chain.num_vectors = N
    return result_chain
Example #4
0
 def test_point_constructors(self):
     pt1 = (4.5, -5.4)
     pt2 = Point.from_tuple(pt1)
     pt3 = Point(x=4.5, y=-5.4)
     pt4 = Point.from_point(pt3)
     self.assertAlmostEqual(pt1[0], pt2.x, places=6)
     self.assertAlmostEqual(pt1[1], pt2.y, places=6)
     self.assertAlmostEqual(pt1[0], pt3.x, places=6)
     self.assertAlmostEqual(pt1[1], pt3.y, places=6)
     self.assertAlmostEqual(pt1[0], pt4.x, places=6)
     self.assertAlmostEqual(pt1[1], pt4.y, places=6)
Example #5
0
def find_layout(c, start):
    NORTH = 1
    SOUTH = 2
    WEST = 3
    EAST = 4
    direc_order = [NORTH, EAST, SOUTH, WEST]
    direc_step = {
        NORTH: Point(0, 1),
        EAST: Point(1, 0),
        SOUTH: Point(0, -1),
        WEST: Point(-1, 0)
    }

    BLOCKED = 0
    OK = 1
    END = 2

    move = NORTH
    loc = start
    direc = 0

    # Empirically determined size
    layout = np.full((43, 43), 3, dtype=np.int8)
    layout[tuple(start)] = 2
    move_count = 0
    while c.running:
        c.run([move])
        status = c.output.pop()

        step = direc_step[move]
        next_loc = loc + step
        if next_loc == start:
            break
        layout[tuple(next_loc)] = status

        if status == BLOCKED:
            # Turn left
            direc = (direc - 1) % 4
            move = direc_order[direc]
        elif status in (OK, END):
            # Turn right--essentially constantly tests wall on right
            move_count += 1
            loc = next_loc
            direc = (direc + 1) % 4
            move = direc_order[direc]
            if status == END:
                goal = next_loc


#     fig, ax = plt.subplots(figsize=(10, 10))
#     ax.imshow(layout.T, origin='lower')

    return layout, goal
Example #6
0
 def __init__(self):
     self.floor = 0
     self.pos = Point(0, 0)  # overwritten by game state initialization
     self.level = 1
     self.xp = 0
     self.next_lvl = XP_LEVELS[1]
     self.hp = 10
     self.max_hp = 10
     self.dmg = "1d6"
     self.vis_range = 15
     self.gp = 0
     self.potions = 1
     self.name = random.choice(NAMES)
     self.race = random.choice(RACES)
     self.pclass = random.choice(CLASSES)
Example #7
0
def merge_vectors(vectors1, vectors2):
    assert vectors1[0].p_from == vectors2[0].p_from
    assert len(vectors1) == len(vectors2)
    vectors = []
    x_prev, y_prev = list(vectors1[0].p_from.get_iter())
    for i in range(len(vectors1)):
        rel_vec1 = (vectors1[i].p_to[0] - vectors1[i].p_from[0],
                    vectors1[i].p_to[1] - vectors1[i].p_from[1])
        rel_vec2 = (vectors2[i].p_to[0] - vectors2[i].p_from[0],
                    vectors2[i].p_to[1] - vectors2[i].p_from[1])
        rel_vec = rel_vec1[0] + rel_vec2[0], rel_vec1[1] + rel_vec2[1]
        x_cur, y_cur = x_prev + rel_vec[0], y_prev + rel_vec[1]
        vectors.append(Vector(Point(x_prev, y_prev), Point(x_cur, y_cur)))
        x_prev, y_prev = x_cur, y_cur
    return vectors
Example #8
0
File: poi.py Project: jfarrimo/sabx
    def __init__(self, id, description, lat, lon):
        """
        Save the passed-in data.

        @param id: id of the point of interest
        @type id: C{string}
        @param description: description of the point of interest
        @type description: C{string}
        @param lat: latitude of point of interest
        @type lat: C{float}
        @param lon: longitude of point of interest
        @type lon: C{float}
        """
        Point.__init__(self, lat, lon, id=id)
        self.description = description
Example #9
0
 def on_mouse_press(self, x, y, buttons, modifiers):
     # левая для создания точек
     if buttons & mouse.LEFT:
         if self.container2D.isin(x, y):
             x, y = self.container2D.recount_xy(x, y)
             z = randint(0, self.container2D.height_w)
             self.boundary.mouse_press(Point(x, y, z))
def points_inside_triangle(a: Point, b: Point, c: Point):
    xs = [x.x() for x in (a, b, c)]
    ys = [x.y() for x in (a, b, c)]

    xs = np.array(xs, dtype=float)
    ys = np.array(ys, dtype=float)

    # The possible range of coordinates that can be returned
    x_range = np.arange(np.min(xs), np.max(xs) + 1)
    y_range = np.arange(np.min(ys), np.max(ys) + 1)

    # Set the grid of coordinates on which the triangle lies. The centre of the
    # triangle serves as a criterion for what is inside or outside the triangle.
    X, Y = np.meshgrid(x_range, y_range)
    xc = np.mean(xs)
    yc = np.mean(ys)

    # From the array 'triangle', points that lie outside the triangle will be
    # set to 'False'.
    triangle = np.ones(X.shape, dtype=bool)
    for i in range(3):
        ii = (i + 1) % 3
        if xs[i] == xs[ii]:
            include = X * (xc - xs[i]) / abs(xc - xs[i]) > xs[i] * (xc - xs[i]) / abs(xc - xs[i])
        else:
            poly = np.poly1d([(ys[ii] - ys[i]) / (xs[ii] - xs[i]), ys[i] - xs[i] * (ys[ii] - ys[i]) / (xs[ii] - xs[i])])
            include = Y * (yc - poly(xc)) / abs(yc - poly(xc)) > poly(X) * (yc - poly(xc)) / abs(yc - poly(xc))
        triangle *= include

    xs = X[triangle]
    ys = Y[triangle]
    return [Point(x, y) for x, y in zip(xs, ys)]
Example #11
0
    def __init__(self, id, fromto, cue, comments):
        """
        Save the passed-in data.

        @param id: id of the turn
        @type id: C{string}
        @param fromto: from segment to segment
        @type fromto: C{string}
        @param cue: instructions for executing the turn
        @type cue: C{string}
        @param comments: additional info about the turn
        @type comments: C{string}
        """
        Point.__init__(self, id=id)
        self.fromto = fromto
        self.cue = cue
        self.comments = comments
Example #12
0
def Txt2PntList(txt):
    """ Convert a string to list of points
        e.g. "1 2 4 6 -1 2" -> [Point(1,2), Point(4, 6), Point(-1, 2)]
    """
    # change string to list of floats
    fl = [float(item) for item in txt.strip().split()]
    # generate easting, northing list
    return [Point(*i) for i in zip(fl[::2], fl[1::2])]
Example #13
0
 def _init_epicycles(self, color):
     c = self.canvas
     self.epicycles = [
         (
             c.create_line(0, 0, 0, 0, tag=self.tag_name, fill=color),
             # , activefill=color, arrow=tk.LAST, arrowshape="10 20 10"
             c.create_oval(0,
                           0,
                           0,
                           0,
                           tag=self.tag_name,
                           outline=color,
                           width=2)) for i in range(self.num_vectors)
     ]
     self.vectors = [
         Vector(Point(0, 0), Point(0, 0)) for i in range(self.num_vectors)
     ]
Example #14
0
def shortest_path(x, y, val):
    """Shortest path using A*."""
    goal = Point(x, y)
    start = Point(1, 1)
    frontier = [Node(0, start)]
    min_dist = {start: 0}
    # came_from = {}
    while frontier:
        current = heapq.heappop(frontier).point
        if current == goal:
            break
        for pt in current.neighbors:
            if is_wall(*pt, val):
                continue
            if (dist := min_dist.get(current, 0) + 1) < min_dist.get(pt, 2**32):
                # came_from[pt] = current
                min_dist[pt] = dist
                heapq.heappush(frontier, Node(dist + pt.manhattan_distance(goal), pt))
Example #15
0
 def set_multi_board(self):
     # Update board with new start:
     if self.multi:
         return
     start = Point(*self.get_location('@'))
     self.layout[start.y - 1] = self.layout[start.y - 1][:start.x - 1] + '@#@' + self.layout[start.y - 1][start.x + 2:]
     self.layout[start.y] = self.layout[start.y][:start.x - 1] + '###' + self.layout[start.y][start.x + 2:]
     self.layout[start.y + 1] = self.layout[start.y + 1][:start.x - 1] + '@#@' + self.layout[start.y + 1][start.x + 2:]
     self.multi = True
Example #16
0
def run(data):
    c = Computer.fromstring(data)

    # arbitrary starting point really, just denotes a location in the grid
    start = Point(22, 20)
    layout, goal = find_layout(c, start)

    path = astar(start, goal, layout)
    return path.cost, fill(goal, layout)
Example #17
0
    def __init__(self, id, type, description, lat, lon):
        """
        Save the passed-in data.

        @param id: id of the stop
        @type id: C{string}
        @param type: type of stop (convenience store, restaurant, etc...)
        @type type: C{string}
        @param description: description of the stop
        @type description: C{string}
        @param lat: latitude of the stop
        @type lat: C{float}
        @param lon: longitude of the stop
        @type lon: C{float}
        """
        Point.__init__(self, lat, lon, id=id)
        self.type = type
        self.description = description
Example #18
0
 def update_vectors_by_time(self, time):
     x_prev, y_prev = self.x0, self.y0
     j = 0
     self.fourier_vectors = sorted(self.fourier_vectors,
                                   key=lambda i: i.amp,
                                   reverse=True)
     for f_vec in self.fourier_vectors:
         # for f_vec in self.fourier_vectors:
         rad = f_vec.amp
         x_cur = x_prev + rad * math.cos(time * f_vec.freq + f_vec.phase +
                                         self.rotation)
         y_cur = y_prev + rad * math.sin(time * f_vec.freq + f_vec.phase +
                                         self.rotation)
         self.vectors[j] = Vector(Point(x_prev, y_prev),
                                  Point(x_cur, y_cur))
         x_prev, y_prev = x_cur, y_cur
         j += 1
     return Point(x_cur, y_cur)  # last point of chain
Example #19
0
    def getMinVolEllipse(self, P=None, tolerance=0.0001):
        """ Find the minimum volume ellipsoid which holds all the points
        
        Based on work by Nima Moshtagh
        http://www.mathworks.com/matlabcentral/fileexchange/9542
        and also by looking at:
        http://cctbx.sourceforge.net/current/python/scitbx.math.minimum_covering_ellipsoid.html
        Which is based on the first reference anyway!
        
        Here, P is a numpy array of N dimensional points like this:
        P = [[x,y,z,...], <-- one point per line
             [x,y,z,...],
             [x,y,z,...]]
        
        Returns:
        (center, radii, rotation)
        
        """
        (N, d) = np.shape(P)
        d = float(d)

        # Q will be our working array
        Q = np.vstack([np.copy(P.T), np.ones(N)])
        QT = Q.T

        # initializations
        err = 1.0 + tolerance
        u = (1.0 / N) * np.ones(N)

        # Khachiyan Algorithm
        while err > tolerance:
            V = np.dot(Q, np.dot(np.diag(u), QT))
            M = np.diag(np.dot(QT, np.dot(
                linalg.inv(V), Q)))  # M the diagonal vector of an NxN matrix
            j = np.argmax(M)
            maximum = M[j]
            step_size = (maximum - d - 1.0) / ((d + 1.0) * (maximum - 1.0))
            new_u = (1.0 - step_size) * u
            new_u[j] += step_size
            err = np.linalg.norm(new_u - u)
            u = new_u

        # center of the ellipse
        center = np.dot(P.T, u)

        # the A matrix for the ellipse
        A = linalg.inv(
            np.dot(P.T, np.dot(np.diag(u), P)) -
            np.array([[a * b for b in center] for a in center])) / d

        # Get the values we'd like to return
        U, s, rotation = linalg.svd(A)
        radii = 1.0 / np.sqrt(s)
        V1 = Vector2(rotation[0][0], rotation[0][1])
        V2 = Vector2(rotation[1][0], rotation[1][1])
        return Ellipse(Point(center), radii, [V1, V2])
Example #20
0
 def mouse_drag(self, x, y, dx, dy):
     if self.mouse_press_index is None:
         self.mouse_press_index = self.get_point_index(Point(x - dx, y - dy))
     if self.mouse_press_index is None:
         return
     self.control_points[self.mouse_press_index].x = x
     self.control_points[self.mouse_press_index].y = y
     for line in self.lines:
         line.recount_points()
     self.changed = True
Example #21
0
def to_image(panels):
    min_row = min(panels.keys(), key=lambda i: i.y).y
    max_row = max(panels.keys(), key=lambda i: i.y).y
    min_col = min(panels.keys(), key=lambda i: i.x).x
    max_col = max(panels.keys(), key=lambda i: i.x).x

    return '\n'.join(''.join(
        '#' if panels.get(Point(col, row), 0) == 1 else ' '
        for col in range(min_col, max_col + 1))
                     for row in range(max_row, min_row - 1, -1))
Example #22
0
def walk(steps):
    loc = Point(0, 0)
    direc = Vector(0, 1, 0)
    for turn, dist in moves(steps):
        if turn == 'R':
            direc = -Vector.k().cross(direc)
        else:
            direc = direc.cross(-Vector.k())
        loc += dist * direc

    return loc
Example #23
0
def import_data(filename):
    lines = open(filename, 'r').read()
    solids = re.split("--- SOLID \[\d*\]---", lines)
    return [
        Solid([
            Face(*[
                Point(*[float(p) for p in point.split(";")])
                for point in face.split("\n") if len(point) != 0
            ]) for face in solid.split("\n\n") if face != ""
        ]) for solid in solids if solid != ""
    ]
Example #24
0
    def __init__(self, *args, **kwargs):
        super(App, self).__init__(caption='Kirchhoff-Plateau Surfaces',
                                  resizable=True,
                                  width=950,
                                  height=480,
                                  *args,
                                  **kwargs)

        self.set_minimum_size(950, 480)
        # инициализируются в on_resize
        self.container2D, self.container3D = None, None
        # создаём Boundary
        self.boundary = Boundary()
        # для рисования
        Point.set_radius(5)
        glEnable(GL_POINT_SMOOTH)
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_DEPTH_TEST)
        # чёрный фон
        glClearColor(0., 0., 0., 1)
Example #25
0
def walk_scaffold(layout, robot):
    direcs = {
        '>': Vector(1, 0, 0),
        '<': Vector(-1, 0, 0),
        '^': Vector(0, -1, 0),
        'V': Vector(0, 1, 0)
    }
    scaffold = '#'

    cur_loc = Point(*robot[:2])
    cur_dir = direcs[robot[-1]]
    cur_run = 0
    moves = []
    while True:
        #print(cur_loc, cur_dir)
        next_loc = cur_loc + cur_dir
        if valid_index(
                layout,
                next_loc) and layout[next_loc.y][next_loc.x] == scaffold:
            cur_loc = next_loc
            cur_run += 1
        else:
            if cur_run:
                moves.append(cur_run)
                cur_run = 0

            # All of the directions are kinda flipped from expected because we're in a coordinate system
            # where +y is down.
            if cur_dir.x == 1:
                left = cur_loc.down
                right = cur_loc.up
            elif cur_dir.x == -1:
                left = cur_loc.up
                right = cur_loc.down
            elif cur_dir.y == 1:
                left = cur_loc.right
                right = cur_loc.left
            elif cur_dir.y == -1:
                left = cur_loc.left
                right = cur_loc.right

            if valid_index(layout,
                           left) and layout[left.y][left.x] == scaffold:
                moves.append('L')
                cur_dir = cur_dir.cross(Vector.k())
            elif valid_index(layout,
                             right) and layout[right.y][right.x] == scaffold:
                moves.append('R')
                cur_dir = Vector.k().cross(cur_dir)
            else:
                break

    return ','.join(str(i) for i in moves)
Example #26
0
 def fit(self, data):
     x_m = np.mean(data[0])
     y_m = np.mean(data[1])
     center_estimate = x_m, y_m
     center, ier = optimize.leastsq(self._f,
                                    center_estimate,
                                    args=(data[0], data[1]))
     xc, yc = center
     Ri = self._calc_R(data[0], data[1], *center)
     R = Ri.mean()
     residu = np.sum((Ri - R)**2)
     return Circle(Point(xc, yc), R)
Example #27
0
    def draw(self):
        for i in range(self.num_vectors):
            vector = self.vectors[i]
            epi = self.epicycles[i]

            from_x, from_y, to_x, to_y = list(vector.get_iter())
            rad = vector.norm()
            self.canvas.coords(epi[0], from_x, from_y, to_x, to_y)  # line
            self.canvas.coords(epi[1], from_x - rad, from_y - rad,
                               from_x + rad, from_y + rad)  # circle
        # return last point of chain
        return Point(to_x, to_y)
Example #28
0
def total_visited(x, y, val):
    """Flood fill with A*-style distance tracking."""
    start = Point(1, 1)
    frontier = deque([start])
    min_dist = {start: 0}
    while frontier:
        current = frontier.pop()
        for pt in current.neighbors:
            if is_wall(*pt, val):
                continue
            if (dist := min_dist.get(current, 0) + 1) <= min(min_dist.get(pt, 2**32), 50):
                min_dist[pt] = dist
                frontier.appendleft(pt)
Example #29
0
def distance(e: Edge, p: Point) -> float:
    # http://geomalgorithms.com/a02-_lines.html#Distance-to-Ray-or-Segment
    v = Vector(e.p1, e.p2)
    w = Vector(e.p1, p)
    c1 = dot(w, v)
    c2 = dot(v, v)
    b = c1 / c2
    pb = Point(e.p1.x + b * v.x, e.p1.y + b * v.y, e.p1.z + b * v.z)

    if c1 <= 0:
        return distance(p, e.p1)
    if c2 <= c1:
        return distance(p, e.p2)
    return distance(p, pb)
Example #30
0
    def __init__(self, id, stop, poi, lat, lon, ele, usgs):
        """
        Save the passed-in data.

        @param id: id of the C{Waypoint}
        @type id: C{string}
        @param stop: space-delimited list of stop id's for this waypoint
        @type stop: C{string}
        @param poi: space-delimited list of poi id's for this waypoint
        @type poi: C{string}
        @param lat: latitude of the waypoint
        @type lat: C{float}
        @param lon: longitude of the waypoint
        @type lon: C{float}
        @param ele: observed elevation for this waypoint (meters above 
        sea level)
        @type ele: C{float}
        @param usgs: USGS elevation for this waypoint (meters above sea level)
        @type usgs: C{float}
        """
        Point.__init__(self, lat, lon, ele, usgs, id)
        self.stop = stop
        self.poi = poi
Example #31
0
def walk2(steps):
    loc = Point(0, 0)
    visited = {loc}
    direc = Vector(0, 1, 0)
    for turn, dist in cycle(moves(steps)):
        if turn == 'R':
            direc = -Vector.k().cross(direc)
        else:
            direc = direc.cross(-Vector.k())
        for _ in range(dist):
            loc += direc
            if loc in visited:
                return loc
            else:
                visited.add(loc)
Example #32
0
def polypath(*polys, **kwargs):
    d = ''
    for poly in polys:
        poly = [Point(p[0], p[1]) for p in poly]

        pts = [(towards(poly[i], poly[i - 1], 1e-2), poly[i],
                towards(poly[i], poly[(i + 1) % len(poly)], 1e-2))
               for i in range(len(poly))]
        started = False
        for p0, p1, p2 in pts:
            d += '%s%f,%f Q%f,%f %f,%f' % ('L' if started else 'M', p0.x, p0.y,
                                           p1.x, p1.y, p2.x, p2.y)
            started = True
        d += 'z'
    return Path(d=d, **kwargs)
Example #33
0
def find_location(cp):
    right = Vector(1, 0, 0)
    down = Vector(0, 1, 0)

    loc = Point(0, 0)
    size = 100
    right_edge = Vector(size - 1, 0, 0)
    bottom_edge = Vector(0, size - 1, 0)

    while not (cp(loc + right_edge) and cp(loc + bottom_edge)):
        while not cp(loc + bottom_edge):
            loc += right
        while not cp(loc + right_edge):
            loc += down

    return loc
Example #34
0
    def find_path(self):
        bfs = BreadthFirstSearch(self.start)
        for loc in bfs:
            if loc == self.end:
                break

            if loc in self.portals:
                bfs.add(self.portals[loc])

            for candidate in Point(*loc).neighbors:
                if self.maze[candidate.y][candidate.x] == self.PATH:
                    bfs.add(tuple(candidate))
        else:
            raise RuntimeError('Failed to find end!')

        return bfs.order()