Exemplo n.º 1
0
def loop(path, car):
    """
    Receive position information and control the car.s
    
    Inputs:
        - path: List of tuples, which are the points of the path in order.
          [(x0, y0), (x1, y1), ...]
        - car: Tuple ((xt, yt), angle) of the current position and direction
          of the car.
    Returns:
        - state: A new dict including the information accumulated up to now.
    """
    ###########################################################################
    # TODO:                                                                   #
    #  Try to control the car in a smooth way. Please take possible errors    #
    #  into consideration. It's also POSSIBLE that `car` is None because the  #
    #  the car is not detected at one time. The parameter `state` may be      #
    #  handful, or you can use global variables and ignore it.                #
    ###########################################################################
    global state, pos

    if car[0] is None:
        print('Position not detected')
        return 0

    p_car = ge.Point(car[0])
    p_path = ge.Point(path[pos])
    line1 = ge.determine_linear_equation(p_car, p_path)
    if state == check_time:
        if p_car - p_path > 50:
            send("F")
        else:
            send("S")
            pos += 1
            if pos == len(path):
                return 1
            state = 0
            print('Turn to point {}'.format(pos))

    elif car[1]:
        delta = (np.arctan2(line1[1], line1[0]) - np.pi / 2) % (2 *
                                                                np.pi) - car[1]
        if delta < -np.pi: delta += np.pi * 2
        elif delta > np.pi: delta -= np.pi * 2

        if car[1] and abs(delta) > 0.3:
            if (delta < 0):
                send("L")
            else:
                send("R")
            state = 0
        else:
            send("S")
            state += 1
            print('Move to point {}'.format(pos))

    else:
        print('Angle not detected')

    return 0
Exemplo n.º 2
0
    def test_line_segment_interference_with_rect(self):
        point1 = geometry.Point( 2, 1 )
        point2 = geometry.Point( 1, 3 )
        point3 = geometry.Point( 9, 7 )
        point4 = geometry.Point( 10, 5 )

        rect_segments = [
            geometry.LineSegment( point1, point2 ),
            geometry.LineSegment( point2, point3 ),
            geometry.LineSegment( point3, point4 ),
            geometry.LineSegment( point4, point1 )
        ]

        self.assertTrue( does_line_segment_interfere_with_rect( geometry.LineSegment( geometry.Point( 5, 0 ),
                                                                                      geometry.Point( 5, 10 ) ),
                                                                rect_segments ) )
        self.assertTrue( does_line_segment_interfere_with_rect( geometry.LineSegment( geometry.Point( 5, 4 ),
                                                                                      geometry.Point( 5, 10 ) ),
                                                                rect_segments ) )
        self.assertTrue( does_line_segment_interfere_with_rect( geometry.LineSegment( geometry.Point( 5, 4 ),
                                                                                      geometry.Point( 5, 3 ) ),
                                                                rect_segments ) )
        self.assertTrue( does_line_segment_interfere_with_rect( geometry.LineSegment( geometry.Point( 2, 2 ),
                                                                                      geometry.Point( 4, 3 ) ),
                                                                rect_segments ) )

        self.assertFalse( does_line_segment_interfere_with_rect( geometry.LineSegment( geometry.Point( 3, 10 ),
                                                                                       geometry.Point( 3, 20 ) ),
                                                                rect_segments ) )
Exemplo n.º 3
0
    def test_point(self):
        p = geometry.Point(10, 23)
        self.assertEqual('%s' % p, '#<Point y=10 x=23>')

        q = p.move_point(DIR_UP, 4)
        self.assertEqual('%s' % q, '#<Point y=6 x=23>')
        self.assertEqual(q.distance_from(p), -4)

        q = p.move_point(DIR_DOWN, 4)
        self.assertEqual('%s' % q, '#<Point y=14 x=23>')
        self.assertEqual(q.distance_from(p), 4)

        q = p.move_point(DIR_LEFT, 4)
        self.assertEqual('%s' % q, '#<Point y=10 x=19>')
        self.assertEqual(q.distance_from(p), -4)

        q = p.move_point(DIR_RIGHT, 4)
        self.assertEqual('%s' % q, '#<Point y=10 x=27>')
        self.assertEqual(q.distance_from(p), 4)

        q = geometry.Point(15, 22)
        self.assertRaises(errors.GeometryError, lambda: q.distance_from(p))

        self.assertFalse(p == q)
        q = geometry.Point(10, 23)
        self.assertTrue(p == q)
