Exemple #1
0
  def runTest(self):
    schedule = self.SimpleSchedule()
    stop1 = schedule.stops["stop1"]
    stop2 = schedule.stops["stop2"]
    stop3 = schedule.stops["stop3"]

    # Set shape_dist_traveled
    trip = schedule.trips["CITY1"]
    trip.ClearStopTimes()
    trip.AddStopTime(stop1, stop_time="12:00:00", shape_dist_traveled=0)
    trip.AddStopTime(stop2, stop_time="12:00:45", shape_dist_traveled=500)
    trip.AddStopTime(stop3, stop_time="12:02:30", shape_dist_traveled=1500)
    trip.shape_id = "shape1"

    # Add a valid shape for the trip to the current schedule.
    shape = transitfeed.Shape("shape1")
    shape.AddPoint(48.2, 1.00, 0)
    shape.AddPoint(48.2, 1.01, 500)
    shape.AddPoint(48.2, 1.03, 1500)
    shape.max_distance = 1500
    schedule.AddShapeObject(shape)

    # The schedule should validate with no problems.
    self.ExpectNoProblems(schedule)

    # Delete a stop latitude. This should not crash validation.
    stop1.stop_lat = None
    self.ValidateAndExpectMissingValue(schedule, "stop_lat")
Exemple #2
0
  def runTest(self):
    schedule = self.SimpleSchedule()

    shape = transitfeed.Shape("shape_1")
    shape.AddPoint(36.425288, -117.133162, 0)
    shape.AddPoint(36.424288, -117.143142, 1)
    schedule.AddShapeObject(shape)

    trip = schedule.GetRoute("054C").AddTrip(trip_id="054C-00")
    trip.shape_id = "shape_1"

    # Stop 1 is only 600 meters away from shape, which is allowed.
    stop = transitfeed.Stop(36.425288, -117.139162, "Demo Stop 1", "STOP1")
    schedule.AddStopObject(stop)
    trip.AddStopTime(stop, arrival_time="5:11:00", departure_time="5:12:00",
                     stop_sequence=0, shape_dist_traveled=0)
    # Stop 2 is more than 1000 meters away from shape, which is not allowed.
    stop = transitfeed.Stop(36.424288, -117.158142, "Demo Stop 2", "STOP2")
    schedule.AddStopObject(stop)
    trip.AddStopTime(stop, arrival_time="5:15:00", departure_time="5:16:00",
                     stop_sequence=1, shape_dist_traveled=1)

    schedule.Validate(self.problems)
    e = self.accumulator.PopException('StopTooFarFromShapeWithDistTraveled')
    self.assertTrue(e.FormatProblem().find('Demo Stop 2') != -1)
    self.assertTrue(e.FormatProblem().find('1344 meters away') != -1)
    self.accumulator.AssertNoMoreExceptions()
Exemple #3
0
  def runTest(self):
    schedule = self.SimpleSchedule()

    shape = transitfeed.Shape("shape_1")
    shape.AddPoint(36.425288, -117.133162, 0)
    shape.AddPoint(36.424288, -117.133142, 1)
    schedule.AddShapeObject(shape)

    trip = schedule.GetRoute("054C").AddTrip(trip_id="054C-00")
    trip.shape_id = "shape_1"

    stop = transitfeed.Stop(36.425288, -117.133162, "Demo Stop 1", "STOP1")
    schedule.AddStopObject(stop)
    trip.AddStopTime(stop, arrival_time="5:11:00", departure_time="5:12:00",
                     stop_sequence=0, shape_dist_traveled=0)
    stop = transitfeed.Stop(36.424288, -117.133142, "Demo Stop 2", "STOP2")
    schedule.AddStopObject(stop)
    trip.AddStopTime(stop, arrival_time="5:15:00", departure_time="5:16:00",
                     stop_sequence=1, shape_dist_traveled=1)

    stop = transitfeed.Stop(36.423288, -117.133122, "Demo Stop 3", "STOP3")
    schedule.AddStopObject(stop)
    trip.AddStopTime(stop, arrival_time="5:18:00", departure_time="5:19:00",
                     stop_sequence=2, shape_dist_traveled=2)
    self.accumulator.AssertNoMoreExceptions()
    schedule.Validate(self.problems)
    e = self.accumulator.PopException('OtherProblem')
    self.assertMatchesRegex('shape_dist_traveled=2', e.FormatProblem())
    self.accumulator.AssertNoMoreExceptions()

    # Error if the distance decreases.
    shape.AddPoint(36.421288, -117.133132, 2)
    stop = transitfeed.Stop(36.421288, -117.133122, "Demo Stop 4", "STOP4")
    schedule.AddStopObject(stop)
    stoptime = transitfeed.StopTime(self.problems, stop,
                                    arrival_time="5:29:00",
                                    departure_time="5:29:00", stop_sequence=3,
                                    shape_dist_traveled=1.7)
    trip.AddStopTimeObject(stoptime, schedule=schedule)
    self.accumulator.AssertNoMoreExceptions()
    schedule.Validate(self.problems)
    e = self.accumulator.PopException('InvalidValue')
    self.assertMatchesRegex('stop STOP4 has', e.FormatProblem())
    self.assertMatchesRegex('shape_dist_traveled=1.7', e.FormatProblem())
    self.assertMatchesRegex('distance was 2.0.', e.FormatProblem())
    self.assertEqual(e.type, transitfeed.TYPE_ERROR)
    self.accumulator.AssertNoMoreExceptions()

    # Warning if distance remains the same between two stop_times
    stoptime.shape_dist_traveled = 2.0
    trip.ReplaceStopTimeObject(stoptime, schedule=schedule)
    schedule.Validate(self.problems)
    e = self.accumulator.PopException('InvalidValue')
    self.assertMatchesRegex('stop STOP4 has', e.FormatProblem())
    self.assertMatchesRegex('shape_dist_traveled=2.0', e.FormatProblem())
    self.assertMatchesRegex('distance was 2.0.', e.FormatProblem())
    self.assertEqual(e.type, transitfeed.TYPE_WARNING)
    self.accumulator.AssertNoMoreExceptions()
