예제 #1
0
 def test_cant_change_lane_when_close_to_traffic_lights(self):
     car1 = Car(98, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     light = TrafficLight(100)
     self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))
예제 #2
0
    def test_gather_matching_genres(self):
        self.fantasy, ig = Genre.lookup(self._db, classifier.Fantasy)
        self.urban_fantasy, ig = Genre.lookup(self._db,
                                              classifier.Urban_Fantasy)

        self.cooking, ig = Genre.lookup(self._db, classifier.Cooking)
        self.history, ig = Genre.lookup(self._db, classifier.History)

        # Fantasy contains three subgenres and is restricted to fiction.
        fantasy, default = Lane.gather_matching_genres(
            [self.fantasy], Lane.FICTION_DEFAULT_FOR_GENRE)
        eq_(4, len(fantasy))
        eq_(True, default)

        fantasy, default = Lane.gather_matching_genres([self.fantasy], True)
        eq_(4, len(fantasy))
        eq_(True, default)

        fantasy, default = Lane.gather_matching_genres([self.fantasy], True,
                                                       [self.urban_fantasy])
        eq_(3, len(fantasy))
        eq_(True, default)

        # Attempting to create a contradiction (like nonfiction fantasy)
        # will create a lane broad enough to actually contain books
        fantasy, default = Lane.gather_matching_genres([self.fantasy], False)
        eq_(4, len(fantasy))
        eq_(Lane.BOTH_FICTION_AND_NONFICTION, default)

        # Fantasy and history have conflicting fiction defaults, so
        # although we can make a lane that contains both, we can't
        # have it use the default value.
        assert_raises(UndefinedLane, Lane.gather_matching_genres,
                      [self.fantasy, self.history],
                      Lane.FICTION_DEFAULT_FOR_GENRE)
예제 #3
0
    def process_image(self, image):
        img_height, img_width, _ = image.shape

        undistorted_img = self.undistort(image)
        color_binary, combined_binary = self.thresholded_binary(
            undistorted_img)
        bin_image = self.transform_to_top_down(combined_binary)

        left_fitx, right_fitx, ploty, left_fit, right_fit, leftx, lefty, rightx, righty = self.find_lane_lines(
            bin_image)
        left = Lane(leftx, lefty)
        right = Lane(rightx, righty)

        lanes = Lanes(left, right)

        self.lanes_average.update(lanes)

        if self.last_lanes is None:
            self.last_lanes = lanes

        if lanes.lanes_parallel(img_height) and lanes.distance_from_center(
            (img_width / 2, img_height)) < 4.0:
            self.last_lanes = lanes

        self.output = self.draw_overlays(
            image=image,
            left_fit=self.lanes_average.lanes.left.pixels.fit,
            right_fit=self.lanes_average.lanes.right.pixels.fit,
            leftx=self.lanes_average.left.xs,
            rightx=self.lanes_average.right.xs,
            lefty=self.lanes_average.left.ys,
            righty=self.lanes_average.right.ys)

        return self.output
예제 #4
0
 def test_can_change_lane_when_alone(self):
     car1 = Car(20, 0, 0, 10, 0)
     lane1 = Lane()
     lane2 = Lane()
     lane1.add_car(car1)
     light = TrafficLight(100)
     self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))
예제 #5
0
    def test_can_change_lane_when_alone(self):
	car1 = Car(20, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
        light = TrafficLight(100)
        self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))
예제 #6
0
    def __init__(self):

        self.image_shape = [0, 0]

        self.camera_calibration_path = '../camera_cal/'
        self.output_images_path = '../output_images/'
        self.input_video_path = '../input_video/'
        self.output_video_path = '../output_video/'

        self.sobel_kernel_size = 7
        self.sx_thresh = (60, 255)
        self.sy_thresh = (60, 150)
        self.s_thresh = (170, 255)
        self.mag_thresh = (40, 255)
        self.dir_thresh = (.65, 1.05)

        self.wrap_src = np.float32([[595, 450], [686, 450], [1102, 719], [206, 719]])
        self.wrap_dst = np.float32([[320, 0], [980, 0], [980, 719], [320, 719]])

        self.mask_offset = 30
        self.vertices = [np.array([[206-self.mask_offset, 719],
                                   [595-self.mask_offset, 460-self.mask_offset],
                                   [686+self.mask_offset, 460-self.mask_offset],
                                   [1102+self.mask_offset, 719]],
                                  dtype=np.int32)]

        self.mask_offset_inverse = 30
        self.vertices_inverse = [np.array([[206+self.mask_offset_inverse, 719],
                                   [595+self.mask_offset_inverse, 460-self.mask_offset_inverse],
                                   [686-self.mask_offset_inverse, 460-self.mask_offset_inverse],
                                   [1102-self.mask_offset_inverse, 719]],
                                  dtype=np.int32)]

        self.thresh = Threshold()
        self.lane = Lane()
예제 #7
0
    def test_get_search_target(self):
        fantasy, ig = Genre.lookup(self._db, classifier.Fantasy)
        lane = Lane(
            self._db, "YA Fantasy", genres=fantasy, 
            languages='eng',
            audiences=Lane.AUDIENCE_YOUNG_ADULT,
            age_range=[15,16],
            subgenre_behavior=Lane.IN_SUBLANES
        )
        sublanes = lane.sublanes.lanes
        names = sorted([x.name for x in sublanes])
        eq_(["Epic Fantasy", "Historical Fantasy", "Urban Fantasy"],
            names)

        # To start with, none of the lanes are searchable.
        eq_(None, lane.search_target)
        eq_(None, sublanes[0].search_target)

        # If we make a lane searchable, suddenly there's a search target.
        lane.searchable = True
        eq_(lane, lane.search_target)

        # The searchable lane also becomes the search target for its
        # children.
        eq_(lane, sublanes[0].search_target)
예제 #8
0
    def search(cls, _db, title, url, lane, search_engine, query, pagination=None,
               annotator=None
    ):
        if not isinstance(lane, Lane):
            search_lane = Lane(
                _db, "Everything", searchable=True, fiction=Lane.BOTH_FICTION_AND_NONFICTION)
        else:
            search_lane = lane

        results = search_lane.search(query, search_engine, pagination=pagination)
        opds_feed = AcquisitionFeed(_db, title, url, results, annotator=annotator)
        AcquisitionFeed.add_link_to_feed(feed=opds_feed.feed, rel='start', href=annotator.default_lane_url(), title=annotator.top_level_title())

        if len(results) > 0:
            # There are works in this list. Add a 'next' link.
            AcquisitionFeed.add_link_to_feed(feed=opds_feed.feed, rel="next", href=annotator.search_url(lane, query, pagination.next_page))

        if pagination.offset > 0:
            AcquisitionFeed.add_link_to_feed(feed=opds_feed.feed, rel="first", href=annotator.search_url(lane, query, pagination.first_page))

        previous_page = pagination.previous_page
        if previous_page:
            AcquisitionFeed.add_link_to_feed(feed=opds_feed.feed, rel="previous", href=annotator.search_url(lane, query, previous_page))

        # Add "up" link and breadcrumbs
        AcquisitionFeed.add_link_to_feed(feed=opds_feed.feed, rel="up", href=annotator.lane_url(search_lane), title=lane.display_name)
        opds_feed.add_breadcrumbs(search_lane, annotator, include_lane=True)

        annotator.annotate_feed(opds_feed, lane)
        return unicode(opds_feed)
예제 #9
0
    def test_custom_sublanes(self):
        fantasy, ig = Genre.lookup(self._db, classifier.Fantasy)
        urban_fantasy, ig = Genre.lookup(self._db, classifier.Urban_Fantasy)

        urban_fantasy_lane = Lane(self._db,
                                  "Urban Fantasy",
                                  genres=urban_fantasy)

        fantasy_lane = Lane(self._db,
                            "Fantasy",
                            fantasy,
                            genres=fantasy,
                            subgenre_behavior=Lane.IN_SAME_LANE,
                            sublanes=[urban_fantasy_lane])
        eq_([urban_fantasy_lane], fantasy_lane.sublanes.lanes)

        # You can just give the name of a genre as a sublane and it
        # will work.
        fantasy_lane = Lane(self._db,
                            "Fantasy",
                            fantasy,
                            genres=fantasy,
                            subgenre_behavior=Lane.IN_SAME_LANE,
                            sublanes="Urban Fantasy")
        eq_([["Urban Fantasy"]],
            [x.genre_names for x in fantasy_lane.sublanes.lanes])