Exemplo n.º 4
0
 def test_comparsion(self):
     """Tests for comparsion"""
     point1 = g.Point(0, 0)
     point2 = g.Point(1, 1)
     point3 = g.Point(0, 0)
     self.assertTrue(point1 < point2)
     self.assertTrue(point1 == point3)
Exemplo n.º 5
0
 def polygon_on_click(self, x, y, button, modifiers):
     if (button == mouse.LEFT):
         if (not hasattr(self, 'temp_item')):
             self.temp_item = Polygon([geometry.Point(x, y)])
             self.add_item(self.temp_item)
         else:
             self.temp_item.add_point(geometry.Point(x, y))
         self.check_collisions([self.temp_item])
Exemplo n.º 6
0
 def test_distance(self):
     """Test distance_to()"""
     point1 = g.Point(0, 0)
     point2 = g.Point(0, 1)
     distance_1 = point1.distance_to(point2)
     distance_2 = point2.distance_to(point1)
     self.assertEqual(distance_1, distance_2)
     self.assertTrue(
         distance_1 == distance_2 == g.Point.distance(point1, point2))
Exemplo n.º 7
0
def main(args):
  """
  Generates a file containing the coordinates of a body.

  Parameters
  ----------
  args: namespace
    Arguments parsed from the command-line.
  """
  if args.body_type == 'file':
    body = geometry.Geometry(file_path=args.file_path)
  elif args.body_type == 'circle':
    body = geometry.Circle(radius=args.circle[0],
                           center=geometry.Point(args.circle[1],
                                                 args.circle[2]),
                           n=args.n, ds=args.ds)
  elif args.body_type == 'line':
    body = geometry.Line(length=args.line[0],
                         start=geometry.Point(args.line[1], args.line[2]),
                         n=args.n, ds=args.ds)
  elif args.body_type == 'rectangle':
    body = geometry.Rectangle(bottom_left=geometry.Point(args.rectangle[0],
                                                         args.rectangle[1]),
                              top_right=geometry.Point(args.rectangle[2],
                                                       args.rectangle[3]),
                              nx=args.n,
                              ny=args.n,
                              ds=args.ds)
  elif args.body_type == 'sphere':
    body = geometry.Sphere(radius=args.sphere[0],
                           center=geometry.Point(args.sphere[1],
                                                 args.sphere[2],
                                                 args.sphere[3]),
                           n=args.n,
                           ds=args.ds)
  body.scale(ratio=args.scale)
  body.rotation(center=args.rotation,
                roll=args.roll,
                yaw=args.yaw,
                pitch=args.pitch,
                mode=args.mode)
  body.translation(displacement=args.translation)
  if body.dimensions == 2 and args.body_type == 'file':
    body.discretization(n=args.n,
                        ds=args.ds)
  if body.dimensions == 2 and args.extrusion:
    body = body.extrusion(limits=args.extrusion,
                          n=args.n,
                          ds=args.ds,
                          force=args.force)
  if args.save:
    output_path = os.path.join(args.save_directory,
                               args.save_name + '.' + args.extension)
    body.write(file_path=output_path)
  if args.show:
      body.plot()
