Exemple #1
0
def AddShapefile(shapefile, graph, key_cols):
    """
  Adds shapes found in the given shape filename to the given polyline
  graph object.
  """
    ds = ogr.Open(shapefile)
    layer = ds.GetLayer(0)

    for i in range(0, len(layer)):
        feature = layer.GetFeature(i)

        geometry = feature.GetGeometryRef()

        if key_cols:
            key_list = []
            for col in key_cols:
                key_list.append(str(feature.GetField(col)))
            shape_id = '-'.join(key_list)
        else:
            shape_id = '%s-%d' % (shapefile, i)

        poly = shapelib.Poly(name=shape_id)
        for j in range(0, geometry.GetPointCount()):
            (lat, lng) = (round(geometry.GetY(j),
                                15), round(geometry.GetX(j), 15))
            poly.AddPoint(shapelib.Point.FromLatLng(lat, lng))
        graph.AddPoly(poly)

    return graph
Exemple #2
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)
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 #4
0
def ShapeToPoly(shape):
    poly = shapelib.Poly(name=shape.shape_id)
    for lat, lng, distance in shape.points:
        point = shapelib.Point.FromLatLng(round(lat, 15), round(lng, 15))
        poly.AddPoint(point)
    return poly
def shape_to_poly(shape):
    poly = shapelib.Poly(name=shape.shape_id)
    for lat, lng, distance in shape.points:
        point = shapelib.Point.from_lat_lng(round(lat, 15), round(lng, 15))
        poly.add_point(point)
    return poly