예제 #10
0
    def open(self):
        fileName, _ = QtGui.QFileDialog.getOpenFileName(
            self, "Open File", QtCore.QDir.currentPath())
        if fileName:

            image = QtGui.QImage(fileName)
            if image.isNull():
                QtGui.QMessageBox.information(self, "Image Viewer",
                                              "Cannot load %s." % fileName)
                return
            Lane.purge()
            image = mpimg.imread(fileName)
            try:
                res = image_pipeline(image)
            except:
                QtGui.QMessageBox.information(
                    self, "Image Viewer",
                    "Cannot detect lines in %s." % fileName)
                return
            plt.imsave('res.jpg', res)
            image = QtGui.QImage('res.jpg')

            self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(image))
            self.scaleFactor = 1.0
            self.imageLabel.adjustSize()
예제 #11
0
    def test_visible_sublanes(self):
        fantasy, ig = Genre.lookup(self._db, classifier.Fantasy)
        urban_fantasy, ig = Genre.lookup(self._db, classifier.Urban_Fantasy)
        humorous, ig = Genre.lookup(self._db, classifier.Humorous_Fiction)

        visible_sublane = Lane(self._db, "Humorous Fiction", genres=humorous)

        visible_grandchild = Lane(self._db,
                                  "Urban Fantasy",
                                  genres=urban_fantasy)

        invisible_sublane = Lane(self._db,
                                 "Fantasy",
                                 invisible=True,
                                 genres=fantasy,
                                 sublanes=[visible_grandchild],
                                 subgenre_behavior=Lane.IN_SAME_LANE)

        lane = Lane(self._db,
                    "English",
                    sublanes=[visible_sublane, invisible_sublane],
                    subgenre_behavior=Lane.IN_SAME_LANE)

        eq_(2, len(lane.visible_sublanes))
        assert visible_sublane in lane.visible_sublanes
        assert visible_grandchild in lane.visible_sublanes
예제 #12
0
    def init_lanes(self, capacities):
        """
        Initialize lanes for each lane group, different lane groups might share the same lane

        :param capacities:
        :return:
        """
        capacities = [int(c) for c in capacities]
        self.capacity = sum(capacities)
        if sum(capacities) == 5:
            # if it's single lane, then all group share the same lane
            self.single_lane = True
            lane = Lane(self.link, self, max(capacities))
            self.lanes["T"].append(lane)
            self.lanes["L"].append(lane)
            self.lanes["R"].append(lane)
        else:
            # create left,right lanes
            left_lane = Lane(self.link, self, capacities[0])
            right_lane = Lane(self.link, self, capacities[-1])
            self.lanes["L"].append(left_lane)
            self.lanes["R"].append(right_lane)

            # create through lanes
            for cap in capacities[1:-1]:
                if cap:
                    self.lanes["T"].append(Lane(self.link, self, cap))

            # if capacity is 5, then left/right and through group share the same lane
            if capacities[0] == 5:
                self.lanes["T"].insert(0, left_lane)
            if capacities[-1] == 5:
                self.lanes["T"].append(right_lane)
예제 #13
0
    def get_lane_type(self, img, color_img):
        right_lane = Lane()
        left_lane = Lane()

        # Detect color.
        left_lane.color, right_lane.color = detect_color(color_img)
        # Detect solid vs dotted and single vs double.
        left_lane, right_lane, left_centers, right_centers = detect_dotted(
            img, left_lane, right_lane)

        # Handle errors. Don't update lane information unless new lane has been seen for 5 frames.
        if left_lane != self.last_left:
            if self.new_count_left >= 5 or self.first_frame:
                self.last_left = left_lane
                self.new_count_left = 0
            else:
                left_lane = self.last_left
                self.new_count_left += 1
        else:
            self.new_count_left = 0
        if right_lane != self.last_right:
            if self.new_count_right >= 5 or self.first_frame:
                self.last_right = right_lane
                self.new_count_right = 0
                self.first_frame = False
            else:
                right_lane = self.last_right
                self.new_count_right += 1
        else:
            self.new_count_right = 0

        return left_lane, right_lane, left_centers, right_centers
예제 #14
0
def quick_detect_lane_lines(image, last_lanes):
    nonzero = image.nonzero()
    nonzero_x, nonzero_y = np.array(nonzero[1]), np.array(nonzero[0])

    last_left_p = np.poly1d(last_lanes.left.pixels.fit)
    last_right_p = np.poly1d(last_lanes.right.pixels.fit)

    margin = 100

    left_lane_indices = ((nonzero_x > (last_left_p(nonzero_y) - margin)) &
                         (nonzero_x < (last_left_p(nonzero_y) + margin)))

    right_lane_indices = ((nonzero_x > (last_right_p(nonzero_y) - margin)) &
                          (nonzero_x < (last_right_p(nonzero_y) + margin)))

    # Again, extract left and right line pixel positions
    left_x = nonzero_x[left_lane_indices]
    left_y = nonzero_y[left_lane_indices]
    right_x = nonzero_x[right_lane_indices]
    right_y = nonzero_y[right_lane_indices]

    left = Lane(left_x, left_y)
    right = Lane(right_x, right_y)

    return Lanes(left, right), image
예제 #15
0
    def test_cant_change_lane_when_close_to_traffic_lights(self):
	car1 = Car(98, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))
def compute_lane_from_candidates(line_candidates, img_shape):
    # Compute lines that approximate the position of both road lanes.
    #:param line_candidates: lines from hough transform
    # :param img_shape: shape of image to which hough transform was applied
    # :return: lines that approximate left and right lane position
    pos_lines = [l for l in line_candidates if l.slope > 0]
    neg_lines = [l for l in line_candidates if l.slope < 0]

    # interpolate biases and slopes to compute equation of line that approximates
    # left lane median is employed to filter outliers
    neg_bias = np.median([l.bias for l in neg_lines]).astype(int)
    neg_slope = np.median([l.slope for l in neg_lines])
    x1, y1 = 0, neg_bias
    x2, y2 = -np.int32(np.round(neg_bias / neg_slope)), 0
    left_lane = Lane(x1, y1, x2, y2)

    # interpolate biases and slopes to compute equation of line that approximates
    # right lane median is employed to filter outliers
    lane_right_bias = np.median([l.bias for l in pos_lines]).astype(int)
    lane_right_slope = np.median([l.slope for l in pos_lines])
    x1, y1 = 0, lane_right_bias
    x2, y2 = np.int32(
        np.round(
            (img_shape[0] - lane_right_bias) / lane_right_slope)), img_shape[0]
    right_lane = Lane(x1, y1, x2, y2)

    return left_lane, right_lane
예제 #17
0
    def update_position(self, maze, modifs):
        """depending on the player answer:
        gives the conditions to update McGyver's position inside the maze.
        modifs: given by the player in the move method of class Game
        return: None if McGyver is out = True and stop reading this method"""
        if self.is_out:
            return
        # initial position = Mcgyver tile in maze
        # update position inside the maze
        pos = maze.find_tile(McGyver)
        lin = pos[0] + modifs[0]
        lin = min(lin, 14)
        lin = max(0, lin)
        col = pos[1] + modifs[1]
        col = min(col, 14)
        col = max(0, col)

        # if the new position (found with get_tile) is an item,
        # print a lane (with set_tile)
        tile = maze.get_tile(lin, col)
        if isinstance(tile, Item):
            self.inventory.append(tile.name)
            maze.set_tile(lin, col, Lane())

        # if the new position is Guardian -> check victory
        if isinstance(maze.get_tile(lin, col), Guardian):
            self.check_victory(maze)
        # if the new position is a lane: replace by mg,
        # and print lane instead of old position
        if isinstance(maze.get_tile(lin, col), Lane):
            maze.set_tile(pos[0], pos[1], Lane())
            maze.set_tile(lin, col, self)
예제 #18
0
 def __init__(self):
     self.new_count_left = 0
     self.new_count_right = 0
     self.last_left = Lane()
     self.last_right = Lane()
     self.first_frame = True
     self.left_fit = None
     self.right_fit = None
예제 #19
0
    def test_shouldnt_change_lane_to_go_faster_when_nothing(self):
	car1 = Car(50, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
        light = TrafficLight(100)
        self.assertFalse(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]))
예제 #20
0
 def test_advance(self):
     for i in range(1, 99):
         test_car = Car(i, 0, 0, 0, 0)
         lane = Lane()
         lanes = [lane]
         lane.add_car(test_car)
         lights = [TrafficLight(100)]
         for j in range(200):
             control.advance(test_car, lane, lanes, lights, 30, 0.1)
         self.assertTrue(test_car.position < 100,
                         'Car starting at %d fail' % i)