Exemplo n.º 8
0
 def make_coordinates(self):
     self.lTop_ = self.pos_
     self.lBot_ = self.pos_ + gm.Point(0, self.sz_.y())
     self.rTop_ = self.pos_ + gm.Point(self.sz_.x(), 0)
     self.rBot_ = self.pos_ + gm.Point(self.sz_.x(), self.sz_.y())
     self.l1_ = gm.Line(self.lTop_, self.lBot_)  # Left line
     self.l2_ = gm.Line(self.lBot_, self.rBot_)
     self.l3_ = gm.Line(self.rBot_, self.rTop_)
     self.l4_ = gm.Line(self.rTop_, self.lTop_)
     self.bbox_ = gm.Bbox(self.lTop_, self.lBot_, self.rBot_, self.rTop_)
Exemplo n.º 9
0
def test_get_normal_towards_point():
    pt1 = gm.Point(0, 0)
    pt2 = gm.Point(1, 1)
    l = gm.Line(pt1, pt2)
    pt3 = gm.Point(1, 0)
    nr1 = l.get_normal_towards_point(pt3)
    print "GT: (0.71,-0.71), Predict: ", nr1
    pt3 = gm.Point(0, 1)
    nr1 = l.get_normal_towards_point(pt3)
    print "GT: (-0.71,0.71), Predict: ", nr1
Exemplo n.º 10
0
    def add_balls(self):
        #generate ball definitions
        allr, allpos = [], []
        for i in range(self.numBalls_):
            placeflag = True
            while placeflag:
                #randomly sample the radius of the ball
                r = int(
                    np.floor(self.bmn_ + self.rand_.rand() *
                             (self.bmx_ - self.bmn_)))
                bdef = pm.BallDef(radius=r, fColor=pm.Color(0.5, 0.5, 0.5))
                #find a position to keep the ball
                '''
					if self.isrect_:
						xleft, ytop = self.pts[0].x_asint(), self.pts[0].y_asint()
						#xmn  = xleft + 2 * r + self.wth_
						#ymn  = ytop  + 2 * r + self.wth_
						#xmx  = xleft + self.whl_ - self.wth_ - 2 * r
						#ymx  = ytop  + self.wvl_ - self.wth_ - 2 * r
						xmn  = xleft + r + self.wth_ + 2 #give some margin
						ymn  = ytop  + r + self.wth_ + 2
						xmx  = xleft + self.whl_ - self.wth_ - r - 2
						ymx  = ytop  + self.wvl_ - self.wth_ - r - 2
						xloc = int(np.floor(xmn + (xmx - xmn) * self.rand_.rand()))
						yloc = int(np.floor(ymn + (ymx - ymn) * self.rand_.rand()))
					else:
					'''
                findflag = True
                count = 0
                while findflag:
                    pt, isvalid, md = self.find_point_within_lines(
                        r + self.wth_ + 2)  #2 is safety margin
                    count += 1
                    if isvalid:
                        findflag = False
                    if count >= 500:
                        print "failed to find a point to place the ball"
                        pdb.set_trace()
                if self.verbose_ > 0:
                    print("ball at (%f, %f), dist: %f" % (pt.x(), pt.y(), md))
                xloc, yloc = pt.x_asint(), pt.y_asint()
                pt = gm.Point(xloc, yloc)
                #determine if the ball can be placed at the chosen position or not
                isok = True
                for j in range(i):
                    dist = pt.distance(allpos[j])
                    if self.verbose_ > 0:
                        print("placement dist:", dist)
                    isok = isok and dist > (allr[j] + r)
                if isok:
                    placeflag = False
                    allr.append(r)
                    allpos.append(pt)
            self.world_.add_object(bdef, initPos=gm.Point(xloc, yloc))
        return allpos