Exemple #4
0
 def testCreateLineStringForShape(self):
   shape = transitfeed.Shape('shape')
   shape.AddPoint(1.0, 1.0)
   shape.AddPoint(2.0, 4.0)
   shape.AddPoint(3.0, 9.0)
   element = self.kmlwriter._CreateLineStringForShape(self.parent, shape)
   self.assertEqual(_ElementToString(element),
                    '<LineString><tessellate>1</tessellate>'
                    '<coordinates>%f,%f %f,%f %f,%f</coordinates>'
                    '</LineString>' % (1.0, 1.0, 4.0, 2.0, 9.0, 3.0))
    def runTest(self):
        shape = transitfeed.Shape('TEST')
        repr(shape)  # shouldn't crash
        self.ValidateAndExpectOtherProblem(shape)  # no points!

        self.ExpectFailedAdd(shape, 36.905019, -116.763207, -1,
                             'shape_dist_traveled', -1)

        shape.add_point(36.915760, -116.751709, 0, self.problems)
        shape.add_point(36.905018, -116.763206, 5, self.problems)
        shape.validate(self.problems)

        shape.shape_id = None
        self.ValidateAndExpectMissingValue(shape, 'shape_id')
        shape.shape_id = 'TEST'

        self.ExpectFailedAdd(shape, 91, -116.751709, 6, 'shape_pt_lat', 91)
        self.ExpectFailedAdd(shape, -91, -116.751709, 6, 'shape_pt_lat', -91)

        self.ExpectFailedAdd(shape, 36.915760, -181, 6, 'shape_pt_lon', -181)
        self.ExpectFailedAdd(shape, 36.915760, 181, 6, 'shape_pt_lon', 181)

        self.ExpectFailedAdd(shape, 0.5, -0.5, 6, 'shape_pt_lat', 0.5)
        self.ExpectFailedAdd(shape, 0, 0, 6, 'shape_pt_lat', 0)

        # distance decreasing is bad, but staying the same is OK
        shape.add_point(36.905019, -116.763206, 4, self.problems)
        e = self.accumulator.pop_exception('InvalidValue')
        self.assertMatchesRegex('Each subsequent point', e.format_problem())
        self.assertMatchesRegex('distance was 5.000000.', e.format_problem())
        self.accumulator.assert_no_more_exceptions()

        shape.add_point(36.925019, -116.764206, 6, self.problems)
        self.accumulator.assert_no_more_exceptions()

        shapepoint = transitfeed.ShapePoint('TEST', 36.915760, -116.7156, 6, 8)
        shape.add_shape_point_object_unsorted(shapepoint, self.problems)
        shapepoint = transitfeed.ShapePoint('TEST', 36.915760, -116.7156, 5,
                                            10)
        shape.add_shape_point_object_unsorted(shapepoint, self.problems)
        e = self.accumulator.pop_exception('InvalidValue')
        self.assertMatchesRegex('Each subsequent point', e.format_problem())
        self.assertMatchesRegex('distance was 8.000000.', e.format_problem())
        self.accumulator.assert_no_more_exceptions()

        shapepoint = transitfeed.ShapePoint('TEST', 36.915760, -116.7156, 6,
                                            11)
        shape.add_shape_point_object_unsorted(shapepoint, self.problems)
        e = self.accumulator.pop_exception('InvalidValue')
        self.assertMatchesRegex('The sequence number 6 occurs ',
                                e.format_problem())
        self.assertMatchesRegex('once in shape TEST.', e.format_problem())
        self.accumulator.assert_no_more_exceptions()