예제 #21
0
 def test_advance(self):
     for i in range(1, 99):
         test_car = Car(i, 0, 0, 0, 0)
         lane = Lane()
         lanes = [lane]
         lane.add_car(test_car)
         lights = [TrafficLight(100)]
         for j in range(200):
             control.advance(test_car, lane, lanes, lights, 30, 0.1)
         self.assertTrue(test_car.position < 100,
                 'Car starting at %d fail' % i)
def smoothen_over_time(lane_lines):
    # Smooth the lane line inference over a window of frames and returns the average lines
    avg_line_lt = np.zeros((len(lane_lines), 4))
    avg_line_rt = np.zeros((len(lane_lines), 4))

    for t in range(0, len(lane_lines)):
        avg_line_lt[t] += lane_lines[t][0].get_coordinates()
        avg_line_rt[t] += lane_lines[t][1].get_coordinates()

    # axis=0 : rows
    return Lane(*np.mean(avg_line_lt, axis=0)), Lane(
        *np.mean(avg_line_rt, axis=0))
예제 #23
0
    def bowling_game():

        new_strategy = input(
            "Do you want to input a new strategy? (Answer with Yes or No)\n")
        if new_strategy.lower() == 'yes':
            num_of_strategy = int(
                input("Number of strategies you want to add:"))
            if num_of_strategy != 0:
                Strategies.add_strategy(num_of_strategy)
        Strategies.display_strategies()

        lanes = int(input("\nEnter the number of lanes: "))
        Lane.lanes = lanes
        Lane.start_game_lane()
예제 #24
0
 def __init__(self, *args, **kwargs):
     self.south = Lane("south")
     self.north = Lane("north")
     self.west = Lane("west")
     self.east = Lane("east")
     self.traffic_probability = self.fit_curve(False)
     self.time = 0
예제 #25
0
    def __init__(self):
        self.ym_per_pix = 30 / 720  # meters per pixel in y dimension
        self.xm_per_pix = 3.7 / 880  # meters per pixel in x dimension
        self.src_points = np.float32([[240, 690], [1070, 690], [577, 460],
                                      [706, 460]])

        self.dst_points = np.float32([[200, 720], [1110, 720], [200, 25],
                                      [1110, 25]])
        self.saved_camera_calibration_path = './camera_cal/ \
                                              saved_camera_calibration.p'

        self.camera_calibration = self.__do_camera_calibration()

        self.line_left = Lane()
        self.line_right = Lane()
예제 #26
0
 def detectLane(self, left, right, width):
     lWall, lCenters, lAreas = left
     rWall, rCenters, rAreas = right
     walls = lWall, rWall
     lArea, rArea = 0, 0
     for a in lAreas:
         lArea += a
     for a in rAreas:
         rArea += a
     area = (lArea + rArea) / 2
     print "lane area " + str(area)
     centers = self.determineCentersOfLane(lCenters, rCenters)
     x, y = [], []
     for center in centers:
         x.append(center[0])
         y.append(center[1])
     #y = mx + b
     #slope = np.polyfit(x, y, 1)[0]
     try:
         if centers[0] is not (0, 0) or centers[1] is not (0, 0):
             m, b = np.polyfit(y, x, 1)
             Y = y[0], y[len(y) - 1]
             X = int((Y[0] - b) / m), width / 2
             print "x, y " + str((x, y))
             x, y = (X[0], X[1]), (Y[0], Y[1])
             print "x, y " + str((x, y))
             slope = np.polyfit(x, y, 1)[0]
         else:
             slope = None
     except:
         slope = 0.0
     if False:
         print "slope %.3f" % slope
     #slope = (x2-x1)/float(y2-y1) # I've inverted the slope so that 0 is vertical and infinity is horizontal
     return Lane(walls, centers, slope, area)
예제 #27
0
def process_video_file(file_name, camera):
    lane_object = Lane(camera.image_shape)

    src_clip = VideoFileClip(file_name)
    dst_clip = src_clip.fl_image(
        lambda frame: process_image(frame, camera, lane_object))
    dst_clip.write_videofile(get_out_file_name(file_name), audio=False)
예제 #28
0
    def test_fetch_ignores_feeds_without_content(self):
        facets = Facets.default(self._default_library)
        pagination = Pagination.default()
        lane = Lane(self._db,
                    self._default_library,
                    u"My Lane",
                    languages=['eng', 'chi'])

        # Create a feed without content (i.e. don't update it)
        contentless_feed = get_one_or_create(
            self._db,
            CachedFeed,
            lane_name=lane.name,
            type=CachedFeed.PAGE_TYPE,
            languages=u"eng,chi",
            facets=unicode(facets.query_string),
            pagination=unicode(pagination.query_string))[0]

        # It's not returned because it hasn't been updated.
        args = (self._db, lane, CachedFeed.PAGE_TYPE, facets, pagination, None)
        feed, fresh = CachedFeed.fetch(*args)
        eq_(True, feed != contentless_feed)
        eq_(False, fresh)

        # But if the feed is updated, we get it back.
        feed.update(self._db, u"Just feedy things")
        result, fresh = CachedFeed.fetch(*args)
        eq_(True, fresh)
        eq_(feed, result)
예제 #29
0
def draw_lane_polygon(img):
    offset_from_lane_edge = 20
    color = Lane.COLORS['region_stable']

    if not Lane.lines_exist(): return img

    # Polygon points
    p1 = [Lane.left_line.x1, Lane.left_line.y1]
    p2 = [
        Lane.left_line.get_x_coord(Lane.left_line.y2 + offset_from_lane_edge),
        Lane.left_line.y2 + offset_from_lane_edge
    ]
    p3 = [
        Lane.right_line.get_x_coord(Lane.left_line.y2 + offset_from_lane_edge),
        Lane.right_line.y2 + offset_from_lane_edge
    ]
    p4 = [Lane.right_line.x1, Lane.right_line.y1]

    polygon_points = np.array([p1, p2, p3, p4], np.int32).reshape((-1, 1, 2))

    if not Lane.left_line.stable or not Lane.right_line.stable:
        color = Lane.COLORS['region_unstable']

    poly_img = np.zeros_like(img)
    cv2.fillPoly(poly_img, [polygon_points], color)
    return weighted_img(img, poly_img)
    def test_refusal_to_create_expensive_feed(self):

        facets = Facets.default()
        pagination = Pagination.default()
        lane = Lane(self._db, "My Lane", languages=['eng', 'chi'])

        args = (self._db, lane, CachedFeed.PAGE_TYPE, facets, pagination, None)

        # If we ask for a group feed that will be cached forever, and it's
        # not around, we'll get a page feed instead.
        feed, fresh = CachedFeed.fetch(*args,
                                       max_age=Configuration.CACHE_FOREVER)
        eq_(CachedFeed.PAGE_TYPE, feed.type)

        # If we ask for the same feed, but we don't say it must be cached
        # forever, it'll be created.
        feed, fresh = CachedFeed.fetch(*args, max_age=0)

        # Or if we explicitly demand that the feed be created, it will
        # be created.
        feed, fresh = CachedFeed.fetch(*args,
                                       force_refresh=True,
                                       max_age=Configuration.CACHE_FOREVER)
        feed.update("Cache this forever!")

        # Once the feed has content associated with it, we can ask for
        # it in cached-forever mode and no longer get the exception.
        feed, fresh = CachedFeed.fetch(*args,
                                       max_age=Configuration.CACHE_FOREVER)
        eq_("Cache this forever!", feed.content)