Exemplo n.º 11
0
def test_pseudo_tangent_contact():
    circle = gm.Circle(radius=20, center=gm.Point(0, 0))
    # Parallel to x-axis
    pt1 = gm.Point(-1, 25)
    pt2 = gm.Point(1, 25)
    l1 = gm.Line(pt1, pt2)
    l2 = gm.Line(pt2, pt1)
    iPt1 = circle.get_contact_point_pseudo_tangent(l1)
    iPt2 = circle.get_contact_point_pseudo_tangent(l2)
    print "GT: (0,20), Predict: ", iPt1
    print "GT: (0,20), Predict: ", iPt2
    # Parallel to y-axis
    pt1 = gm.Point(-25, 5)
    pt2 = gm.Point(-25, 50)
    pt3 = gm.Point(30, 5)
    pt4 = gm.Point(30, 50)
    l1 = gm.Line(pt1, pt2)
    l2 = gm.Line(pt3, pt4)
    iPt1 = circle.get_contact_point_pseudo_tangent(l1)
    iPt2 = circle.get_contact_point_pseudo_tangent(l2)
    print "GT: (-20,0), Predict: ", iPt1
    print "GT: (20,0), Predict: ", iPt2
    # A diagonal
    pt1 = gm.Point(50, 0)
    pt2 = gm.Point(0, 50)
    l1 = gm.Line(pt1, pt2)
    iPt1 = circle.get_contact_point_pseudo_tangent(l1)
    print iPt1
Exemplo n.º 12
0
 def __init__(self, initPos=gm.Point(0, 0), sz=gm.Point(4, 100),
              fColor=Color(1.0, 0.0, 0.0), name=None):
     '''
         initPos: Upper left corner
     '''
     self.sz_ = sz
     self.pos_ = initPos
     self.fColor_ = fColor
     self.name_ = name
     self.make_coordinates()
     self.make_data()
Exemplo n.º 13
0
 def test_is_in_area_must_be_true_for_1_1_and_square_size_of_2(self):
     point = geometry.Point(1, 1)
     area = [
         geometry.Point(0, 0),
         geometry.Point(0, 2),
         geometry.Point(2, 2),
         geometry.Point(2, 2)
     ]
     self.assertEqual(True, point.is_in_area(area))
     area.reverse()
     self.assertEqual(True, point.is_in_area(area))
Exemplo n.º 14
0
 def influence_east(self, border: list) -> list:
     """Построить вершины для восточной InfluenceArea"""
     start = border[0]
     end = border[-1]
     result = [geometry.Point(node.x, node.z) for node in border] + [
         geometry.Point(x=self._north, z=end.z),
         geometry.Point(x=self._north, z=self._east),
         geometry.Point(x=self._south, z=self._east),
         geometry.Point(x=self._south, z=start.z)
     ]
     return result
Exemplo n.º 15
0
def detect_point_groups(edge_img, gradient_direction):
    point_groups = []
    visited = np.zeros_like(edge_img).astype(np.bool)
    neighbours = {
        (1, 0),
        (1, 1),
        (0, 1),
        (-1, 1),
        (-1, 0),
        (-1, -1),
        (0, -1),
        (1, -1),
    }

    # DFS through edge pixels
    for y, x in zip(*np.where(edge_img)):
        if visited[y, x]:
            continue

        # start new point group
        point_group = geometry.BoundedGradientPointGroup()
        frontier = [geometry.Point(x, y)]

        while frontier:
            point = frontier.pop()
            direction = gradient_direction[point.y, point.x]

            # verify the direction is inline with existing points
            # stop searching the branch once we hit a bad point
            if not point_group.fits(direction):
                continue

            visited[point.y, point.x] = True
            point_group.add(point, direction)

            # add adjacent edges to the search space
            for dx, dy in neighbours:
                new_x = point.x + dx
                new_y = point.y + dy
                try:
                    if not edge_img[new_y, new_x]:
                        continue

                    if visited[new_y, new_x]:
                        continue

                    frontier.append(geometry.Point(new_x, new_y))
                except IndexError:
                    continue

        point_groups.append(point_group)

    return point_groups