Exemple #6
0
  def loadShapes(self):
    logger.info("Loading Shapes")

    usedShapes = set([trip['shape_id'] for trip in self.schedule.GetTripList()])

    for shape_id in usedShapes:
      shape_obj = self.db.query(ShapePath).filter_by(shape_id=shape_id).first()
      shape_path = shape_obj.shape_path_array
      shape = transitfeed.Shape(shape_id=shape_id)
      for pt in shape_path:
        shape.AddPoint(lon=pt[0], lat=pt[1])
      self.schedule.AddShapeObject(shape)
    def runTest(self):
        shape = transitfeed.Shape("TEST")
        repr(shape)  # shouldn't crash
        self.ValidateAndExpectOtherProblem(shape)  # no points!

        self.ExpectFailedAdd(
            shape, 36.905019, -116.763207, -1, "shape_dist_traveled", -1
        )

        shape.AddPoint(36.915760, -116.751709, 0, self.problems)
        shape.AddPoint(36.905018, -116.763206, 5, self.problems)
        shape.Validate(self.problems)

        shape.shape_id = None
        self.ValidateAndExpectMissingValue(shape, "shape_id")
        shape.shape_id = "TEST"

        self.ExpectFailedAdd(shape, 91, -116.751709, 6, "shape_pt_lat", 91)
        self.ExpectFailedAdd(shape, -91, -116.751709, 6, "shape_pt_lat", -91)

        self.ExpectFailedAdd(shape, 36.915760, -181, 6, "shape_pt_lon", -181)
        self.ExpectFailedAdd(shape, 36.915760, 181, 6, "shape_pt_lon", 181)

        self.ExpectFailedAdd(shape, 0.5, -0.5, 6, "shape_pt_lat", 0.5)
        self.ExpectFailedAdd(shape, 0, 0, 6, "shape_pt_lat", 0)

        # distance decreasing is bad, but staying the same is OK
        shape.AddPoint(36.905019, -116.763206, 4, self.problems)
        e = self.accumulator.PopException("InvalidValue")
        self.assertMatchesRegex("Each subsequent point", e.FormatProblem())
        self.assertMatchesRegex("distance was 5.000000.", e.FormatProblem())
        self.accumulator.AssertNoMoreExceptions()

        shape.AddPoint(36.925019, -116.764206, 6, self.problems)
        self.accumulator.AssertNoMoreExceptions()

        shapepoint = transitfeed.ShapePoint("TEST", 36.915760, -116.7156, 6, 8)
        shape.AddShapePointObjectUnsorted(shapepoint, self.problems)
        shapepoint = transitfeed.ShapePoint("TEST", 36.915760, -116.7156, 5, 10)
        shape.AddShapePointObjectUnsorted(shapepoint, self.problems)
        e = self.accumulator.PopException("InvalidValue")
        self.assertMatchesRegex("Each subsequent point", e.FormatProblem())
        self.assertMatchesRegex("distance was 8.000000.", e.FormatProblem())
        self.accumulator.AssertNoMoreExceptions()

        shapepoint = transitfeed.ShapePoint("TEST", 36.915760, -116.7156, 6, 11)
        shape.AddShapePointObjectUnsorted(shapepoint, self.problems)
        e = self.accumulator.PopException("InvalidValue")
        self.assertMatchesRegex("The sequence number 6 occurs ", e.FormatProblem())
        self.assertMatchesRegex("once in shape TEST.", e.FormatProblem())
        self.accumulator.AssertNoMoreExceptions()
Exemple #8
0
 def add_shape(schedule, route_id, osm_r):
     """
     create GTFS shape and return shape_id to add on GTFS trip
     """
     import transitfeed
     shape_id = str(route_id)
     try:
         schedule.GetShape(shape_id)
     except KeyError:
         shape = transitfeed.Shape(shape_id)
         for point in osm_r.shape:
             shape.AddPoint(
                 lat=float(point["lat"]), lon=float(point["lon"]))
         schedule.AddShapeObject(shape)
     return shape_id
Exemple #9
0
    def _add_shape_to_feed(self, feed, shape_id, itinerary):
        """
        Create GTFS shape and return shape_id to add on GTFS trip
        """
        shape_id = str(shape_id)

        # Only add a shape if there isn't one with this shape_id
        try:
            feed.GetShape(shape_id)
        except KeyError:
            shape = transitfeed.Shape(shape_id)
            for point in itinerary.shape:
                shape.AddPoint(lat=float(point["lat"]),
                               lon=float(point["lon"]))
            feed.AddShapeObject(shape)
        return shape_id
Exemple #10
0
    def ParseDom(self, dom, feed):
        """
    Parses the given kml dom tree and updates the Google transit feed object.

    Args:
      dom - kml dom tree
      feed - an instance of Schedule class to be updated
    """
        shape_num = 0
        for node in dom.getElementsByTagName('Placemark'):
            p = self.ParsePlacemark(node)
            if p.IsPoint():
                (lon, lat) = p.coordinates[0]
                m = self.stopNameRe.search(p.name)
                feed.AddStop(lat, lon, m.group(1))
            elif p.IsLine():
                shape_num = shape_num + 1
                shape = transitfeed.Shape("kml_shape_" + str(shape_num))
                for (lon, lat) in p.coordinates:
                    shape.AddPoint(lat, lon)
                feed.AddShapeObject(shape)
Exemple #11
0
    def ConvertPlacemarkToShape(self, p, feed):
        shape = transitfeed.Shape(p.name)
        for (lon, lat) in p.coordinates:
            shape.AddPoint(lat, lon)

        try:
            existing_shape = feed.GetShape(p.name)

            # If the existing shape has the same points, we don't need to add a new
            # shape.
            if existing_shape == shape:
                return

            # If the shape has different points, we need to modify our shape id so as
            # to avoid duplication.
            shape.shape_id += '_%d' % len(feed.GetShapeList())

        except KeyError:
            # No existing shape with that id, so no worries.
            pass

        feed.AddShapeObject(shape)