예제 #31
0
    def test_query_works_from_lane_definition_handles_exclude_languages(self):
        search = DummyExternalSearchIndex()

        lane = Lane(
            self._db,
            self._default_library,
            "Not english or spanish",
            exclude_languages=set(['eng', 'spa']),
        )
        filter = search.make_filter(
            lane.media,
            lane.languages,
            lane.exclude_languages,
            lane.fiction,
            list(lane.audiences),
            lane.age_range,
            lane.genre_ids,
        )

        exclude_languages_filter, medium_filter = filter['and']
        expect_exclude_languages = ['eng', 'spa']
        assert 'not' in exclude_languages_filter
        assert 'terms' in exclude_languages_filter['not']
        assert 'language' in exclude_languages_filter['not']['terms']
        eq_(expect_exclude_languages,
            sorted(exclude_languages_filter['not']['terms']['language']))
    def test_lifecycle(self):
        facets = Facets.default()
        pagination = Pagination.default()
        lane = Lane(self._db, "My Lane", languages=['eng', 'chi'])

        # Fetch a cached feed from the database--it's empty.
        args = (self._db, lane, CachedFeed.PAGE_TYPE, facets, pagination, None)
        feed, fresh = CachedFeed.fetch(*args, max_age=0)

        eq_(False, fresh)
        eq_(None, feed.content)

        eq_(pagination.query_string, feed.pagination)
        eq_(facets.query_string, feed.facets)
        eq_(lane.name, feed.lane_name)
        eq_('eng,chi', feed.languages)

        # Update the content
        feed.update("The content")
        self._db.commit()

        # Fetch it again.
        feed, fresh = CachedFeed.fetch(*args, max_age=0)

        # Now it's cached! But not fresh, because max_age is zero
        eq_("The content", feed.content)
        eq_(False, fresh)

        # Lower our standards, and it's fresh!
        feed, fresh = CachedFeed.fetch(*args, max_age=1000)
        eq_("The content", feed.content)
        eq_(True, fresh)
def process_image(file_name, path, show):
    """
    Loads a given image path, and applies the pipeline to it

    :param file_name: The name of the file (without extension)
    :param path: Path to the input (image, video) to process.
    :param show: Show the outcome

    :return: None
    """

    # load the image
    image = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    height, width = image.shape[:2]

    # initialize the objects
    threshold = Threshold()
    lane = Lane(height=height)
    camera = Camera(image_size=(width, height))
    transform = Transform(width=width, height=height)

    # process the frame
    output = pipeline(image, camera, threshold, transform, lane)

    # save the output
    cv2.imwrite(f'data/processed/output_images/{file_name}.jpg', output)
예제 #34
0
    def test_staff_picks_and_best_sellers_sublane(self):
        staff_picks, ignore = self._customlist(
            foreign_identifier=u"Staff Picks",
            name=u"Staff Picks!",
            data_source_name=DataSource.LIBRARY_STAFF,
            num_entries=0)
        best_sellers, ignore = self._customlist(
            foreign_identifier=u"NYT Best Sellers",
            name=u"Best Sellers!",
            data_source_name=DataSource.NYT,
            num_entries=0)
        lane = Lane(self._db,
                    "Everything",
                    include_staff_picks=True,
                    include_best_sellers=True)

        # A staff picks sublane and a best-sellers sublane have been
        # created for us.
        best, picks = lane.sublanes.lanes
        eq_("Best Sellers", best.display_name)
        eq_("Everything - Best Sellers", best.name)
        nyt = DataSource.lookup(self._db, DataSource.NYT)
        eq_(nyt.id, best.list_data_source_id)

        eq_("Staff Picks", picks.display_name)
        eq_("Everything - Staff Picks", picks.name)
        eq_([staff_picks.id], picks.list_ids)
예제 #35
0
    def test_should_change_lane_to_go_to_faster_lane(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(30, 0, 0, 10, 0)
	car3 = Car(40, 0, 0, 10, 0)
	car4 = Car(35, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane1.add_car(car4)
	lane0.add_car(car2)
	lane2.add_car(car3)
        light = TrafficLight(100)
        self.assertEquals(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]), lane2)
예제 #36
0
    def __init__(self):
        super(TrafficMap, self).__init__(46, 139, 87, 255)
        self.north_stop_line = None
        self.east_stop_line = None
        self.south_stop_line = None
        self.west_stop_line = None
        self.north_normal_button = Button("normal", "north", self)
        self.east_normal_button = Button("normal", "east", self)
        self.south_normal_button = Button("normal", "south", self)
        self.west_normal_button = Button("normal", "west", self)
        self.north_emergency_button = Button("emergency", "north", self)
        self.east_emergency_button = Button("emergency", "east", self)
        self.south_emergency_button = Button("emergency", "south", self)
        self.west_emergency_button = Button("emergency", "west", self)

        self.car_queue = []

        self.from_north_light = TrafficLight("north")
        self.from_east_light = TrafficLight("east")
        self.from_south_light = TrafficLight("south")
        self.from_west_light = TrafficLight("west")
        self.from_north_light.push_handlers(self)
        self.from_east_light.push_handlers(self)
        self.from_south_light.push_handlers(self)
        self.from_west_light.push_handlers(self)

        self.north_lane = Lane(self, 'north')
        self.south_lane = Lane(self, 'south')
        self.east_lane = Lane(self, 'east')
        self.west_lane = Lane(self, 'west')

        self.central_occupied = 0

        self.draw_road()
        self.draw_button()
        self.draw_light()
        self.running_lane = "horizontal"
        self.last_change_time = time.time()



        pyglet.clock.schedule_interval(self.schedule, 0.1)
        self.aging = False
예제 #37
0
 def test_advance_with_car_in_front(self):
     for i in range (1, 80):
         test_car_1 = Car(i, 0, 0, 0, 0)
         test_car_2 = Car(i + 19, 0, 0, 0, 0)
         lane = Lane()
         lanes = [lane]
         lane.add_car(test_car_1)
         lane.add_car(test_car_2)
         lights = [TrafficLight(100)]
         for j in range(200):
             control.advance(test_car_1, lane, lanes, lights, 30, 0.1)
             control.advance(test_car_2, lane, lanes, lights, 30, 0.1)
         self.assertTrue(test_car_1.position < 100,
                 'First car at %d fail, pos(car1) = %f, pos(car2) = %f'
                 %(i, test_car_1.position, test_car_2.position))
         self.assertTrue(test_car_2.position < 100,
                 'Second car at %d fails' % (i + 19))
         self.assertTrue(test_car_1.position <= control.rear(
             test_car_2, test_car_1.speed),
             'First car ended up further than expected'
         )
예제 #38
0
    def test_cant_change_lane_when_car_slightly_in_front(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(25, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))
예제 #39
0
    def test_can_change_lane_when_cars_around_but_far(self):
	car1 = Car(50, 0, 0, 10, 0)
	car2 = Car(20, 0, 0, 10, 0)
	car3 = Car(70, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane2.add_car(car2)
	lane2.add_car(car3)
        light = TrafficLight(100)
        self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))
예제 #40
0
파일: tree.py 프로젝트: daveisadork/Racer
 def __init__(
     self,
     tree_type="pro",
     delay=0.4,
     left_lane="computer",
     right_lane="human",
     debug=False,
     perfect=0.0,
     left_rollout=0.220,
     right_rollout=0.220,
     stats=False,
     amin=1.0,
     amax=3.0,
     cmin=-0.009,
     cmax=0.115,
     auto_reset=False,
     res="480x700",
     fullscreen=False,
     hw=False,
     doublebuf=False,
 ):
     self.perfect = perfect
     self.left_rollout = left_rollout
     self.right_rollout = right_rollout
     self.amin = amin
     self.amax = amax
     self.auto_reset = auto_reset
     self.two_player = left_lane == "human" and right_lane == "human"
     self.debug = debug
     self.stats = stats
     self.delay = delay
     self.start = threading.Event()
     self.staged = threading.Event()
     self.quitting = threading.Event()
     self.tree_type = tree_type
     self.tie = []
     self.start_time = None
     self.clock = pygame.time.Clock()
     flags = 0
     if hw:
         flags = flags | pygame.HWSURFACE
     if doublebuf:
         flags = flags | pygame.DOUBLEBUF
     if fullscreen:
         resolution = (0, 0)
         flags = flags | pygame.FULLSCREEN
         pygame.mouse.set_visible(False)
     else:
         width, height = res.split("x")
         resolution = (int(width), int(height))
     self.screen = pygame.display.set_mode(resolution, flags)
     self.scale()
     self.left_lane = Lane(
         tree_type=tree_type,
         delay=delay,
         start=self.start,
         lane="left",
         computer=(left_lane == "computer"),
         perfect=perfect,
         rollout=left_rollout,
         cmin=cmin,
         cmax=cmax,
         surface=self.screen.subsurface(
             pygame.Rect(self.rect.left, self.tree_rect.top, self.rect.centerx, self.tree_rect.height)
         ),
         background=self.background,
     )
     self.right_lane = Lane(
         tree_type=tree_type,
         delay=delay,
         start=self.start,
         lane="right",
         computer=(right_lane == "computer"),
         perfect=perfect,
         rollout=right_rollout,
         cmin=cmin,
         cmax=cmax,
         surface=self.screen.subsurface(
             pygame.Rect(self.rect.centerx, self.tree_rect.top, self.rect.centerx, self.tree_rect.height)
         ),
         background=self.background,
     )
     self.lanes = {"left": self.left_lane, "right": self.right_lane}
     if self.two_player:
         self.human = None
     elif right_lane == "human":
         self.human = self.right_lane
     elif left_lane == "human":
         self.human = self.left_lane
     else:
         self.human = self.left_lane
     if self.debug:
         self.font = pygame.font.Font("assets/font.ttf", 50)
         self.fps = self.font.render("", 1, (255, 255, 255))
     clock = threading.Thread(None, self._clock, name="clock()")
     # monitor = threading.Thread(None, self.thread_monitor,
     #    name="thread_monitor()")
     clock.start()
     # monitor.start()
     self.reset()
     self.event_loop()
     clock.join()