Exemplo n.º 16
0
def test_Point_add():
    point1 = geometry.Point(0, 0)
    point2 = geometry.Point(1, 1)
    point3 = point1 + point2
    assert isinstance(point3, geometry.Point)
    assertEqual(point3.x, 1)
    assertEqual(point3.y, 1)
    assertEqual(point3.degrees, 45)
    assertEqual(point3.radians, math.pi / 4)
    assertEqual(point3.as_euclidian(), (1, 1))
    assertEqual(point3.as_polar_radians(), (math.sqrt(2), math.pi / 4))
    assertEqual(point3.as_polar_degrees(), (math.sqrt(2), 45))
Exemplo n.º 17
0
 def __init__(self,img,width, height) :
     self.sprite = pygame.sprite.Sprite()
     self.sprite.image =  pygame.transform.scale(pygame.image.load(img).convert_alpha(),(80,80))
     self.sprite.rect = self.sprite.image.get_rect()
     self.sprite.rect.top = height -10 - self.sprite.image.get_height()
     self.sprite.rect.left = (width/2) - (self.sprite.image.get_width()/2)
     self.shoots = [] 
     self.colliderCirc = (
                             geometry.Circle(geometry.Point(40,30),20),
                             geometry.Circle(geometry.Point(20,60),20),
                             geometry.Circle(geometry.Point(60,60),20)
                         )
Exemplo n.º 18
0
def arrange(lines):
    """
    Delete overlapping lines, connect incontinuous lines.
    
    Inputs:
    - lines: List of lines to be rearranged.
      Each line is represent as a numpy array [P.x, P.y, Q.x, Q.y],
      where P and Q are the endpoints of the line.
    """
    flag = False
    while not flag:
        flag = True
        for line1 in lines:
            if not flag: break
            for line2 in lines:
                if line1 is line2: continue
                p = [[gm.Point(*line[:2]),
                      gm.Point(*line[2:])] for line in (line1, line2)]
                l = [gm.determine_linear_equation(*p[i]) for i in range(2)]
                if gm.get_distance(l[1],
                                   p[0][0]) <= delta_e and gm.get_distance(
                                       l[1], p[0][1]) <= delta_e:
                    ends = p[0]
                    pl = [
                        gm.get_perpendicular_line(l[0], p[1][i])
                        for i in range(2)
                    ]
                    out = [
                        not ((gm.f(pl[i], p[0][0]) > 0) ^
                             (gm.f(pl[i], p[0][1]) > 0)) for i in range(2)
                    ]
                    if out[0] and out[1] and not ((gm.f(pl[0], p[0][0]) > 0) ^
                                                  (gm.f(pl[1], p[0][0]) > 0)):
                        flag = False
                        for i in range(2):
                            if flag:
                                break
                            for j in range(2):
                                if ends[i] - p[1][j] <= delta_v:
                                    ends[i] = p[1][1 - j]
                                    flag = True
                                    break
                    else:
                        for i in range(2):
                            if out[i]:
                                ends[i] = p[1][i]
                    remove(lines, line1)
                    remove(lines, line2)
                    lines.append(
                        np.array(ends[0].to_tuple() + ends[1].to_tuple()))
                    flag = False
                    break
Exemplo n.º 19
0
def detect_words(pixels):
    visited = np.zeros_like(pixels).astype(np.bool)
    neighbours = {
        (1, 0),
        (1, 1),
        (0, 1),
        (-1, 1),
        (-1, 0),
        (-1, -1),
        (0, -1),
        (1, -1),
    }

    words = []

    # DFS through edge pixels
    for y, x in zip(*np.where(pixels)):
        if visited[y, x]:
            continue

        # create a new character region
        word = text.Word(pixels)
        frontier = [geometry.Point(x, y)]

        while frontier:
            point = frontier.pop()
            if not word.fits(point):
                continue

            visited[point.y, point.x] = True
            word.add(point)

            # add adjacent edges to the search space
            for dx, dy in neighbours:
                new_x = point.x + dx
                new_y = point.y + dy
                try:
                    if not pixels[new_y, new_x]:
                        continue

                    if visited[new_y, new_x]:
                        continue

                    frontier.append(geometry.Point(new_x, new_y))
                except IndexError:
                    continue

        words.append(word)

    return words