Exemple #12
0
    def setUp(self):
        utm17 = pyproj.Proj(proj='utm', zone=17, ellps='WGS84')

        lc = {k: utm17(*v) for k, v in rawCoords.items()}
        G = nx.MultiDiGraph()
        for e1, e2 in edgeNodes:
            G.add_edge(e1, e2, geom=LineString([lc[e1], lc[e2]]))
            G.add_edge(e2, e1, geom=LineString([lc[e2], lc[e1]]))
        self.G = G

        schedule = transitfeed.Schedule()
        schedule.AddAgency("Mike's bus", "http://google.com",
                           "America/Toronto")
        stop1 = schedule.AddStop(lng=-80.46, lat=43.45, name="Dummy stop 1")
        stop2 = schedule.AddStop(lng=-80.47, lat=43.45, name="Dummy stop 2")

        self.paths = {
            'shape1': [(85, 80, 0), (80, 90, 0), (90, 100, 0), (100, 91, 0),
                       (91, 81, 0), (81, 92, 0), (92, 89, 0)],
            'shape2': [(84, 80, 0), (80, 90, 0), (90, 100, 0), (100, 91, 0),
                       (91, 81, 0), (81, 92, 0), (92, 101, 0)],
            'shape3': [(84, 80, 0), (80, 90, 0), (90, 100, 0), (100, 91, 0),
                       (91, 81, 0), (81, 92, 0), (92, 89, 0)],
            'shape4': [(85, 80, 0), (80, 90, 0), (90, 100, 0), (100, 91, 0),
                       (91, 81, 0), (81, 92, 0), (92, 101, 0)],
            'shape5': [(102, 92, 0), (92, 81, 0), (81, 91, 0), (91, 100, 0),
                       (100, 90, 0), (90, 80, 0), (80, 85, 0), (85, 70, 0),
                       (70, 80, 0)],
            'shape6': [(94, 91, 0), (91, 100, 0), (100, 90, 0), (90, 80, 0),
                       (80, 71, 0), (71, 85, 0), (85, 80, 0)],
            'shape7': [(89, 92, 0), (92, 81, 0), (81, 91, 0), (91, 93, 0),
                       (93, 82, 0), (82, 91, 0), (91, 83, 0), (83, 94, 0),
                       (94, 91, 0), (91, 100, 0)]
        }
        colours = {
            'shape1': 'ff0000',
            'shape2': '00ff00',
            'shape3': '0000ff',
            'shape4': 'ff00ff',
            'shape5': '669900',
            'shape6': '996600',
            'shape7': '990066',
            'shape8': '660099',
            'shape9': '009966',
            'shape10': '006699',
        }

        for p in self.paths:
            route = schedule.AddRoute(short_name="{}".format(p),
                                      long_name="Route {}".format(p),
                                      route_type="Bus",
                                      route_id='{}'.format(p))
            route.route_color = colours[
                p]  #"{:06x}".format(random.randint(0, 0xFFFFFF))
            schedule.AddShapeObject(transitfeed.Shape(p))
            trip = route.AddTrip(schedule, headsign="To Downtown")
            trip.AddStopTime(stop1, stop_time='09:00:00')
            trip.AddStopTime(stop2, stop_time='09:15:00')
            trip.shape_id = p

        self.schedule = schedule
Exemple #13
0
    def add_trips_by_day(self, feed, line, service, route, horarios, day):

        # check if we even have service
        if horarios is None or len(horarios) == 0:
            return

        if isinstance(route, Line):
            # recurse into "Ida" and "Volta" routes
            for sub_route in route.get_itineraries():
                sub_route.duration = route.duration
                self.add_trips_by_day(feed, line, service, sub_route, horarios, day)
            return

        # have at least two stops
        if len(route.stops) < 2:
            sys.stderr.write("Skipping Route, has no stops: " + str(route) + "\n")
            return

        # check if we have a match for the first stop
        key = self.match_first_stops(route, horarios.keys())

        if key is None:
            # Do not print debug output here, because already done in route.match_first_stops()
            return

        if route.route_id == DEBUG_ROUTE:
            print "\n\n\n" + str(route)
            print day + " - " + key

        # get shape id
        shape_id = str(route.route_id)
        try:
            feed.GetShape(shape_id)
        except KeyError:
            shape = transitfeed.Shape(shape_id)
            for point in route.shape:
                shape.AddPoint(lat=float(point["lat"]), lon=float(point["lon"]))
            feed.AddShapeObject(shape)

        if len(horarios) > 1 and route.line is None:
            sys.stderr.write(
                "Route should have a master: [" + route.route_id + "] " + str(
                    route.osm_url) + "\n")

        for time_group in horarios[key]:
            for time_point in time_group:
                # parse first departure time
                start_time = datetime.strptime(time_point[0], "%H:%M")
                start_time = str(start_time.time())

                # calculate last arrival time for GTFS
                start_sec = transitfeed.TimeToSecondsSinceMidnight(start_time)
                factor = 1
                if len(horarios) > 1 and route.line is None:
                    # since this route has only one instead of two trips, double the duration
                    factor = 2
                end_sec = start_sec + route.duration.seconds * factor
                end_time = transitfeed.FormatSecondsSinceMidnight(end_sec)

                # TODO handle options
                # opts = time_point[1]

                trip = line.AddTrip(feed, headsign=route.name, service_period=service)
                # add empty attributes to make navitia happy
                trip.block_id = ""
                trip.wheelchair_accessible = ""
                trip.bikes_allowed = ""
                trip.shape_id = shape_id
                trip.direction_id = ""
                if route.route_id == DEBUG_ROUTE:
                    print "ADD TRIP " + str(trip.trip_id) + ":"
                self.add_trip_stops(feed, trip, route, start_time, end_time)

                # interpolate times, because Navitia can not handle this itself
                Helper.interpolate_stop_times(trip)