예제 #41
0
class TrafficMap(ColorLayer):
    def __init__(self):
        super(TrafficMap, self).__init__(46, 139, 87, 255)
        self.north_stop_line = None
        self.east_stop_line = None
        self.south_stop_line = None
        self.west_stop_line = None
        self.north_normal_button = Button("normal", "north", self)
        self.east_normal_button = Button("normal", "east", self)
        self.south_normal_button = Button("normal", "south", self)
        self.west_normal_button = Button("normal", "west", self)
        self.north_emergency_button = Button("emergency", "north", self)
        self.east_emergency_button = Button("emergency", "east", self)
        self.south_emergency_button = Button("emergency", "south", self)
        self.west_emergency_button = Button("emergency", "west", self)

        self.car_queue = []

        self.from_north_light = TrafficLight("north")
        self.from_east_light = TrafficLight("east")
        self.from_south_light = TrafficLight("south")
        self.from_west_light = TrafficLight("west")
        self.from_north_light.push_handlers(self)
        self.from_east_light.push_handlers(self)
        self.from_south_light.push_handlers(self)
        self.from_west_light.push_handlers(self)

        self.north_lane = Lane(self, 'north')
        self.south_lane = Lane(self, 'south')
        self.east_lane = Lane(self, 'east')
        self.west_lane = Lane(self, 'west')

        self.central_occupied = 0

        self.draw_road()
        self.draw_button()
        self.draw_light()
        self.running_lane = "horizontal"
        self.last_change_time = time.time()



        pyglet.clock.schedule_interval(self.schedule, 0.1)
        self.aging = False


    def draw_road(self):

        road_image_1 = image.create(200, 800, image.SolidColorImagePattern(color=(190, 190, 190, 255)))
        road_image_2 = image.create(800, 200, image.SolidColorImagePattern(color=(190, 190, 190, 255)))
        road_1 = Sprite(road_image_1, position=(400, 400))
        road_2 = Sprite(road_image_2, position=(400, 400))
        self.add(road_1)
        self.add(road_2)
        self.draw_line()

    def draw_line(self):
        line_1 = Line(start=(0, 400), end=(300, 400), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_1)
        line_2 = Line(start=(400, 800), end=(400, 500), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_2)
        line_3 = Line(start=(500, 400), end=(800, 400), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_3)
        line_4 = Line(start=(400, 300), end=(400, 0), color=(255, 215, 0, 255), stroke_width=5)
        self.add(line_4)
        self.north_stop_line = Line(start=(300, 500), end=(500, 500), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.north_stop_line)
        self.east_stop_line = Line(start=(500, 500), end=(500, 300), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.east_stop_line)
        self.south_stop_line = Line(start=(500, 300), end=(300, 300), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.south_stop_line)
        self.west_stop_line = Line(start=(300, 300), end=(300, 500), color=(255, 255, 255, 255), stroke_width=5)
        self.add(self.west_stop_line)

    def draw_button(self):

        self.add(self.north_normal_button)
        self.add(self.east_normal_button)
        self.add(self.south_normal_button)
        self.add(self.west_normal_button)
        self.add(self.north_emergency_button)
        self.add(self.east_emergency_button)
        self.add(self.south_emergency_button)
        self.add(self.west_emergency_button)


    def draw_light(self):

        self.add(self.from_north_light)
        self.add(self.from_south_light)
        self.add(self.from_east_light)
        self.add(self.from_west_light)

        self.from_west_light.switch_signal()
        self.from_east_light.switch_signal()


    def add_car(self, type, from_direction):
        car = None

        if from_direction is "north":
            car = Car(type, self.north_lane)
            self.north_lane.add_car(car)
            car.do(CustomizeMoveBy((0, -900), duration=4))

        elif from_direction is "south":
            car = Car(type, self.south_lane)
            self.south_lane.add_car(car)
            car.do(CustomizeMoveBy((0, 900), duration=4))
        elif from_direction is "east":
            car = Car(type, self.east_lane)
            self.east_lane.add_car(car)
            car.do(CustomizeMoveBy((-900, 0), duration=4))
        elif from_direction is "west":
            car = Car(type, self.west_lane)
            self.west_lane.add_car(car)

            car.do(CustomizeMoveBy((900, 0), duration=4))

        self.add(car)
        print car
        self.car_queue.append(car)


    def swtich_lights(self):
        self.last_change_time = time.time()
        self.from_north_light.switch_signal()
        self.from_west_light.switch_signal()
        self.from_east_light.switch_signal()
        self.from_south_light.switch_signal()


    def allow_vertical(self):
        self.running_lane = "vertical"
        self.last_change_time = time.time()
        self.from_north_light.set_green()
        self.from_south_light.set_green()
        self.from_east_light.set_red()
        self.from_west_light.set_red()


    def allow_horizontal(self):
        self.running_lane = "horizontal"
        self.last_change_time = time.time()
        self.from_west_light.set_green()
        self.from_east_light.set_green()
        self.from_north_light.set_red()
        self.from_south_light.set_red()

    def clear_central(self):

        self.from_west_light.set_red()
        self.from_east_light.set_red()
        self.from_north_light.set_red()
        self.from_south_light.set_red()

    def has_emergency_car(self):
        if not self.north_lane.has_emergency() and not self.south_lane.has_emergency() \
                and not self.west_lane.has_emergency() and not self.east_lane.has_emergency():
            return False
        else:
            return True

    def has_waiting_car(self):
        if self.north_lane.has_waiting_car() or self.south_lane.has_waiting_car() \
                or self.west_lane.has_waiting_car() or self.east_lane.has_waiting_car():
            return True
        else:
            return False

    def has_emergency_waiting(self):
        if not self.north_lane.has_emergency_waiting() and not self.south_lane.has_emergency_waiting() \
                and not self.west_lane.has_emergency_waiting() and not self.east_lane.has_emergency_waiting():
            return False
        else:
            return True

    def is_empty(self):
        if self.north_lane.normal_car_num + self.north_lane.emergency_car_num is 0 \
                and self.south_lane.normal_car_num + self.south_lane.emergency_car_num is 0 \
                and self.east_lane.normal_car_num + self.east_lane.emergency_car_num is 0 \
                and self.west_lane.normal_car_num + self.west_lane.emergency_car_num is 0:
            return True
        else:
            return False

    def schedule(self, dt):

        # print time.time() -self.last_change_time
        # print "aging",self.aging
        if time.time() - self.last_change_time > 4.0 and (self.aging or self.is_empty()):
            # if self.aging or self.is_empty():
                if not self.central_occupied:
                    if self.running_lane is "horizontal":
                        self.allow_vertical()
                    else:
                        self.allow_horizontal()
                else:
                    self.clear_central()
        else:
            if not self.has_waiting_car():
                self.aging = False
                if not self.has_emergency_car():
                    if self.north_lane.normal_car_num > self.west_lane.normal_car_num and self.north_lane.normal_car_num > self.east_lane.normal_car_num \
                            or self.south_lane.normal_car_num > self.west_lane.normal_car_num and self.south_lane.normal_car_num > self.east_lane.normal_car_num:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()

                else:
                    if self.north_lane.emergency_car_num > self.west_lane.emergency_car_num and self.north_lane.emergency_car_num > self.east_lane.emergency_car_num \
                            or self.south_lane.emergency_car_num > self.west_lane.emergency_car_num and self.south_lane.emergency_car_num > self.east_lane.emergency_car_num:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()
                        else:
                            self.clear_central()
            else:
                print "has waiting"
                self.aging = True
                if not self.has_emergency_waiting():

                    if self.north_lane.waiting_normal_car > self.west_lane.waiting_normal_car and self.north_lane.waiting_normal_car > self.east_lane.waiting_normal_car \
                            or self.south_lane.waiting_normal_car > self.west_lane.waiting_normal_car and self.south_lane.waiting_normal_car > self.east_lane.waiting_normal_car:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()

                else:
                    if self.north_lane.waiting_emergency_car > self.west_lane.waiting_emergency_car and self.north_lane.waiting_emergency_car > self.east_lane.waiting_emergency_car \
                            or self.south_lane.waiting_emergency_car > self.west_lane.waiting_emergency_car and self.south_lane.waiting_emergency_car > self.east_lane.waiting_emergency_car:
                        if not self.central_occupied:
                            if self.running_lane is "horizontal":
                                self.allow_vertical()
                                for car in self.car_queue:
                                    car.resume()
                    else:
                        if not self.central_occupied:
                            if self.running_lane is "vertical":
                                self.allow_horizontal()
                                for car in self.car_queue:
                                    car.resume()
                        else:
                            self.clear_central()