Exemplo n.º 20
0
def create_world_diamond():
	world = pm.World(xSz=640, ySz=480)
	pt1   = gm.Point(50, 240)
	pt2   = gm.Point(300, 40)
	pt3   = gm.Point(550, 240)
	pt4   = gm.Point(300, 440)
	walls = pm.create_cage([pt1, pt2, pt3, pt4], wThick=20)
	for w in walls:
		world.add_object(w)

	bDef  = pm.BallDef(fColor=pm.Color(0.5,0.5,0.5))
	world.add_object(bDef, initPos=gm.Point(200,200))
	im = world.generate_image()	
	return im, world	
Exemplo n.º 21
0
def get_block_im(blockDir,
                 fColor=Color(1.0, 0.0, 0.0),
                 sThick=2,
                 bThick=30,
                 sColor=None):
    '''
		blockDir: the the direction in which block needs to be created
	'''
    stPoint = gm.Point(0, 0)
    enPoint = stPoint + blockDir
    pts = get_box_coords(stPoint, enPoint, wThick=bThick)
    pt1, pt2, pt3, pt4 = pts
    #Create the points for drawing the block.
    mnX = min(pt1.x(), pt2.x(), pt3.x(), pt4.x())
    mnY = min(pt1.y(), pt2.y(), pt3.y(), pt4.y())
    mnPt = gm.Point(mnX, mnY)
    pt1, pt2 = pt1 - mnPt, pt2 - mnPt
    pt3, pt4 = pt3 - mnPt, pt4 - mnPt
    #print pt1, pt2, pt3, pt4

    if sColor is None:
        sColor = fColor
    xSz = int(np.ceil(max(pt1.x(), pt2.x(), pt3.x(), pt4.x())))
    ySz = int(np.ceil(max(pt1.y(), pt2.y(), pt3.y(), pt4.y())))
    data = np.zeros((ySz, xSz, 4), dtype=np.uint8)
    surface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_ARGB32,
                                                 xSz, ySz)
    cr = cairo.Context(surface)
    #Create a transparent source
    cr.set_source_rgba(1.0, 1.0, 1.0, 0.0)
    cr.paint()
    #Create the border/Mask
    cr.move_to(pt1.x(), pt1.y())
    cr.line_to(pt2.x(), pt2.y())
    cr.line_to(pt3.x(), pt3.y())
    cr.line_to(pt4.x(), pt4.y())
    cr.line_to(pt1.x(), pt1.y())
    cr.set_line_width(sThick)
    cr.set_source_rgba(sColor.b, sColor.g, sColor.r, sColor.a)
    cr.stroke()
    #Fill in the desired color
    cr.set_source_rgba(fColor.b, fColor.g, fColor.r, fColor.a)
    cr.move_to(pt1.x(), pt1.y())
    cr.line_to(pt2.x(), pt2.y())
    cr.line_to(pt3.x(), pt3.y())
    cr.line_to(pt4.x(), pt4.y())
    cr.line_to(pt1.x(), pt1.y())
    cr.fill()
    return cr, data
Exemplo n.º 22
0
 def __init__(self, call_sign, flight_type, cat):
     self.call_sign = call_sign
     self.type = flight_type
     self.cat = cat
     self.stand = None
     self.runway = None
     self.qfu = 0
     self.start_t = None
     self.end_t = None
     self.rwy_t = None
     self.slot = None
     self.route = None
     self.last_velo = geometry.Vector(geometry.Point(0, 0),
                                      geometry.Point(0, 0))
     self.engine = None