def main(key_columns):
    print('Parsing shapefile(s)...')
    graph = shapelib.PolyGraph()
    for arg in args:
        print('  ' + arg)
        add_shapefile(arg, graph, key_columns)

    if options.extra_shapes:
        add_extra_shapes(options.extra_shapes, graph)

    print('Loading GTFS from %s...' % options.source_gtfs)
    schedule = transitfeed.Loader(options.source_gtfs).load()
    shape_count = 0
    pattern_count = 0

    verbosity = options.verbosity

    print('Matching shapes to trips...')
    for route in schedule.get_route_list():
        print('Processing route', route.route_short_name)
        patterns = route.get_pattern_id_trip_dict()
        for pattern_id, trips in patterns.items():
            pattern_count += 1
            pattern = trips[0].get_pattern()

            poly_points = [
                shapelib.Point.from_lat_lng(p.stop_lat, p.stop_lon)
                for p in pattern
            ]
            if verbosity >= 2:
                print("\npattern %d, %d points:" %
                      (pattern_id, len(poly_points)))
                for i, (stop, point) in enumerate(zip(pattern, poly_points)):
                    print("Stop %d '%s': %s" %
                          (i + 1, stop.stop_name, point.to_lat_lng()))

            # First, try to find polys that run all the way from
            # the start of the trip to the end.
            matches = graph.find_matching_polys(poly_points[0],
                                                poly_points[-1],
                                                options.max_distance)
            if not matches:
                # Try to find a path through the graph, joining
                # multiple edges to find a path that covers all the
                # points in the trip.  Some shape files are structured
                # this way, with a polyline for each segment between
                # stations instead of a polyline covering an entire line.
                shortest_path = graph.find_shortest_multi_point_path(
                    poly_points, options.max_distance, verbosity=verbosity)
                if shortest_path:
                    matches = [shortest_path]
                else:
                    matches = []

            pattern_poly = shapelib.Poly(poly_points)
            shape_match = get_matching_shape(pattern_poly,
                                             trips[0],
                                             matches,
                                             options.max_distance,
                                             verbosity=verbosity)
            if shape_match:
                shape_count += 1
                # Rename shape for readability.
                shape_match = shapelib.Poly(points=shape_match.get_points(),
                                            name="shape_%d" % shape_count)
                for trip in trips:
                    try:
                        shape = schedule.get_shape(shape_match.get_name())
                    except KeyError:
                        shape = transitfeed.Shape(shape_match.get_name())
                        for point in shape_match.get_points():
                            (lat, lng) = point.to_lat_lng()
                            shape.add_point(lat, lng)
                        schedule.add_shape_object(shape)
                    trip.shape_id = shape.shape_id

    print("Matched %d shapes out of %d patterns" %
          (shape_count, pattern_count))
    schedule.write_google_transit_feed(options.dest_gtfs)
Exemple #15
0
def main(key_cols):
    print 'Parsing shapefile(s)...'
    graph = shapelib.PolyGraph()
    for arg in args:
        print '  ' + arg
        AddShapefile(arg, graph, key_cols)

    if options.extra_shapes:
        AddExtraShapes(options.extra_shapes, graph)

    print 'Loading GTFS from %s...' % options.source_gtfs
    schedule = transitfeed.Loader(options.source_gtfs).Load()
    shape_count = 0
    pattern_count = 0

    verbosity = options.verbosity

    print 'Matching shapes to trips...'
    for route in schedule.GetRouteList():
        print 'Processing route', route.route_short_name
        patterns = route.GetPatternIdTripDict()
        for pattern_id, trips in patterns.iteritems():
            pattern_count += 1
            pattern = trips[0].GetPattern()

            poly_points = [
                shapelib.Point.FromLatLng(p.stop_lat, p.stop_lon)
                for p in pattern
            ]
            if verbosity >= 2:
                print "\npattern %d, %d points:" % (pattern_id,
                                                    len(poly_points))
                for i, (stop, point) in enumerate(zip(pattern, poly_points)):
                    print "Stop %d '%s': %s" % (i + 1, stop.stop_name,
                                                point.ToLatLng())

            # First, try to find polys that run all the way from
            # the start of the trip to the end.
            matches = graph.FindMatchingPolys(poly_points[0], poly_points[-1],
                                              options.max_distance)
            if not matches:
                # Try to find a path through the graph, joining
                # multiple edges to find a path that covers all the
                # points in the trip.  Some shape files are structured
                # this way, with a polyline for each segment between
                # stations instead of a polyline covering an entire line.
                shortest_path = graph.FindShortestMultiPointPath(
                    poly_points, options.max_distance, verbosity=verbosity)
                if shortest_path:
                    matches = [shortest_path]
                else:
                    matches = []

            pattern_poly = shapelib.Poly(poly_points)
            shape_match = GetMatchingShape(pattern_poly,
                                           trips[0],
                                           matches,
                                           options.max_distance,
                                           verbosity=verbosity)
            if shape_match:
                shape_count += 1
                # Rename shape for readability.
                shape_match = shapelib.Poly(points=shape_match.GetPoints(),
                                            name="shape_%d" % shape_count)
                for trip in trips:
                    try:
                        shape = schedule.GetShape(shape_match.GetName())
                    except KeyError:
                        shape = transitfeed.Shape(shape_match.GetName())
                        for point in shape_match.GetPoints():
                            (lat, lng) = point.ToLatLng()
                            shape.AddPoint(lat, lng)
                        schedule.AddShapeObject(shape)
                    trip.shape_id = shape.shape_id

    print "Matched %d shapes out of %d patterns" % (shape_count, pattern_count)
    schedule.WriteGoogleTransitFeed(options.dest_gtfs)
Exemple #16
0
stop_425 = schedule.AddStop(stop_id="425",
                            name="Town and Country Dr. near Giant",
                            lat="38.309055",
                            lng="-77.42897")
stop_420 = schedule.AddStop(stop_id="420",
                            name="Ferry Rd. and Town and Country Dr.",
                            lat="38.296783",
                            lng="-77.422602")
stop_108 = schedule.AddStop(stop_id="108",
                            name="Dixon and Charles St.",
                            lat="38.293858",
                            lng="-77.456569")

# D1 Shape