예제 #42
0
class ControlTest(unittest.TestCase):

    def setUp(self):
        self.car = Car(200, 0, 0, 0, 0)
        self.lane = Lane()
        self.lane.add_car(self.car)

    def test_next_in_set(self):
        self.assertEquals(
            control._next_in_set(3, [1, 2, 3, 4, 5], key = lambda x: x), 3
        )
        self.assertEquals(
            control._next_in_set(3, [1, 2, 3.5, 4, 5], key = lambda x: x), 3.5
        )

    def test_prev_in_set(self):
        self.assertEquals(
            control._prev_in_set(3, [1, 2, 3, 4, 5], key = lambda x: x), 3
        )
        self.assertEquals(
            control._prev_in_set(3, [1, 2.5, 3.5, 4, 5], key = lambda x: x), 2.5
        )

    def test_cant_advance_on_traffic_light(self):
        red_light = TrafficLight(200, initial_state='Red')
        self.assertFalse(
            control.can_advance(self.car, self.lane, [self.lane], [red_light], 0)
        )

    def test_can_advance_on_green(self):
        light = TrafficLight(200)
        self.assertTrue(
            control.can_advance(self.car, self.lane, [self.lane], [light], 0)
        )

    def test_car_cant_advance_due_to_traffic(self):
        light = TrafficLight(200)
        other_car = Car(200 + Car.length, 0, 0, 0, 0)
        self.lane.add_car(other_car)
        self.assertFalse(
            control.can_advance(self.car, self.lane, [self.lane], [light], 0)
        )
        # Cleanup
        self.lane.remove_car(other_car)

    def test_get_next_car_before_next_traffic_light_returns_car(self):
        light = TrafficLight(100)
        self.car.position = 20
        other_car = Car(80, 0, 0, 0, 0)
        self.lane.add_car(other_car)
        self.assertEquals(
            control.get_next_car_before_next_traffic_light(
                self.car, self.lane, [light]
            ), other_car
        )
        self.lane.remove_car(other_car)
        self.car.position = 200

    def test_get_next_car_before_next_traffic_light_returns_none(self):
        light = TrafficLight(100)
        self.car.position = 20
        other_car = Car(120, 0, 0, 0, 0)
        self.lane.add_car(other_car)
        self.assertFalse(
            control.get_next_car_before_next_traffic_light(
                self.car, self.lane, [light]
            )
        )
        self.lane.remove_car(other_car)
        self.car.position = 200

    def test_get_next_car_before_next_traffic_light_when_car_on_light(self):
        light = TrafficLight(200)
        other_car = Car(220, 0, 0, 0, 0)
        self.lane.add_car(other_car)
        self.assertFalse(
            control.get_next_car_before_next_traffic_light(
                self.car, self.lane, [light]
            )
        )
        self.lane.remove_car(other_car)

    def test_solve_quadratic_equation_with_one_negative_solution(self):
        self.assertEquals(control.solve_quadratic_equation(1, -3, -10), 5)

    def test_solve_quadratic_equation_with_one_solution(self):
        self.assertEquals(control.solve_quadratic_equation(1, -8, 16), 4)

    def test_solve_quadratic_equation_with_two_positive_solutions(self):
        self.assertEquals(control.solve_quadratic_equation(1, -7, 10), 2)

    def test_get_target_time_without_reaching_max_speed(self):
        test_car = Car(0, 0, 0, 5, 0)
        self.assertTrue(
            abs(control.get_target_time(test_car, 10) - 1.6108) < 0.0001
        )

    def test_get_target_time_reaching_max_speed(self):
        test_car = Car(0, 0, 0, 5, 0)
        self.assertTrue(
            abs(control.get_target_time(test_car, 100) -
                (20.0 / 9 + 200.0 / 3) < 0.0001)
        )

    def test_advance(self):
        for i in range(1, 99):
            test_car = Car(i, 0, 0, 0, 0)
            lane = Lane()
            lanes = [lane]
            lane.add_car(test_car)
            lights = [TrafficLight(100)]
            for j in range(200):
                control.advance(test_car, lane, lanes, lights, 30, 0.1)
            self.assertTrue(test_car.position < 100,
                    'Car starting at %d fail' % i)

    def test_advance_with_car_in_front(self):
        for i in range (1, 80):
            test_car_1 = Car(i, 0, 0, 0, 0)
            test_car_2 = Car(i + 19, 0, 0, 0, 0)
            lane = Lane()
            lanes = [lane]
            lane.add_car(test_car_1)
            lane.add_car(test_car_2)
            lights = [TrafficLight(100)]
            for j in range(200):
                control.advance(test_car_1, lane, lanes, lights, 30, 0.1)
                control.advance(test_car_2, lane, lanes, lights, 30, 0.1)
            self.assertTrue(test_car_1.position < 100,
                    'First car at %d fail, pos(car1) = %f, pos(car2) = %f'
                    %(i, test_car_1.position, test_car_2.position))
            self.assertTrue(test_car_2.position < 100,
                    'Second car at %d fails' % (i + 19))
            self.assertTrue(test_car_1.position <= control.rear(
                test_car_2, test_car_1.speed),
                'First car ended up further than expected'
            )

    def test_cant_change_lane_when_car_beside(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(20, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))

    def test_cant_change_lane_when_car_slightly_behind(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(15, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))

    def test_cant_change_lane_when_car_slightly_in_front(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(25, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))

    def test_cant_change_lane_when_close_to_traffic_lights(self):
	car1 = Car(98, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car1, lane1, lane2, [light]))

    def test_cant_change_to_lane_with_opposite_direction(self):
        car = Car(20, 0, 0, 10, 0)
        lane1 = Lane()
        lane2 = Lane('SOUTH')
        light = TrafficLight(100)
        self.assertFalse(control.can_change_lane(car, lane1, lane2, [light]))

    def test_can_change_lane_when_alone(self):
	car1 = Car(20, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
        light = TrafficLight(100)
        self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))

    def test_can_change_lane_when_cars_around_but_far(self):
	car1 = Car(50, 0, 0, 10, 0)
	car2 = Car(20, 0, 0, 10, 0)
	car3 = Car(70, 0, 0, 10, 0)
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane2.add_car(car2)
	lane2.add_car(car3)
        light = TrafficLight(100)
        self.assertTrue(control.can_change_lane(car1, lane1, lane2, [light]))

    def test_shouldnt_change_lane_to_go_faster_when_nothing(self):
	car1 = Car(50, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
        light = TrafficLight(100)
        self.assertFalse(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]))

    def test_shouldnt_change_lane_to_go_faster_when_no_cars_in_front(self):
	car1 = Car(10, 0, 0, 10, 0)
	car0 = Car(50, 0, 0, 10, 0)
	car2 = Car(40, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane0.add_car(car0)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]))

    def test_should_change_lane_to_go_to_faster_lane(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(30, 0, 0, 10, 0)
	car3 = Car(40, 0, 0, 10, 0)
	car4 = Car(35, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane1.add_car(car4)
	lane0.add_car(car2)
	lane2.add_car(car3)
        light = TrafficLight(100)
        self.assertEquals(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]), lane2)

    def test_should_change_lane_to_go_to_no_car_lane(self):
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(30, 0, 0, 10, 0)
	car3 = Car(60, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane1.add_car(car1)
	lane1.add_car(car3)
	lane0.add_car(car2)
        light = TrafficLight(100)
        self.assertEquals(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]), lane2)

    def test_shouldnt_change_lane_when_cant_change_lane(self):
        car0 = Car(18, 0, 0, 10, 0)
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(25, 0, 0, 10, 0)
        car3 = Car(23, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane0.add_car(car0)
	lane1.add_car(car1)
        lane1.add_car(car3)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]))

    def test_shouldnt_change_lane_when_current_lane_is_fastest(self):
        car0 = Car(30, 0, 0, 10, 0)
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(45, 0, 0, 10, 0)
        car3 = Car(50, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane0.add_car(car0)
	lane1.add_car(car1)
        lane1.add_car(car3)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]))

    def test_bus_arrived_at_stop_at_full_capacity(self):
        lane = Lane()
        stop = BusStop(lane, 30, 10)
        line = BusLine([stop], 0, 500)
        bus = Bus(line, 10, 100)
        control.bus_stop(bus, stop)
        self.assertEquals(bus.people_carried, 100)
        self.assertEquals(stop.people, 10)

    def test_bus_arrived_and_people_were_left_at_stop(self):
        lane = Lane()
        stop = BusStop(lane, 30, 10)
        line = BusLine([stop], 0, 500)
        bus = Bus(line, 10, 93)
        control.bus_stop(bus, stop)
        self.assertEquals(bus.people_carried, 100)
        self.assertEquals(stop.people, 3)

    def test_bus_arrived_and_everybody_got_on_the_bus(self):
        lane = Lane()
        stop = BusStop(lane, 30, 10)
        line = BusLine([stop], 0, 500)
        bus = Bus(line, 10, 10)
        control.bus_stop(bus, stop)
        self.assertEquals(bus.people_carried, 20)
        self.assertEquals(stop.people, 0)

    def test_appear_cars_between_two_lanes(self):
        lanes = [Lane(), Lane()]
        lights = [TrafficLight(100)]

    def test_get_target_lanes(self):
        lanes = [Lane(), Lane(), Lane(), Lane(), Lane(), Lane(), Lane(), Lane()]
        self.assertEquals(control._get_target_lanes(lanes[3], lanes, 4, 4),
            [lanes[2], None])
        self.assertEquals(control._get_target_lanes(lanes[0], lanes, 4, 4),
            [None, lanes[1]])
        self.assertEquals(control._get_target_lanes(lanes[2], lanes, 4, 4),
            [lanes[1], lanes[3]])
        self.assertEquals(control._get_target_lanes(lanes[4], lanes, 4, 4),
            [None, lanes[5]])
        self.assertEquals(control._get_target_lanes(lanes[7], lanes, 4, 4),
            [lanes[6], None])