Exemplo n.º 23
0
def test_line_bbox_intersection():
    bbox = gm.Bbox(gm.Point(1, 2), gm.Point(1, 1), gm.Point(2, 1), gm.Point(2, 2))
    l1 = gm.Line(gm.Point(0, 0), gm.Point(1.5, 1.9))
    l2 = gm.Line(gm.Point(0, 0), gm.Point(1, 10))
    l3 = gm.Line(gm.Point(0, 1), gm.Point(5, 1))
    print "GT: True, Predict:", bbox.is_intersect_line(l1)
    print "GT: False, Predict:", bbox.is_intersect_line(l2)
    print "GT: True, Predict:", bbox.is_intersect_line(l3)

    pt1, s1 = bbox.get_intersection_with_line(l1)
    pt2, s2 = bbox.get_intersection_with_line(l2)
    pt3, s3 = bbox.get_intersection_with_line(l3)
    print pt1, s1
    print pt2, s2
    print pt3, s3
Exemplo n.º 24
0
def ball_world_simulation(): 
	plt.ion()
	plt.figure()
	#_,world = create_single_ball_world_gray()
	_,world = create_world_diamond()
	im = world.generate_image()
	plt.imshow(im)
	model = pm.Dynamics(world)		
	model.world_.dynamic_['ball-0'].set_velocity(gm.Point(2000,100))
	ballPos = deque()
	nPlot   = 20
	cmap    = plt.cm.ScalarMappable(cmap='jet')
	cmap.set_clim((0,nPlot))
	for i in range(100):
		im  = ball_world_step(i, model)
		plt.imshow(im)
		pos = model.get_object_position('ball-0')
		ballPos.append(pos)
		for j in range(min(i, nPlot)):
			plt.plot(ballPos[j].x(), ballPos[j].y(), '.',color=cmap.to_rgba(j))
		if i >= nPlot:
			p = ballPos.popleft()
			plt.plot(p.x(), p.y(), '.',color=(1.0,1.0,1.0,1.0))
		a = raw_input()
		if a=='q':
			break
Exemplo n.º 25
0
 def from_def(cls, ballDef, name, initPos, initVel=gm.Point(0, 0)):
     self = cls(radius=ballDef.radius, sThick=ballDef.sThick,
                sColor=ballDef.sColor, fColor=ballDef.fColor)
     self.name_ = name
     self.pos_ = initPos
     self.vel_ = initVel
     return self
    def update_rangefinder_sensors(self):
        """
        The function to update the agent range finder sensors.
        """
        for i, angle in enumerate(self.agent.range_finder_angles):
            rad = geometry.deg_to_rad(angle)
            # project a point from agent location outwards
            projection_point = geometry.Point(
                x=self.agent.location.x +
                math.cos(rad) * self.agent.range_finder_range,
                y=self.agent.location.y +
                math.sin(rad) * self.agent.range_finder_range)
            # rotate the projection point by the agent's heading angle to
            # align it with heading direction
            projection_point.rotate(self.agent.heading, self.agent.location)
            # create the line segment from the agent location to the projected point
            projection_line = geometry.Line(a=self.agent.location,
                                            b=projection_point)
            # set range to maximum detection range
            min_range = self.agent.range_finder_range

            # now test against maze walls to see if projection line hits any wall
            # and find the closest hit
            for wall in self.walls:
                found, intersection = wall.intersection(projection_line)
                if found:
                    found_range = intersection.distance(self.agent.location)
                    # we are interested in the closest hit
                    if found_range < min_range:
                        min_range = found_range

            # Update sensor value
            self.agent.range_finders[i] = min_range
Exemplo n.º 27
0
def test_Rectangle_bounding_box():
    rectangle = geometry.Rectangle(geometry.Point(10, 10), 20, 20, geometry.RotationDegrees(0))
    bounding_box = rectangle.bounding_box
    assert (bounding_box.upper_left.x, bounding_box.upper_left.y) == (0, 20)
    assert (bounding_box.lower_left.x, bounding_box.lower_left.y) == (0, 0)
    assert (bounding_box.lower_right.x, bounding_box.lower_right.y) == (20, 0)
    assert (bounding_box.upper_right.x, bounding_box.upper_right.y) == (20, 20)