shape_d1 = transitfeed.Shape("shape_d1")
shape_d1.AddPoint(lat="38.298318", lon="-77.456132")
shape_d1.AddPoint(lat="38.29797", lon="-77.457208")
shape_d1.AddPoint(lat="38.294347", lon="-77.456577")
shape_d1.AddPoint(lat="38.28375", lon="-77.43654")
shape_d1.AddPoint(lat="38.297955", lon="-77.446622")
shape_d1.AddPoint(lat="38.305928", lon="-77.452731")
shape_d1.AddPoint(lat="38.310067", lon="-77.448175")
shape_d1.AddPoint(lat="38.313291", lon="-77.450801")
shape_d1.AddPoint(lat="38.337279", lon="-77.485423")
shape_d1.AddPoint(lat="38.337167", lon="-77.485917")
shape_d1.AddPoint(lat="38.33553", lon="-77.482431")
shape_d1.AddPoint(lat="38.317363", lon="-77.456062")
shape_d1.AddPoint(lat="38.327251", lon="-77.439217")
shape_d1.AddPoint(lat="38.32585", lon="-77.432881")
shape_d1.AddPoint(lat="38.31813", lon="-77.432036")
    def runTest(self):
        accumulator = util.RecordingProblemAccumulator(
            self, ignore_types=("ExpirationDate", ))
        problems = transitfeed.ProblemReporter(accumulator)
        schedule = transitfeed.Schedule(problem_reporter=problems)
        agency = transitfeed.Agency()
        agency.agency_id = "DTA"
        agency.agency_name = "Demo Transit Authority"
        agency.agency_url = "http://google.com"
        agency.agency_timezone = "America/Los_Angeles"
        agency.agency_lang = 'en'
        # Test that unknown columns, such as agency_mission, are preserved
        agency.agency_mission = "Get You There"
        schedule.AddAgencyObject(agency)

        routes = []
        route_data = [("AB", "DTA", "10", "Airport - Bullfrog", 3),
                      ("BFC", "DTA", "20", "Bullfrog - Furnace Creek Resort",
                       3),
                      ("STBA", "DTA", "30", "Stagecoach - Airport Shuttle", 3),
                      ("CITY", "DTA", "40", "City", 3),
                      ("AAMV", "DTA", "50", "Airport - Amargosa Valley", 3)]

        for route_entry in route_data:
            route = transitfeed.Route()
            (route.route_id, route.agency_id, route.route_short_name,
             route.route_long_name, route.route_type) = route_entry
            routes.append(route)
            schedule.AddRouteObject(route)

        shape_data = [
            (36.915760, -116.751709),
            (36.905018, -116.763206),
            (36.902134, -116.777969),
            (36.904091, -116.788185),
            (36.883602, -116.814537),
            (36.874523, -116.795593),
            (36.873302, -116.786491),
            (36.869202, -116.784241),
            (36.868515, -116.784729),
        ]

        shape = transitfeed.Shape("BFC1S")
        for (lat, lon) in shape_data:
            shape.AddPoint(lat, lon)
        schedule.AddShapeObject(shape)

        week_period = transitfeed.ServicePeriod()
        week_period.service_id = "FULLW"
        week_period.start_date = "20070101"
        week_period.end_date = "20071231"
        week_period.SetWeekdayService()
        week_period.SetWeekendService()
        week_period.SetDateHasService("20070604", False)
        schedule.AddServicePeriodObject(week_period)

        weekend_period = transitfeed.ServicePeriod()
        weekend_period.service_id = "WE"
        weekend_period.start_date = "20070101"
        weekend_period.end_date = "20071231"
        weekend_period.SetWeekendService()
        schedule.AddServicePeriodObject(weekend_period)

        stops = []
        stop_data = [
            ("FUR_CREEK_RES", "Furnace Creek Resort (Demo)", 36.425288,
             -117.133162, "zone-a", "1234"),
            ("BEATTY_AIRPORT", "Nye County Airport (Demo)", 36.868446,
             -116.784682, "zone-a", "1235"),
            ("BULLFROG", "Bullfrog (Demo)", 36.88108, -116.81797, "zone-b",
             "1236"),
            ("STAGECOACH", "Stagecoach Hotel & Casino (Demo)", 36.915682,
             -116.751677, "zone-c", "1237"),
            ("NADAV", "North Ave / D Ave N (Demo)", 36.914893, -116.76821, "",
             ""),
            ("NANAA", "North Ave / N A Ave (Demo)", 36.914944, -116.761472, "",
             ""),
            ("DADAN", "Doing AVe / D Ave N (Demo)", 36.909489, -116.768242, "",
             ""),
            ("EMSI", "E Main St / S Irving St (Demo)", 36.905697, -116.76218,
             "", ""),
            ("AMV", "Amargosa Valley (Demo)", 36.641496, -116.40094, "", ""),
        ]
        for stop_entry in stop_data:
            stop = transitfeed.Stop()
            (stop.stop_id, stop.stop_name, stop.stop_lat, stop.stop_lon,
             stop.zone_id, stop.stop_code) = stop_entry
            schedule.AddStopObject(stop)
            stops.append(stop)
        # Add a value to an unknown column and make sure it is preserved
        schedule.GetStop("BULLFROG").stop_sound = "croak!"

        trip_data = [
            ("AB", "FULLW", "AB1", "to Bullfrog", "0", "1", None),
            ("AB", "FULLW", "AB2", "to Airport", "1", "2", None),
            ("STBA", "FULLW", "STBA", "Shuttle", None, None, None),
            ("CITY", "FULLW", "CITY1", None, "0", None, None),
            ("CITY", "FULLW", "CITY2", None, "1", None, None),
            ("BFC", "FULLW", "BFC1", "to Furnace Creek Resort", "0", "1",
             "BFC1S"),
            ("BFC", "FULLW", "BFC2", "to Bullfrog", "1", "2", None),
            ("AAMV", "WE", "AAMV1", "to Amargosa Valley", "0", None, None),
            ("AAMV", "WE", "AAMV2", "to Airport", "1", None, None),
            ("AAMV", "WE", "AAMV3", "to Amargosa Valley", "0", None, None),
            ("AAMV", "WE", "AAMV4", "to Airport", "1", None, None),
        ]

        trips = []
        for trip_entry in trip_data:
            trip = transitfeed.Trip()
            (trip.route_id, trip.service_id, trip.trip_id, trip.trip_headsign,
             trip.direction_id, trip.block_id, trip.shape_id) = trip_entry
            trips.append(trip)
            schedule.AddTripObject(trip)

        stop_time_data = {
            "STBA":
            [("6:00:00", "6:00:00", "STAGECOACH", None, None, None, None),
             ("6:20:00", "6:20:00", "BEATTY_AIRPORT", None, None, None, None)],
            "CITY1":
            [("6:00:00", "6:00:00", "STAGECOACH", 1.34, 0, 0, "stop 1"),
             ("6:05:00", "6:07:00", "NANAA", 2.40, 1, 2, "stop 2"),
             ("6:12:00", "6:14:00", "NADAV", 3.0, 2, 2, "stop 3"),
             ("6:19:00", "6:21:00", "DADAN", 4, 2, 2, "stop 4"),
             ("6:26:00", "6:28:00", "EMSI", 5.78, 2, 3, "stop 5")],
            "CITY2": [("6:28:00", "6:28:00", "EMSI", None, None, None, None),
                      ("6:35:00", "6:37:00", "DADAN", None, None, None, None),
                      ("6:42:00", "6:44:00", "NADAV", None, None, None, None),
                      ("6:49:00", "6:51:00", "NANAA", None, None, None, None),
                      ("6:56:00", "6:58:00", "STAGECOACH", None, None, None,
                       None)],
            "AB1":
            [("8:00:00", "8:00:00", "BEATTY_AIRPORT", None, None, None, None),
             ("8:10:00", "8:15:00", "BULLFROG", None, None, None, None)],
            "AB2":
            [("12:05:00", "12:05:00", "BULLFROG", None, None, None, None),
             ("12:15:00", "12:15:00", "BEATTY_AIRPORT", None, None, None, None)
             ],
            "BFC1": [
                ("8:20:00", "8:20:00", "BULLFROG", None, None, None, None),
                ("9:20:00", "9:20:00", "FUR_CREEK_RES", None, None, None, None)
            ],
            "BFC2":
            [("11:00:00", "11:00:00", "FUR_CREEK_RES", None, None, None, None),
             ("12:00:00", "12:00:00", "BULLFROG", None, None, None, None)],
            "AAMV1": [("8:00:00", "8:00:00", "BEATTY_AIRPORT", None, None,
                       None, None),
                      ("9:00:00", "9:00:00", "AMV", None, None, None, None)],
            "AAMV2": [("10:00:00", "10:00:00", "AMV", None, None, None, None),
                      ("11:00:00", "11:00:00", "BEATTY_AIRPORT", None, None,
                       None, None)],
            "AAMV3": [("13:00:00", "13:00:00", "BEATTY_AIRPORT", None, None,
                       None, None),
                      ("14:00:00", "14:00:00", "AMV", None, None, None, None)],
            "AAMV4": [("15:00:00", "15:00:00", "AMV", None, None, None, None),
                      ("16:00:00", "16:00:00", "BEATTY_AIRPORT", None, None,
                       None, None)],
        }

        for trip_id, stop_time_list in stop_time_data.items():
            for stop_time_entry in stop_time_list:
                (arrival_time, departure_time, stop_id, shape_dist_traveled,
                 pickup_type, drop_off_type, stop_headsign) = stop_time_entry
                trip = schedule.GetTrip(trip_id)
                stop = schedule.GetStop(stop_id)
                trip.AddStopTime(stop,
                                 arrival_time=arrival_time,
                                 departure_time=departure_time,
                                 shape_dist_traveled=shape_dist_traveled,
                                 pickup_type=pickup_type,
                                 drop_off_type=drop_off_type,
                                 stop_headsign=stop_headsign)

        self.assertEqual(
            0,
            schedule.GetTrip("CITY1").GetStopTimes()[0].pickup_type)
        self.assertEqual(
            1,
            schedule.GetTrip("CITY1").GetStopTimes()[1].pickup_type)

        headway_data = [
            ("STBA", "6:00:00", "22:00:00", 1800),
            ("CITY1", "6:00:00", "7:59:59", 1800),
            ("CITY2", "6:00:00", "7:59:59", 1800),
            ("CITY1", "8:00:00", "9:59:59", 600),
            ("CITY2", "8:00:00", "9:59:59", 600),
            ("CITY1", "10:00:00", "15:59:59", 1800),
            ("CITY2", "10:00:00", "15:59:59", 1800),
            ("CITY1", "16:00:00", "18:59:59", 600),
            ("CITY2", "16:00:00", "18:59:59", 600),
            ("CITY1", "19:00:00", "22:00:00", 1800),
            ("CITY2", "19:00:00", "22:00:00", 1800),
        ]

        headway_trips = {}
        for headway_entry in headway_data:
            (trip_id, start_time, end_time, headway) = headway_entry
            headway_trips[trip_id] = []  # adding to set to check later
            trip = schedule.GetTrip(trip_id)
            trip.AddFrequency(start_time, end_time, headway, 0, problems)
        for trip_id in headway_trips:
            headway_trips[trip_id] = \
                schedule.GetTrip(trip_id).GetFrequencyTuples()

        fare_data = [
            ("p", 1.25, "USD", 0, 0),
            ("a", 5.25, "USD", 0, 0),
        ]

        fares = []
        for fare_entry in fare_data:
            fare = transitfeed.FareAttribute(fare_entry[0], fare_entry[1],
                                             fare_entry[2], fare_entry[3],
                                             fare_entry[4])
            fares.append(fare)
            schedule.AddFareAttributeObject(fare)

        fare_rule_data = [
            ("p", "AB", "zone-a", "zone-b", None),
            ("p", "STBA", "zone-a", None, "zone-c"),
            ("p", "BFC", None, "zone-b", "zone-a"),
            ("a", "AAMV", None, None, None),
        ]

        for fare_id, route_id, orig_id, dest_id, contains_id in fare_rule_data:
            rule = transitfeed.FareRule(fare_id=fare_id,
                                        route_id=route_id,
                                        origin_id=orig_id,
                                        destination_id=dest_id,
                                        contains_id=contains_id)
            schedule.AddFareRuleObject(rule, problems)

        schedule.Validate(problems)
        accumulator.AssertNoMoreExceptions()
        schedule.WriteGoogleTransitFeed(self.tempfilepath)

        read_schedule = \
            transitfeed.Loader(self.tempfilepath, problems=problems,
                               extra_validation=True).Load()
        e = accumulator.PopException("UnrecognizedColumn")
        self.assertEqual(e.file_name, "agency.txt")
        self.assertEqual(e.column_name, "agency_mission")
        e = accumulator.PopException("UnrecognizedColumn")
        self.assertEqual(e.file_name, "stops.txt")
        self.assertEqual(e.column_name, "stop_sound")
        accumulator.AssertNoMoreExceptions()

        self.assertEqual(1, len(read_schedule.GetAgencyList()))
        self.assertEqual(agency, read_schedule.GetAgency(agency.agency_id))

        self.assertEqual(len(routes), len(read_schedule.GetRouteList()))
        for route in routes:
            self.assertEqual(route, read_schedule.GetRoute(route.route_id))

        self.assertEqual(2, len(read_schedule.GetServicePeriodList()))
        self.assertEqual(
            week_period,
            read_schedule.GetServicePeriod(week_period.service_id))
        self.assertEqual(
            weekend_period,
            read_schedule.GetServicePeriod(weekend_period.service_id))

        self.assertEqual(len(stops), len(read_schedule.GetStopList()))
        for stop in stops:
            self.assertEqual(stop, read_schedule.GetStop(stop.stop_id))
        self.assertEqual("croak!",
                         read_schedule.GetStop("BULLFROG").stop_sound)

        self.assertEqual(len(trips), len(read_schedule.GetTripList()))
        for trip in trips:
            self.assertEqual(trip, read_schedule.GetTrip(trip.trip_id))

        for trip_id in headway_trips:
            self.assertEqual(
                headway_trips[trip_id],
                read_schedule.GetTrip(trip_id).GetFrequencyTuples())

        for trip_id, stop_time_list in stop_time_data.items():
            trip = read_schedule.GetTrip(trip_id)
            read_stoptimes = trip.GetStopTimes()
            self.assertEqual(len(read_stoptimes), len(stop_time_list))
            for stop_time_entry, read_stoptime in zip(stop_time_list,
                                                      read_stoptimes):
                (arrival_time, departure_time, stop_id, shape_dist_traveled,
                 pickup_type, drop_off_type, stop_headsign) = stop_time_entry
                self.assertEqual(stop_id, read_stoptime.stop_id)
                self.assertEqual(read_schedule.GetStop(stop_id),
                                 read_stoptime.stop)
                self.assertEqualTimeString(arrival_time,
                                           read_stoptime.arrival_time)
                self.assertEqualTimeString(departure_time,
                                           read_stoptime.departure_time)
                self.assertEqual(shape_dist_traveled,
                                 read_stoptime.shape_dist_traveled)
                self.assertEqualWithDefault(pickup_type,
                                            read_stoptime.pickup_type, 0)
                self.assertEqualWithDefault(drop_off_type,
                                            read_stoptime.drop_off_type, 0)
                self.assertEqualWithDefault(stop_headsign,
                                            read_stoptime.stop_headsign, '')

        self.assertEqual(len(fares), len(read_schedule.GetFareAttributeList()))
        for fare in fares:
            self.assertEqual(fare,
                             read_schedule.GetFareAttribute(fare.fare_id))

        read_fare_rules_data = []
        for fare in read_schedule.GetFareAttributeList():
            for rule in fare.GetFareRuleList():
                self.assertEqual(fare.fare_id, rule.fare_id)
                read_fare_rules_data.append(
                    (fare.fare_id, rule.route_id, rule.origin_id,
                     rule.destination_id, rule.contains_id))

        fare_rule_data.sort()
        read_fare_rules_data.sort()
        self.assertEqual(len(read_fare_rules_data), len(fare_rule_data))
        for rf, f in zip(read_fare_rules_data, fare_rule_data):
            self.assertEqual(rf, f)

        self.assertEqual(1, len(read_schedule.GetShapeList()))
        self.assertEqual(shape, read_schedule.GetShape(shape.shape_id))