예제 #43
0
    def test_shouldnt_change_lane_when_current_lane_is_fastest(self):
        car0 = Car(30, 0, 0, 10, 0)
	car1 = Car(20, 0, 0, 10, 0)
	car2 = Car(45, 0, 0, 10, 0)
        car3 = Car(50, 0, 0, 10, 0)
        lane0 = Lane()
	lane1 = Lane()
	lane2 = Lane()
	lane0.add_car(car0)
	lane1.add_car(car1)
        lane1.add_car(car3)
	lane2.add_car(car2)
        light = TrafficLight(100)
        self.assertFalse(control.should_change_lane_to_move_faster(car1, lane1,
            [lane0, lane2], [light]))
예제 #44
0
 def setUp(self):
     self.car = Car(200, 0, 0, 0, 0)
     self.lane = Lane()
     self.lane.add_car(self.car)
예제 #45
0
파일: tree.py 프로젝트: daveisadork/Racer
class Tree:
    def __init__(
        self,
        tree_type="pro",
        delay=0.4,
        left_lane="computer",
        right_lane="human",
        debug=False,
        perfect=0.0,
        left_rollout=0.220,
        right_rollout=0.220,
        stats=False,
        amin=1.0,
        amax=3.0,
        cmin=-0.009,
        cmax=0.115,
        auto_reset=False,
        res="480x700",
        fullscreen=False,
        hw=False,
        doublebuf=False,
    ):
        self.perfect = perfect
        self.left_rollout = left_rollout
        self.right_rollout = right_rollout
        self.amin = amin
        self.amax = amax
        self.auto_reset = auto_reset
        self.two_player = left_lane == "human" and right_lane == "human"
        self.debug = debug
        self.stats = stats
        self.delay = delay
        self.start = threading.Event()
        self.staged = threading.Event()
        self.quitting = threading.Event()
        self.tree_type = tree_type
        self.tie = []
        self.start_time = None
        self.clock = pygame.time.Clock()
        flags = 0
        if hw:
            flags = flags | pygame.HWSURFACE
        if doublebuf:
            flags = flags | pygame.DOUBLEBUF
        if fullscreen:
            resolution = (0, 0)
            flags = flags | pygame.FULLSCREEN
            pygame.mouse.set_visible(False)
        else:
            width, height = res.split("x")
            resolution = (int(width), int(height))
        self.screen = pygame.display.set_mode(resolution, flags)
        self.scale()
        self.left_lane = Lane(
            tree_type=tree_type,
            delay=delay,
            start=self.start,
            lane="left",
            computer=(left_lane == "computer"),
            perfect=perfect,
            rollout=left_rollout,
            cmin=cmin,
            cmax=cmax,
            surface=self.screen.subsurface(
                pygame.Rect(self.rect.left, self.tree_rect.top, self.rect.centerx, self.tree_rect.height)
            ),
            background=self.background,
        )
        self.right_lane = Lane(
            tree_type=tree_type,
            delay=delay,
            start=self.start,
            lane="right",
            computer=(right_lane == "computer"),
            perfect=perfect,
            rollout=right_rollout,
            cmin=cmin,
            cmax=cmax,
            surface=self.screen.subsurface(
                pygame.Rect(self.rect.centerx, self.tree_rect.top, self.rect.centerx, self.tree_rect.height)
            ),
            background=self.background,
        )
        self.lanes = {"left": self.left_lane, "right": self.right_lane}
        if self.two_player:
            self.human = None
        elif right_lane == "human":
            self.human = self.right_lane
        elif left_lane == "human":
            self.human = self.left_lane
        else:
            self.human = self.left_lane
        if self.debug:
            self.font = pygame.font.Font("assets/font.ttf", 50)
            self.fps = self.font.render("", 1, (255, 255, 255))
        clock = threading.Thread(None, self._clock, name="clock()")
        # monitor = threading.Thread(None, self.thread_monitor,
        #    name="thread_monitor()")
        clock.start()
        # monitor.start()
        self.reset()
        self.event_loop()
        clock.join()
        # monitor.join()

    def scale(self):
        self.rect = self.screen.get_rect()
        background = pygame.image.load("assets/background.png")
        background.convert()
        # background = utils.load_background()
        background_rect = background.get_rect()
        if float(self.rect.width) / float(self.rect.height) <= 1.6:
            background = pygame.transform.smoothscale(
                background, (int(round(self.rect.height * 1.6, 0)), self.rect.height)
            )
        else:
            background = pygame.transform.smoothscale(
                background, (self.rect.width, int(round(self.rect.width / 1.6, 0)))
            )
        background_rect = background.get_rect()
        temp_rect = self.rect.move(0, 0)
        temp_rect.centerx = background_rect.centerx
        temp_rect.centery = background_rect.centery
        self.background = background.subsurface(temp_rect)
        # self.vignette = utils.load_vignette()
        self.vignette = pygame.image.load("assets/vignette.png")
        self.vignette.convert_alpha()
        self.vignette = pygame.transform.smoothscale(self.vignette, (self.rect.width, self.rect.height))
        self.tree = pygame.image.load("assets/tree.png")
        self.tree.convert_alpha()
        self.tree_rect = self.tree.get_rect()
        self.tree_rect = self.tree_rect.fit(self.rect)
        self.tree = pygame.transform.smoothscale(self.tree, (self.tree_rect.width, self.tree_rect.height))
        self.tree_rect.midbottom = self.rect.midbottom
        self.background.blit(self.vignette, (0, 0))
        self.background.blit(self.tree, (self.tree_rect.left, 0))
        self.screen.blit(self.background, (0, 0))
        pygame.display.flip()

    def reset(self):
        self.tie = []
        self.start_time = None
        self.start.clear()
        self.staged.clear()
        for lane in self.lanes.values():
            lane.reset()
        if self.quitting.is_set():
            return
        threading.Thread(None, self.staging, name="staging()").start()

    def staging(self):
        while not self.quitting.is_set() and not (self.left_lane.staged.is_set() and self.right_lane.staged.is_set()):
            time.sleep(0.001)
        if self.quitting.is_set():
            return
        # The following line sets the window for the randomized delay between
        # both lanes having fully staged and the race starting.
        if self.amin == self.amax:
            autostart = self.amin
        else:
            autostart = random.randrange(self.amin * 1000.0, self.amax * 1000.0, 1) / 1000.0
        self.start_time = time.time() + autostart
        if self.left_lane.staged.is_set() and self.right_lane.staged.is_set():
            self.staged.set()
        else:
            self.reset()
            return
        while (
            time.time() < self.start_time - 0.1 and self.left_lane.staged.is_set() and self.right_lane.staged.is_set()
        ):
            time.sleep(0.001)
        if self.left_lane.staged.is_set() and self.right_lane.staged.is_set():
            threading.Thread(None, self.race, name="race()").start()
        else:
            self.reset()
            return

    def timer(self):
        left = threading.Thread(None, self.left_lane.timer, name="Left Lane timer()")
        right = threading.Thread(None, self.right_lane.timer, name="Right Lane timer()")
        if self.tree_type == "sportsman":
            green_time = self.start_time + (3 * self.delay)
        else:
            green_time = self.start_time + self.delay
        y2time = self.start_time + self.delay
        y3time = self.start_time + (self.delay * 2)
        left.start()
        right.start()
        self.start.set()
        while time.time() < self.start_time:
            continue
        self.left_lane.y1.set()
        self.right_lane.y1.set()
        if self.tree_type == "sportsman":
            while time.time() < y2time:
                continue
            self.left_lane.y2.set()
            self.right_lane.y2.set()
            while time.time() < y3time:
                continue
            self.left_lane.y3.set()
            self.right_lane.y3.set()
        while time.time() < green_time:
            continue
        self.left_lane.g.set()
        self.right_lane.g.set()
        self.left_lane.launched.wait()
        self.right_lane.launched.wait()
        left.join()
        right.join()

    def race(self):
        self.left_lane.start_time = self.right_lane.start_time = self.start_time
        self.timer()
        time.sleep(0.1)
        self.start_time = None
        # print "Left start time: %0.7f" % self.left_lane.start_time
        # print "Right start time: %0.7f" % self.right_lane.start_time
        if self.two_player:
            if self.tie[0].foul.is_set():
                self.tie[1].win()
            else:
                self.tie[0].win()
        elif self.left_lane.reaction < self.right_lane.reaction:
            if self.left_lane.foul.is_set():
                if self.right_lane.foul.is_set():
                    self.right_lane.win()
                    # print "Winner: Right Lane RT %0.3f (foul)" % self.right_lane.reaction
                    # print "Loser:  Left Lane  RT %0.3f (foul)" % self.left_lane.reaction
                self.right_lane.win()
                # print "Winner: Right Lane RT %0.3f" % self.right_lane.reaction
                # print "Loser:  Left Lane  RT %0.3f (foul)" % self.left_lane.reaction
            else:
                self.left_lane.win()
                # print "Winner: Left Lane  RT %0.3f" % self.left_lane.reaction
                # print "Loser:  Right Lane RT %0.3f" % self.right_lane.reaction
        elif self.right_lane.reaction < self.left_lane.reaction:
            if self.right_lane.foul.is_set():
                if self.left_lane.foul.is_set():
                    self.left_lane.win()
                    # print "Winner: Left Lane  RT %0.3f (foul)" % self.left_lane.reaction
                    # print "Loser:  Right Lane RT %0.3f (foul)" % self.right_lane.reaction
                self.left_lane.win()
                # print "Winner: Left Lane  RT %0.3f" % self.left_lane.reaction
                # print "Loser:  Right Lane RT %0.3f (foul)" % self.right_lane.reaction
            else:
                self.right_lane.win()
                # print "Winner: Right Lane RT %0.3f" % self.right_lane.reaction
                # print "Loser:  Left Lane  RT %0.3f" % self.left_lane.reaction
        elif self.left_lane.reaction == self.right_lane.reaction:
            for lane in self.lanes.values():
                lane.win()
        if self.stats:
            print "Round %d: Left Lane: %0.3f\tRight Lane: %0.3f" % (
                len(self.left_lane.log),
                self.left_lane.reaction,
                self.right_lane.reaction,
            )
        if self.auto_reset:
            reset = time.time() + self.auto_reset
            while time.time() < reset:
                if self.quitting.is_set():
                    return
            self.reset()

    def win(self, lane):
        print "win lane %s" % lane
        self.lanes[lane].win()

    def event_loop(self):
        pygame.event.set_allowed(None)
        pygame.event.set_allowed([KEYDOWN, KEYUP, QUIT])
        while not self.quitting.is_set():
            event = pygame.event.wait()
            if event.type == KEYDOWN and event.key in [K_m, K_z, K_SPACE]:
                if self.two_player:
                    if not (self.right_lane.pre_staged.is_set() or self.left_lane.pre_staged.is_set()):
                        if not self.auto_reset:
                            self.reset()
                    elif event.key == K_m and self.right_lane.pre_staged.is_set():
                        self.right_lane.stage()
                    elif event.key == K_z and self.left_lane.pre_staged.is_set():
                        self.left_lane.stage()
                elif event.key == K_SPACE:
                    if self.human.pre_staged.is_set():
                        self.human.stage()
                        # while pygame.key.get_pressed()[K_SPACE]:
                        #    pygame.event.pump()
                        # if self.human.staged.is_set() and self.start.is_set():
                        #    self.human.launched_time = time.time()
                        #    self.human.launched.set()
                        # else:
                        #    self.human.staged.clear()
                        #    self.human.lights[1].off()
                    elif not self.auto_reset:
                        self.reset()
            elif event.type == KEYUP and event.key in [K_m, K_z, K_SPACE]:
                if self.two_player:
                    if event.key == K_m:
                        if self.right_lane.staged.is_set() and self.start.is_set():
                            self.right_lane.launched_time = time.time()
                            self.right_lane.launched.set()
                            self.tie.append(self.right_lane)
                        else:
                            self.right_lane.staged.clear()
                            self.right_lane.lights[1].off()
                    elif event.key == K_z:
                        if self.left_lane.staged.is_set() and self.start.is_set():
                            self.left_lane.launched_time = time.time()
                            self.left_lane.launched.set()
                            self.tie.append(self.left_lane)
                        else:
                            self.left_lane.staged.clear()
                            self.left_lane.lights[1].off()
                elif event.key == K_SPACE:
                    if self.human.staged.is_set() and self.start.is_set():
                        self.human.launched_time = time.time()
                        self.human.launched.set()
                    else:
                        self.human.staged.clear()
                        self.human.lights[1].off()
            elif event.type == pygame.QUIT or (event.type == KEYDOWN and event.key in [K_ESCAPE, K_q]):
                self.quit()
            # print event

    def draw(self):
        self.left_lane.draw()
        self.right_lane.draw()
        dirty = []
        if self.left_lane.dirty:
            dirty += self.left_lane.dirty_rects
            self.left_lane.dirty = False
            self.left_lane.dirty_rects = []
        if self.right_lane.dirty:
            dirty += self.right_lane.dirty_rects
            self.right_lane.dirty = False
            self.right_lane.dirty_rects = []
        if self.debug:
            self.fps = self.font.render("%0.1f" % self.clock.get_fps(), 1, (255, 255, 255))
            fps_rect = self.fps.get_rect()
            fps_rect.top = 10
            fps_rect.left = 10
            self.screen.blit(self.background, (fps_rect.left, fps_rect.top), fps_rect)
            self.screen.blit(self.fps, (fps_rect.left, fps_rect.top))
            dirty.append(fps_rect)
        if dirty:
            pygame.display.update(dirty)

    def _clock(self):
        while not self.quitting.is_set():
            self.clock.tick()
            self.draw()

    def thread_monitor(self):
        if not self.debug:
            return
        last_count = 0
        while not self.quitting.is_set():
            if threading.active_count() == last_count:
                continue
            else:
                last_count = threading.active_count()
            print "\nActive threads:"
            for thread in sorted(threading.enumerate(), key=threading.Thread.getName):
                print "  " + thread.name

    def print_stats(self):
        for lane in self.lanes.values():
            if lane.log:
                print lane.lane, "stats:"
                best = None
                worst = None
                for react in lane.log:
                    if not best and not worst:
                        worst = best = react
                    if react < best and react >= self.delay:
                        best = react
                    if react > best and best < self.delay:
                        best = react
                    if react > worst:
                        worst = react
                print "\tBest: %0.3f" % best
                print "\tWorst: %0.3f" % worst
                print "\tAverage: %0.3f" % round(sum(lane.log) / len(lane.log), 3)

    def quit(self):
        self.quitting.set()
        self.reset()
        if self.stats:
            self.print_stats()
        pygame.quit()