Exemplo n.º 28
0
def createCellObjs(initialPoints, vor, pointObjs):
    final = dict()
    # print("Total regions:")
    # print(len(vor.regions))
    # print(vor.regions)
    # print("Total points:")
    # print(len(vor.points))
    # print(vor.points)
    for i in range(len(vor.points)):
        regionIndex = vor.point_region[i]
        #print("i: " + str(i))
        # There are half as many points as there are values in initialPoints (is 2d)
        #print(vor.points)
        #print(vor.points[i*2])
        newCentre = geometry.Point(vor.points[i][0], vor.points[i][1])
        #print(newCentre.coords)
        # Use index i to find set of points surrounding region
        points = []
        for n in vor.regions[regionIndex]:
            #print("n: " + str(n))
            # Use point objects rather than vertex information
            if n == -1:
                #print("N is minus 1")
                pass
            else:
                points.append(pointObjs[n])
        newCell = geometry.Cell(newCentre, points)
        final[newCell.id] = newCell
    return final
Exemplo n.º 29
0
    def _update(self, event, x, y, flag, para):
        """
        mouse event
        """
        image = self.img.copy()
        if event == cv2.EVENT_LBUTTONDOWN:
            self._point = ge.Point(x, y)
            self._point = self._get_nearest_corner()
        elif event == cv2.EVENT_MOUSEMOVE:
            if self._point is not None:
                self._point.update(x, y)
        elif event == cv2.EVENT_LBUTTONUP:
            self._point = None

        cv2.line(image, self.corners.p1.tuple(), self.corners.p2.tuple(), (255, 255, 255), self.line_thick)
        cv2.line(image, self.corners.p1.tuple(), self.corners.p3.tuple(), (255, 255, 255), self.line_thick)
        cv2.line(image, self.corners.p2.tuple(), self.corners.p4.tuple(), (255, 255, 255), self.line_thick)
        cv2.line(image, self.corners.p3.tuple(), self.corners.p4.tuple(), (255, 255, 255), self.line_thick)

        cv2.circle(image, self.corners.p1.tuple(), 5, [255, 255, 255], 1)
        cv2.circle(image, self.corners.p2.tuple(), 10, [255, 255, 255], 3)
        cv2.circle(image, self.corners.p3.tuple(), 15, [255, 255, 255], 5)
        cv2.circle(image, self.corners.p4.tuple(), 20, [255, 255, 255], 7)

        cv2.imshow(self.win_name, image)
Exemplo n.º 30
0
def multi_ball_world_simulation(): 
	plt.ion()
	plt.figure()
	_,world = create_multiple_ball_world_gray()
	im = world.generate_image()
	plt.imshow(im)
	model = pm.Dynamics(world)		
	model.world_.dynamic_['ball-0'].set_velocity(gm.Point(1000,0))
	#model.world_.dynamic_['ball-1'].set_velocity(gm.Point(-2000,500))
	#model.world_.dynamic_['ball-1'].set_velocity(gm.Point(-100,0))
	#model.world_.dynamic_['ball-1'].set_velocity(gm.Point(0,0))
	for i in range(1000):
		im  = ball_world_step(i, model)
		name = imName % i
		#scm.imsave(name, im)
		plt.imshow(im)
		#pos = model.get_object_position('ball-0')
		#ballPos.append(pos)
		#for j in range(min(i, nPlot)):
		#	plt.plot(ballPos[j].x(), ballPos[j].y(), '.',color=cmap.to_rgba(j))
		#if i >= nPlot:
		#	p = ballPos.popleft()
		#	plt.plot(p.x(), p.y(), '.',color=(1.0,1.0,1.0,1.0))
		a = raw_input()
		if a=='q':
			break