public void TestTripAB1()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // find stops.
            var finder = new StopAtShapesFinder();
            var stopAtShapes = finder.Find(feed, "AB1");

            // validate/test.
            Assert.IsNotNull(stopAtShapes);
            Assert.AreEqual(2, stopAtShapes.Count);
            Assert.AreEqual("BEATTY_AIRPORT", stopAtShapes[0].StopId);
            Assert.AreEqual(1, stopAtShapes[0].ShapePointSequence);
            Assert.AreEqual(0, stopAtShapes[0].StopOffset);
            Assert.AreEqual("AB1", stopAtShapes[0].TripId);
            Assert.AreEqual("BULLFROG", stopAtShapes[1].StopId);
            Assert.AreEqual(4, stopAtShapes[1].ShapePointSequence);
            Assert.AreEqual(0, stopAtShapes[1].StopOffset);
            Assert.AreEqual("AB1", stopAtShapes[1].TripId);
        }
        public void ParseCalendarDates()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            reader.DateTimeReader = (dateString) =>
            {
                var year = int.Parse(dateString.Substring(0, 4));
                var month = int.Parse(dateString.Substring(4, 2));
                var day = int.Parse(dateString.Substring(6, 2));
                return new System.DateTime(year, month, day);
            };

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("calendar_dates")));

            // test result.
            Assert.IsNotNull(feed.CalendarDates);
            var calendarDates = new List<CalendarDate>(feed.CalendarDates);

            // @ 1: service_id,date,exception_type
            // @ 2: FULLW,20070604,2
            int idx = 0;
            Assert.AreEqual("FULLW", calendarDates[idx].ServiceId);
            Assert.AreEqual(new System.DateTime(2007, 06, 04), calendarDates[idx].Date);
            Assert.AreEqual(ExceptionType.Removed, calendarDates[idx].ExceptionType);
        }
Beispiel #3
0
		private static void TestGtfs()
		{
			// create the reader.
			var reader = new GTFSReader<GTFSFeed>(strict: false);

			// execute the reader.
			var feed = reader.Read(new GTFSDirectorySource(new DirectoryInfo(Paths.GOOD_FEED_PATH)));
		}
Beispiel #4
0
		private static void RunExample()
		{
			// create the reader.
			var reader = new GTFSReader<GTFSFeed>(strict:false);

			// execute the reader.
			GTFSFeed feed = reader.Read(new GTFSDirectorySource(new DirectoryInfo("feeds/lirr")));
			Console.WriteLine(feed);

			feed = reader.Read(new GTFSDirectorySource(new DirectoryInfo("feeds/subway")));
			Console.WriteLine(feed);

			Console.Read();
		}
        public void TestMissingRoute()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // remove.
            feed.Routes.Remove("AB");

            // validate.
            Assert.IsFalse(GTFSFeedValidation.Validate(feed));
        }
        public void TestFilterNoStops()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // create the filter.
            var filter = new GTFSFeedStopsFilter((x) =>
            {
                return true;
            });

            // execute filter.
            var filtered = filter.Filter(feed);
            Assert.IsTrue(GTFSFeedValidation.Validate(filtered));
            GTFSAssert.AreEqual(feed, filtered);
        }
Beispiel #7
0
        public void ParseTrips()
        {
            // create the reader.
            GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>(false);

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("trips")));

            // test result.
            Assert.IsNotNull(feed.Trips);
            var trips = feed.Trips.ToList();

            Assert.AreEqual(11, trips.Count);

            // @ 1: route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id
            // @ 2: AB,FULLW,AB1,to Bullfrog,0,1,shape_1
            int idx = 0;

            Assert.AreEqual("AB", trips[idx].RouteId);
            Assert.AreEqual("FULLW", trips[idx].ServiceId);
            Assert.AreEqual("AB1", trips[idx].Id);
            Assert.AreEqual("to Bullfrog", trips[idx].Headsign);
            Assert.AreEqual(DirectionType.OneDirection, trips[idx].Direction);
            Assert.AreEqual("1", trips[idx].BlockId);
            Assert.AreEqual("shape_1", trips[idx].ShapeId);

            // @ 10: BFC,FULLW,BFC1,to Furnace Creek Resort,0,1,shape_6
            idx = 5;
            Assert.AreEqual("BFC", trips[idx].RouteId);
            Assert.AreEqual("FULLW", trips[idx].ServiceId);
            Assert.AreEqual("BFC1", trips[idx].Id);
            Assert.AreEqual("to Furnace Creek Resort", trips[idx].Headsign);
            Assert.AreEqual(DirectionType.OneDirection, trips[idx].Direction);
            Assert.AreEqual("1", trips[idx].BlockId);
            Assert.AreEqual("shape_6", trips[idx].ShapeId);
        }
Beispiel #8
0
        public void ParseRoutesWithoutDescription()
        {
            // create the reader.
            var reader = new GTFSReader <GTFSFeed>();

            // build the source
            var source = new List <IGTFSSourceFile>
            {
                new GTFSSourceFileStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("GTFS.Test.sample_feed.agency.txt"), "agency"),
                new GTFSSourceFileStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("GTFS.Test.other_feed.routes.no_desc.txt"), "routes")
            };


            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("routes")));

            // test result.
            Assert.IsNotNull(feed.Routes);
            var routes = feed.Routes.ToList();

            Assert.IsTrue(routes.All(x => x.Description == null));
        }
Beispiel #9
0
        public void ParseFrequencies()
        {
            // create the reader.
            GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>(false);

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("frequencies")));

            // test result.
            Assert.IsNotNull(feed.Frequencies);
            var frequencies = feed.Frequencies.ToList();

            Assert.AreEqual(11, frequencies.Count);

            // @ 1: trip_id,start_time,end_time,headway_secs
            // @ 2: STBA,6:00:00,22:00:00,1800

            // @ 1: route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id
            // @ 2: AB,FULLW,AB1,to Bullfrog,0,1,shape_1
            int idx = 0;

            Assert.AreEqual("STBA", frequencies[idx].TripId);
            Assert.AreEqual("6:00:00", frequencies[idx].StartTime);
            Assert.AreEqual("22:00:00", frequencies[idx].EndTime);
            Assert.AreEqual("1800", frequencies[idx].HeadwaySecs);
            Assert.AreEqual(null, frequencies[idx].ExactTimes);

            // @ 10: CITY2,16:00:00,18:59:59,600
            idx = 8;
            Assert.AreEqual("CITY2", frequencies[idx].TripId);
            Assert.AreEqual("16:00:00", frequencies[idx].StartTime);
            Assert.AreEqual("18:59:59", frequencies[idx].EndTime);
            Assert.AreEqual("600", frequencies[idx].HeadwaySecs);
            Assert.AreEqual(null, frequencies[idx].ExactTimes);
        }
Beispiel #10
0
        public void ParseFareAttributes()
        {
            // create the reader.
            GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("fare_attributes")));

            // test result.
            Assert.IsNotNull(feed.FareAttributes);
            var fareAttributes = feed.FareAttributes.ToList();

            Assert.AreEqual(2, fareAttributes.Count);

            //fare_id,price,currency_type,payment_method,transfers,transfer_duration

            //p,1.25,USD,0,0,
            int idx = 0;

            Assert.AreEqual("p", fareAttributes[idx].FareId);
            Assert.AreEqual("1.25", fareAttributes[idx].Price);
            Assert.AreEqual("USD", fareAttributes[idx].CurrencyType);
            Assert.AreEqual(PaymentMethodType.OnBoard, fareAttributes[idx].PaymentMethod);
            Assert.AreEqual(0, fareAttributes[idx].Transfers);
            Assert.AreEqual(string.Empty, fareAttributes[idx].TransferDuration);

            //a,5.25,USD,0,0,
            idx = 1;
            Assert.AreEqual("a", fareAttributes[idx].FareId);
            Assert.AreEqual("5.25", fareAttributes[idx].Price);
            Assert.AreEqual("USD", fareAttributes[idx].CurrencyType);
            Assert.AreEqual(PaymentMethodType.OnBoard, fareAttributes[idx].PaymentMethod);
            Assert.AreEqual(0, fareAttributes[idx].Transfers);
            Assert.AreEqual(string.Empty, fareAttributes[idx].TransferDuration);
        }
        public void ParseCalendarDates()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("calendar_dates")));

            // test result.
            Assert.IsNotNull(feed.CalendarDates);
            var calendarDates = new List<CalendarDate>(feed.CalendarDates);
            Assert.AreEqual(1, calendarDates.Count);

            // @ 1: service_id,date,exception_type
            // @ 2: FULLW,20070604,2
            int idx = 0;
            Assert.AreEqual("FULLW", calendarDates[idx].ServiceId);
            Assert.AreEqual(new System.DateTime(2007, 06, 04), calendarDates[idx].Date);
            Assert.AreEqual(ExceptionType.Removed, calendarDates[idx].ExceptionType);
        }
        public void ParseAgencies()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("agency")));

            // test result.
            Assert.IsNotNull(feed.Agencies);
            var agencies = new List<Agency>(feed.Agencies);
            Assert.AreEqual(1, agencies.Count);
            Assert.AreEqual(null, agencies[0].FareURL);
            Assert.AreEqual("DTA", agencies[0].Id);
            Assert.AreEqual(null, agencies[0].LanguageCode);
            Assert.AreEqual("Demo Transit Authority", agencies[0].Name);
            Assert.AreEqual(null, agencies[0].Phone);
            Assert.AreEqual("America/Los_Angeles", agencies[0].Timezone);
            Assert.AreEqual("http://google.com", agencies[0].URL);
        }
Beispiel #13
0
        public void ParseStops()
        {
            // create the reader.
            GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("stops")));

            // test result.
            Assert.IsNotNull(feed.Stops);
            var stops = feed.Stops.ToList();

            Assert.AreEqual(9, stops.Count);

            // @ 1: stop_id,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url
            // @ 2: FUR_CREEK_RES,Furnace Creek Resort (Demo),,36.425288,-117.133162,,
            int idx = 0;

            Assert.AreEqual("FUR_CREEK_RES", stops[idx].Id);
            Assert.AreEqual("Furnace Creek Resort (Demo)", stops[idx].Name);
            Assert.AreEqual(string.Empty, stops[idx].Description);
            Assert.AreEqual(36.425288, stops[idx].Latitude);
            Assert.AreEqual(-117.133162, stops[idx].Longitude);
            Assert.AreEqual(string.Empty, stops[idx].Url);

            // @ 10: AMV,Amargosa Valley (Demo),,36.641496,-116.40094,,
            idx = 8;
            Assert.AreEqual("AMV", stops[idx].Id);
            Assert.AreEqual("Amargosa Valley (Demo)", stops[idx].Name);
            Assert.AreEqual(string.Empty, stops[idx].Description);
            Assert.AreEqual(36.641496, stops[idx].Latitude);
            Assert.AreEqual(-116.40094, stops[idx].Longitude);
            Assert.AreEqual(string.Empty, stops[idx].Url);
        }
Beispiel #14
0
        public void ParseAgencies()
        {
            // create the reader.
            GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("agency")));

            // test result.
            Assert.IsNotNull(feed.Agencies);
            var agencies = new List <Agency>(feed.Agencies);

            Assert.AreEqual(1, agencies.Count);
            Assert.AreEqual(null, agencies[0].FareURL);
            Assert.AreEqual("DTA", agencies[0].Id);
            Assert.AreEqual(null, agencies[0].LanguageCode);
            Assert.AreEqual("Demo Transit Authority", agencies[0].Name);
            Assert.AreEqual(null, agencies[0].Phone);
            Assert.AreEqual("America/Los_Angeles", agencies[0].Timezone);
            Assert.AreEqual("http://google.com", agencies[0].URL);
        }
Beispiel #15
0
        public void DisposingDirectorySourceClosesSourceFiles()
        {
            var directoryInfo = new DirectoryInfo(Path.Combine(AssemblyLocation.FullName, "folder-feed"));

            try
            {
                using (var gtfsDirectorySource = new GTFSDirectorySource(directoryInfo))
                {
                    var reader = new GTFSReader <GTFSFeed>();
                    reader.Read(gtfsDirectorySource);
                }
            }
            catch (GTFSExceptionBase)
            {
                // ignore our exceptions
            }

            var agencyFile = Path.Combine(directoryInfo.FullName, "agency.txt");

            using (File.OpenWrite(agencyFile))
            {
                // do nothing
            }
        }
        public void ParseRoutes()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("routes")));

            // test result.
            Assert.IsNotNull(feed.Routes);
            var routes = feed.Routes.ToList();
            Assert.AreEqual(5, routes.Count);

            //route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color

            //AB,DTA,10,Airport - Bullfrog,,3,,,
            int idx = 0;
            Assert.AreEqual("AB", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("10", routes[idx].ShortName);
            Assert.AreEqual("Airport - Bullfrog", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(-3932017, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //BFC,DTA,20,Bullfrog - Furnace Creek Resort,,3,,,
            idx = 1;
            Assert.AreEqual("BFC", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("20", routes[idx].ShortName);
            Assert.AreEqual("Bullfrog - Furnace Creek Resort", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(-1, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //STBA,DTA,30,Stagecoach - Airport Shuttle,,3,,,
            idx = 2;
            Assert.AreEqual("STBA", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("30", routes[idx].ShortName);
            Assert.AreEqual("Stagecoach - Airport Shuttle", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(null, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //CITY,DTA,40,City,,3,,,
            idx = 3;
            Assert.AreEqual("CITY", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("40", routes[idx].ShortName);
            Assert.AreEqual("City", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(null, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //AAMV,DTA,50,Airport - Amargosa Valley,,3,,,
            idx = 4;
            Assert.AreEqual("AAMV", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("50", routes[idx].ShortName);
            Assert.AreEqual("Airport - Amargosa Valley", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(null, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);
        }
        public void ParseFareRules()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("fare_rules")));

            // test result.
            Assert.IsNotNull(feed.FareRules);
            var fareRules = feed.FareRules.ToList();
            Assert.AreEqual(4, fareRules.Count);

            // fare_id,route_id,origin_id,destination_id,contains_id

            //p,AB,,,
            int idx = 0;
            Assert.AreEqual("AB", fareRules[idx].RouteId);
            Assert.AreEqual("p", fareRules[idx].FareId);
            Assert.AreEqual(string.Empty, fareRules[idx].OriginId);
            Assert.AreEqual(string.Empty, fareRules[idx].DestinationId);
            Assert.AreEqual(string.Empty, fareRules[idx].ContainsId);

            //p,STBA,,,
            idx = 1;
            Assert.AreEqual("STBA", fareRules[idx].RouteId);
            Assert.AreEqual("p", fareRules[idx].FareId);
            Assert.AreEqual(string.Empty, fareRules[idx].OriginId);
            Assert.AreEqual(string.Empty, fareRules[idx].DestinationId);
            Assert.AreEqual(string.Empty, fareRules[idx].ContainsId);

            //p,BFC,,,
            idx = 2;
            Assert.AreEqual("BFC", fareRules[idx].RouteId);
            Assert.AreEqual("p", fareRules[idx].FareId);
            Assert.AreEqual(string.Empty, fareRules[idx].OriginId);
            Assert.AreEqual(string.Empty, fareRules[idx].DestinationId);
            Assert.AreEqual(string.Empty, fareRules[idx].ContainsId);

            //a,AAMV,,,
            idx = 3;
            Assert.AreEqual("AAMV", fareRules[idx].RouteId);
            Assert.AreEqual("a", fareRules[idx].FareId);
            Assert.AreEqual(string.Empty, fareRules[idx].OriginId);
            Assert.AreEqual(string.Empty, fareRules[idx].DestinationId);
            Assert.AreEqual(string.Empty, fareRules[idx].ContainsId);
        }
        public void ParseFrequencies()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>(false);

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("frequencies")));

            // test result.
            Assert.IsNotNull(feed.Frequencies);
            var frequencies = feed.Frequencies.ToList();
            Assert.AreEqual(11, frequencies.Count);

            // @ 1: trip_id,start_time,end_time,headway_secs
            // @ 2: STBA,6:00:00,22:00:00,1800

            // @ 1: route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id
            // @ 2: AB,FULLW,AB1,to Bullfrog,0,1,shape_1
            int idx = 0;
            Assert.AreEqual("STBA", frequencies[idx].TripId);
            Assert.AreEqual("6:00:00", frequencies[idx].StartTime);
            Assert.AreEqual("22:00:00", frequencies[idx].EndTime);
            Assert.AreEqual("1800", frequencies[idx].HeadwaySecs);
            Assert.AreEqual(null, frequencies[idx].ExactTimes);

            // @ 10: CITY2,16:00:00,18:59:59,600
            idx = 8;
            Assert.AreEqual("CITY2", frequencies[idx].TripId);
            Assert.AreEqual("16:00:00", frequencies[idx].StartTime);
            Assert.AreEqual("18:59:59", frequencies[idx].EndTime);
            Assert.AreEqual("600", frequencies[idx].HeadwaySecs);
            Assert.AreEqual(null, frequencies[idx].ExactTimes);
        }
        /// <summary>
        /// Loads a new instance.
        /// </summary>
        /// <param name="apiConfiguration"></param>
        /// <param name="instanceConfiguration"></param>
        /// <returns></returns>
        private static bool LoadInstance(ApiConfiguration apiConfiguration, InstanceConfiguration instanceConfiguration)
        {
            try
            {
                // get graph configuration.
                var graph       = instanceConfiguration.Graph;
                var type        = instanceConfiguration.Type;
                var format      = instanceConfiguration.Format;
                var vehicleName = instanceConfiguration.Vehicle;

                try
                {
                    // create routing instance.
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                                                    string.Format("Creating {0} instance...", instanceConfiguration.Name));
                    Router router = null;
                    RouterDataSource <Edge> data = null;

                    var graphFile = new FileInfo(graph);
                    switch (type)
                    {
                    case "raw":
                        switch (format)
                        {
                        case "osm-xml":
                            using (var graphStream = graphFile.OpenRead())
                            {
                                data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                    new XmlOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                            }
                            break;

                        case "osm-pbf":
                            using (var graphStream = graphFile.OpenRead())
                            {
                                data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                    new PBFOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                            }
                            break;

                        default:
                            throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                                              format, type));
                        }
                        break;

                    case "contracted":
                        // check for GTFS-feeds and give warning if they are there.
                        if (instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                        {     // ... oeps a feed and a contracted network are not supported for now.
                            OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                                            "NotSupported: GTFS and contracted graphs cannot (yet) be combined.");
                        }

                        switch (format)
                        {
                        case "osm-xml":
                            if (string.IsNullOrWhiteSpace(vehicleName))
                            {         // invalid configuration.
                                throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                            }
                            using (var graphStream = graphFile.OpenRead())
                            {
                                var graphSource = new XmlOsmStreamSource(graphStream);
                                router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                            }
                            break;

                        case "osm-pbf":
                            if (string.IsNullOrWhiteSpace(vehicleName))
                            {         // invalid configuration.
                                throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                            }
                            using (var graphStream = graphFile.OpenRead())
                            {
                                var graphSource = new PBFOsmStreamSource(graphStream);
                                router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                            }
                            break;

                        case "flat":
                            var mobileRoutingSerializer = new CHEdgeSerializer();
                            // keep this stream open, it is used while routing!
                            var mobileGraphInstance = mobileRoutingSerializer.Deserialize(graphFile.OpenRead(), false);
                            router = Router.CreateCHFrom(mobileGraphInstance, new CHRouter(), new OsmRoutingInterpreter());
                            break;

                        default:
                            throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                                              format, type));
                        }
                        break;

                    case "simple":
                        switch (format)
                        {
                        case "flat":
                            using (var graphStream = graphFile.OpenRead())
                            {
                                var routingSerializer = new RoutingDataSourceSerializer();
                                data   = routingSerializer.Deserialize(graphStream);
                                router = Router.CreateFrom(data, new Dykstra(), new OsmRoutingInterpreter());
                            }
                            break;

                        default:
                            throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                                              format, type));
                        }
                        break;
                    }

                    if (instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                    {     // transit-data use the transit-api.
                        if (instanceConfiguration.Feeds.Count > 1)
                        { // for now only one feed at a time is supported.
                            OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                                            "NotSupported: Only one GTFS-feed at a time is supported.");
                        }

                        var feed                    = instanceConfiguration.Feeds[0];
                        var reader                  = new GTFSReader <GTFSFeed>(false);
                        var gtfsFeed                = reader.Read <GTFSFeed>(new GTFSDirectorySource(feed.Path));
                        var connectionsDb           = new GTFSConnectionsDb(gtfsFeed);
                        var multimodalConnectionsDb = new MultimodalConnectionsDb(data, connectionsDb,
                                                                                  new OsmRoutingInterpreter(), Vehicle.Pedestrian);

                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name,
                                                                                 new MultimodalApi(multimodalConnectionsDb));
                        }
                    }
                    else
                    { // no transit-data just use the regular routing api implementation.
                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name, router);
                        }
                    }

                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                                                    string.Format("Instance {0} created successfully!", instanceConfiguration.Name));
                }
                catch (Exception ex)
                {
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Error,
                                                    string.Format("Exception occured while creating instance {0}:{1}",
                                                                  instanceConfiguration.Name, ex.ToInvariantString()));
                    throw;
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public void ParseFareAttributes()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("fare_attributes")));

            // test result.
            Assert.IsNotNull(feed.FareAttributes);
            var fareAttributes = feed.FareAttributes.ToList();
            Assert.AreEqual(2, fareAttributes.Count);

            //fare_id,price,currency_type,payment_method,transfers,transfer_duration

            //p,1.25,USD,0,0,
            int idx = 0;
            Assert.AreEqual("p", fareAttributes[idx].FareId);
            Assert.AreEqual("1.25", fareAttributes[idx].Price);
            Assert.AreEqual("USD", fareAttributes[idx].CurrencyType);
            Assert.AreEqual(PaymentMethodType.OnBoard, fareAttributes[idx].PaymentMethod);
            Assert.AreEqual(0, fareAttributes[idx].Transfers);
            Assert.AreEqual(string.Empty, fareAttributes[idx].TransferDuration);

            //a,5.25,USD,0,0,
            idx = 1;
            Assert.AreEqual("a", fareAttributes[idx].FareId);
            Assert.AreEqual("5.25", fareAttributes[idx].Price);
            Assert.AreEqual("USD", fareAttributes[idx].CurrencyType);
            Assert.AreEqual(PaymentMethodType.OnBoard, fareAttributes[idx].PaymentMethod);
            Assert.AreEqual(0, fareAttributes[idx].Transfers);
            Assert.AreEqual(string.Empty, fareAttributes[idx].TransferDuration);
        }
        public void ParseStopTimes()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>(false);

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("stop_times")));

            // test result.
            Assert.IsNotNull(feed.StopTimes);
            var stopTimes = feed.StopTimes.ToList();
            Assert.AreEqual(28, stopTimes.Count);

            // @ 1: trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_time,shape_dist_traveled
            // @ SORTED: AAMV1,8:00:00,8:00:00,BEATTY_AIRPORT,1
            int idx = 0;
            Assert.AreEqual("AAMV1", stopTimes[idx].TripId);
            Assert.AreEqual(new TimeOfDay() { Hours = 8 }, stopTimes[idx].ArrivalTime);
            Assert.AreEqual(new TimeOfDay() { Hours = 8 }, stopTimes[idx].DepartureTime);
            Assert.AreEqual("BEATTY_AIRPORT", stopTimes[idx].StopId);
            Assert.AreEqual(1, stopTimes[idx].StopSequence);
            Assert.AreEqual(null, stopTimes[idx].StopHeadsign);
            Assert.AreEqual(null, stopTimes[idx].PickupType);
            Assert.AreEqual(null, stopTimes[idx].DropOffType);
            Assert.AreEqual(null, stopTimes[idx].ShapeDistTravelled);

            // @ SORTED: STBA,6:20:00,6:20:00,BEATTY_AIRPORT,2,,,,
            idx = 27;
            Assert.AreEqual("STBA", stopTimes[idx].TripId);
            Assert.AreEqual(new TimeOfDay() { Hours = 6, Minutes = 20 }, stopTimes[idx].ArrivalTime);
            Assert.AreEqual(new TimeOfDay() { Hours = 6, Minutes = 20 }, stopTimes[idx].DepartureTime);
            Assert.AreEqual("BEATTY_AIRPORT", stopTimes[idx].StopId);
            Assert.AreEqual(2, stopTimes[idx].StopSequence);
            Assert.AreEqual(string.Empty, stopTimes[idx].StopHeadsign);
            Assert.AreEqual(null, stopTimes[idx].PickupType);
            Assert.AreEqual(null, stopTimes[idx].DropOffType);
            Assert.AreEqual(string.Empty, stopTimes[idx].ShapeDistTravelled);
        }
        public void ParseTrips()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>(false);

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("trips")));

            // test result.
            Assert.IsNotNull(feed.Trips);
            var trips = feed.Trips.ToList();
            Assert.AreEqual(11, trips.Count);

            // @ 1: route_id,service_id,trip_id,trip_headsign,direction_id,block_id,shape_id
            // @ 2: AB,FULLW,AB1,to Bullfrog,0,1,shape_1
            int idx = 0;
            Assert.AreEqual("AB", trips[idx].RouteId);
            Assert.AreEqual("FULLW", trips[idx].ServiceId);
            Assert.AreEqual("AB1", trips[idx].Id);
            Assert.AreEqual("to Bullfrog", trips[idx].Headsign);
            Assert.AreEqual(DirectionType.OneDirection, trips[idx].Direction);
            Assert.AreEqual("1", trips[idx].BlockId);
            Assert.AreEqual("shape_1", trips[idx].ShapeId);

            // @ 10: BFC,FULLW,BFC1,to Furnace Creek Resort,0,1,shape_6
            idx = 5;
            Assert.AreEqual("BFC", trips[idx].RouteId);
            Assert.AreEqual("FULLW", trips[idx].ServiceId);
            Assert.AreEqual("BFC1", trips[idx].Id);
            Assert.AreEqual("to Furnace Creek Resort", trips[idx].Headsign);
            Assert.AreEqual(DirectionType.OneDirection, trips[idx].Direction);
            Assert.AreEqual("1", trips[idx].BlockId);
            Assert.AreEqual("shape_6", trips[idx].ShapeId);
        }
        public void TestFilterOneStop()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // create list of object id's that should remain after filtering.
            var expectedTripIds = new string[] { "AB1", "AB2", "BFC1", "BFC2" };
            var expectedStopIds = new string[] { "BULLFROG", "BEATTY_AIRPORT", "FUR_CREEK_RES" };
            var expectedRouteIds = new string[] { "AB", "BFC" };
            var expectedShapeIds = new string[] { "shape_1", "shape_2", "shape_6", "shape_7" };

            // create the filter.
            var filter = new GTFSFeedStopsFilter((x) =>
            {
                return x.Id == "BULLFROG";
            });

            // execute filter.
            var filtered = filter.Filter(feed);
            Assert.IsTrue(GTFSFeedValidation.Validate(filtered));

            // test for trips/stops.
            foreach (var stop in filtered.Stops)
            {
                Assert.Contains(stop.Id, expectedStopIds);
            }
            foreach(var trip in filtered.Trips)
            {
                Assert.Contains(trip.Id, expectedTripIds);
            }
            foreach (var route in filtered.Routes)
            {
                Assert.Contains(route.Id, expectedRouteIds);
            }
            foreach (var shape in filtered.Shapes)
            {
                Assert.Contains(shape.Id, expectedShapeIds);
            }

            // create the filter.
            var stopIds = new HashSet<string>();
            stopIds.Add("BULLFROG");
            filter = new GTFSFeedStopsFilter(stopIds);

            // execute filter.
            filtered = filter.Filter(feed);
            Assert.IsTrue(GTFSFeedValidation.Validate(filtered));

            // test for trips/stops.
            foreach (var stop in filtered.Stops)
            {
                Assert.Contains(stop.Id, expectedStopIds);
            }
            foreach (var trip in filtered.Trips)
            {
                Assert.Contains(trip.Id, expectedTripIds);
            }
            foreach (var route in filtered.Routes)
            {
                Assert.Contains(route.Id, expectedRouteIds);
            }
            foreach (var shape in filtered.Shapes)
            {
                Assert.Contains(shape.Id, expectedShapeIds);
            }
        }
Beispiel #24
0
        public void TestFilterOneStop()
        {
            // create the reader.
            var reader = new GTFSReader <GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // create list of object id's that should remain after filtering.
            var expectedTripIds  = new string[] { "AB1", "AB2", "BFC1", "BFC2" };
            var expectedStopIds  = new string[] { "BULLFROG", "BEATTY_AIRPORT", "FUR_CREEK_RES" };
            var expectedRouteIds = new string[] { "AB", "BFC" };
            var expectedShapeIds = new string[] { "shape_1", "shape_2", "shape_6", "shape_7" };

            // create the filter.
            var filter = new GTFSFeedStopsFilter((x) =>
            {
                return(x.Id == "BULLFROG");
            });

            // execute filter.
            var filtered = filter.Filter(feed);

            Assert.IsTrue(GTFSFeedValidation.Validate(filtered));

            // test for trips/stops.
            foreach (var stop in filtered.Stops)
            {
                Assert.Contains(stop.Id, expectedStopIds);
            }
            foreach (var trip in filtered.Trips)
            {
                Assert.Contains(trip.Id, expectedTripIds);
            }
            foreach (var route in filtered.Routes)
            {
                Assert.Contains(route.Id, expectedRouteIds);
            }
            foreach (var shape in filtered.Shapes)
            {
                Assert.Contains(shape.Id, expectedShapeIds);
            }

            // create the filter.
            var stopIds = new HashSet <string>();

            stopIds.Add("BULLFROG");
            filter = new GTFSFeedStopsFilter(stopIds);

            // execute filter.
            filtered = filter.Filter(feed);
            Assert.IsTrue(GTFSFeedValidation.Validate(filtered));

            // test for trips/stops.
            foreach (var stop in filtered.Stops)
            {
                Assert.Contains(stop.Id, expectedStopIds);
            }
            foreach (var trip in filtered.Trips)
            {
                Assert.Contains(trip.Id, expectedTripIds);
            }
            foreach (var route in filtered.Routes)
            {
                Assert.Contains(route.Id, expectedRouteIds);
            }
            foreach (var shape in filtered.Shapes)
            {
                Assert.Contains(shape.Id, expectedShapeIds);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Returns the feed produced by this reader.
        /// </summary>
        /// <returns></returns>
        public override IGTFSFeed GetFeed()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>(false);

            // execute the reader.
            return reader.Read(new GTFSDirectorySource(new DirectoryInfo(_path)));
        }
Beispiel #26
0
        private async Task RunAsync(Option option)
        {
            Console.WriteLine(HeadingInfo.Default);
            Console.WriteLine(CopyrightInfo.Default);
            Console.WriteLine("");

            try
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(option.Database);
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine(string.Format("ERROR: {0}", exception.Message));
                Console.WriteLine("");

                Environment.Exit(1);
            }

            SqlConnection connection = new SqlConnection(option.Database);

            try
            {
                await connection.OpenAsync();
            }
            catch (SqlException exception)
            {
                Console.Error.WriteLine(string.Format("ERROR: {0}", exception.Message));
                Console.WriteLine("");

                Environment.Exit(1);
            }

            try
            {
                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS AgencyProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS CalendarProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS CalendarDateProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS FareAttributeProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS FareRuleProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS FrequencyProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS LevelProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS PathwayProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS RouteProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS ShapeProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS StopProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS StopTimeProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS TransferProcedure");

                await connection.ExecuteCommandAsync("DROP PROCEDURE IF EXISTS TripProcedure");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS AgencyType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS CalendarType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS CalendarDateType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS FareAttributeType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS FareRuleType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS FrequencyType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS LevelType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS PathwayType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS RouteType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS ShapeType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS StopType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS StopTimeType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS TransferType");

                await connection.ExecuteCommandAsync("DROP TYPE IF EXISTS TripType");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Agency");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Calendar");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS CalendarDate");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS FareAttribute");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS FareRule");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Frequency");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Level");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Pathway");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Route");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Shape");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Stop");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS StopTime");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Transfer");

                await connection.ExecuteCommandAsync("DROP TABLE IF EXISTS Trip");

                await connection.ExecuteCommandAsync("CREATE TABLE Agency (Id nvarchar(255), Name nvarchar(255), URL nvarchar(255), Timezone nvarchar(255), LanguageCode nvarchar(255), Phone nvarchar(255), FareURL nvarchar(255), Email nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE Calendar (ServiceId nvarchar(255) PRIMARY KEY, Monday bit, Tuesday bit, Wednesday bit, Thursday bit, Friday bit, Saturday bit, Sunday bit, StartDate datetime, EndDate datetime)");

                await connection.ExecuteCommandAsync("CREATE TABLE CalendarDate (ServiceId nvarchar(255), Date datetime, ExceptionType int)");

                await connection.ExecuteCommandAsync("CREATE TABLE FareAttribute (FareId nvarchar(255), Price nvarchar(255), CurrencyType nvarchar(255), PaymentMethod int, Transfers int, AgencyId nvarchar(255), TransferDuration nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE FareRule (FareId nvarchar(255), RouteId nvarchar(255), OriginId nvarchar(255), DestinationId nvarchar(255), ContainsId nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE Frequency (TripId nvarchar(255), StartTime nvarchar(255), EndTime nvarchar(255), HeadwaySecs nvarchar(255), ExactTimes bit)");

                await connection.ExecuteCommandAsync("CREATE TABLE Level (Id nvarchar(255), Indexes float, Name nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE Pathway (Id nvarchar(255), FromStopId nvarchar(255), ToStopId nvarchar(255), PathwayMode int, IsBidirectional int, Length float, TraversalTime int, StairCount int, MaxSlope float, MinWidth float, SignpostedAs nvarchar(255), ReversedSignpostedAs nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE Route (Id nvarchar(255) PRIMARY KEY, AgencyId nvarchar(255), ShortName nvarchar(255), LongName nvarchar(255), Description nvarchar(255), Type int, Url nvarchar(255), Color int, TextColor int)");

                await connection.ExecuteCommandAsync("CREATE TABLE Shape (Id nvarchar(255), Latitude float, Longitude float, Sequence int, DistanceTravelled float)");

                await connection.ExecuteCommandAsync("CREATE TABLE Stop (Id nvarchar(255) PRIMARY KEY, Code nvarchar(255), Name nvarchar(255), Description nvarchar(255), Latitude float, Longitude float, Zone nvarchar(255), Url nvarchar(255), LocationType int, ParentStation nvarchar(255), Timezone nvarchar(255), WheelchairBoarding nvarchar(255), LevelId nvarchar(255), PlatformCode nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE StopTime (TripId nvarchar(255), ArrivalTime nvarchar(255), DepartureTime nvarchar(255), StopId nvarchar(255), StopSequence int, StopHeadsign nvarchar(255), PickupType int, DropOffType int, ShapeDistTravelled float, TimepointType int)");

                await connection.ExecuteCommandAsync("CREATE TABLE Transfer (FromStopId nvarchar(255), ToStopId nvarchar(255), TransferType int, MinimumTransferTime nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TABLE Trip (Id nvarchar(255) PRIMARY KEY, RouteId nvarchar(255), ServiceId nvarchar(255), Headsign nvarchar(255), ShortName nvarchar(255), Direction int, BlockId nvarchar(255), ShapeId nvarchar(255), AccessibilityType int)");

                await connection.ExecuteCommandAsync("CREATE TYPE AgencyType AS TABLE (Id nvarchar(255), Name nvarchar(255), URL nvarchar(255), Timezone nvarchar(255), LanguageCode nvarchar(255), Phone nvarchar(255), FareURL nvarchar(255), Email nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE CalendarType AS TABLE (ServiceId nvarchar(255), Monday bit, Tuesday bit, Wednesday bit, Thursday bit, Friday bit, Saturday bit, Sunday bit, StartDate datetime, EndDate datetime)");

                await connection.ExecuteCommandAsync("CREATE TYPE CalendarDateType AS TABLE (ServiceId nvarchar(255), Date datetime, ExceptionType int)");

                await connection.ExecuteCommandAsync("CREATE TYPE FareAttributeType AS TABLE (FareId nvarchar(255), Price nvarchar(255), CurrencyType nvarchar(255), PaymentMethod int, Transfers int, AgencyId nvarchar(255), TransferDuration nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE FareRuleType AS TABLE (FareId nvarchar(255), RouteId nvarchar(255), OriginId nvarchar(255), DestinationId nvarchar(255), ContainsId nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE FrequencyType AS TABLE (TripId nvarchar(255), StartTime nvarchar(255), EndTime nvarchar(255), HeadwaySecs nvarchar(255), ExactTimes bit)");

                await connection.ExecuteCommandAsync("CREATE TYPE LevelType AS TABLE (Id nvarchar(255), Indexes float, Name nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE PathwayType AS TABLE (Id nvarchar(255), FromStopId nvarchar(255), ToStopId nvarchar(255), PathwayMode int, IsBidirectional int, Length float, TraversalTime int, StairCount int, MaxSlope float, MinWidth float, SignpostedAs nvarchar(255), ReversedSignpostedAs nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE RouteType AS TABLE (Id nvarchar(255), AgencyId nvarchar(255), ShortName nvarchar(255), LongName nvarchar(255), Description nvarchar(255), Type int, Url nvarchar(255), Color int, TextColor int)");

                await connection.ExecuteCommandAsync("CREATE TYPE ShapeType AS TABLE (Id nvarchar(255), Latitude float, Longitude float, Sequence int, DistanceTravelled float)");

                await connection.ExecuteCommandAsync("CREATE TYPE StopType AS TABLE (Id nvarchar(255), Code nvarchar(255), Name nvarchar(255), Description nvarchar(255), Latitude float, Longitude float, Zone nvarchar(255), Url nvarchar(255), LocationType int, ParentStation nvarchar(255), Timezone nvarchar(255), WheelchairBoarding nvarchar(255), LevelId nvarchar(255), PlatformCode nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE StopTimeType AS TABLE (TripId nvarchar(255), ArrivalTime nvarchar(255), DepartureTime nvarchar(255), StopId nvarchar(255), StopSequence int, StopHeadsign nvarchar(255), PickupType int, DropOffType int, ShapeDistTravelled float, TimepointType int)");

                await connection.ExecuteCommandAsync("CREATE TYPE TransferType AS TABLE (FromStopId nvarchar(255), ToStopId nvarchar(255), TransferType int, MinimumTransferTime nvarchar(255))");

                await connection.ExecuteCommandAsync("CREATE TYPE TripType AS TABLE (Id nvarchar(255), RouteId nvarchar(255), ServiceId nvarchar(255), Headsign nvarchar(255), ShortName nvarchar(255), Direction int, BlockId nvarchar(255), ShapeId nvarchar(255), AccessibilityType int)");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE AgencyProcedure (@table AgencyType READONLY) AS INSERT INTO Agency (Id, Name, URL, Timezone, LanguageCode, Phone, FareURL, Email) SELECT Id, Name, URL, Timezone, LanguageCode, Phone, FareURL, Email FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE CalendarProcedure (@table CalendarType READONLY) AS INSERT INTO Calendar (ServiceId, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, StartDate, EndDate) SELECT ServiceId, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, StartDate, EndDate FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE CalendarDateProcedure (@table CalendarDateType READONLY) AS INSERT INTO CalendarDate (ServiceId, Date, ExceptionType) SELECT ServiceId, Date, ExceptionType FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE FareAttributeProcedure (@table FareAttributeType READONLY) AS INSERT INTO FareAttribute (FareId, Price, CurrencyType, PaymentMethod, Transfers, AgencyId, TransferDuration) SELECT FareId, Price, CurrencyType, PaymentMethod, Transfers, AgencyId, TransferDuration FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE FareRuleProcedure (@table FareRuleType READONLY) AS INSERT INTO FareRule (FareId, RouteId, OriginId, DestinationId, ContainsId) SELECT FareId, RouteId, OriginId, DestinationId, ContainsId FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE FrequencyProcedure (@table FrequencyType READONLY) AS INSERT INTO Frequency (TripId, StartTime, EndTime, HeadwaySecs, ExactTimes) SELECT TripId, StartTime, EndTime, HeadwaySecs, ExactTimes FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE LevelProcedure (@table LevelType READONLY) AS INSERT INTO Level (Id, Indexes, Name) SELECT Id, Indexes, Name FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE PathwayProcedure (@table PathwayType READONLY) AS INSERT INTO Pathway (Id, FromStopId, ToStopId, PathwayMode, IsBidirectional, Length, TraversalTime, StairCount, MaxSlope, MinWidth, SignpostedAs, ReversedSignpostedAs) SELECT Id, FromStopId, ToStopId, PathwayMode, IsBidirectional, Length, TraversalTime, StairCount, MaxSlope, MinWidth, SignpostedAs, ReversedSignpostedAs FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE RouteProcedure (@table RouteType READONLY) AS INSERT INTO Route (Id, AgencyId, ShortName, LongName, Description, Type, Url, Color, TextColor) SELECT Id, AgencyId, ShortName, LongName, Description, Type, Url, Color, TextColor FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE ShapeProcedure (@table ShapeType READONLY) AS INSERT INTO Shape (Id, Latitude, Longitude, Sequence, DistanceTravelled) SELECT Id, Latitude, Longitude, Sequence, DistanceTravelled FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE StopProcedure (@table StopType READONLY) AS INSERT INTO Stop (Id, Code, Name, Description, Latitude, Longitude, Zone, Url, LocationType, ParentStation, Timezone, WheelchairBoarding, LevelId, PlatformCode) SELECT Id, Code, Name, Description, Latitude, Longitude, Zone, Url, LocationType, ParentStation, Timezone, WheelchairBoarding, LevelId, PlatformCode FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE StopTimeProcedure (@table StopTimeType READONLY) AS INSERT INTO StopTime (TripId, ArrivalTime, DepartureTime, StopId, StopSequence, StopHeadsign, PickupType, DropOffType, ShapeDistTravelled, TimepointType) SELECT TripId, ArrivalTime, DepartureTime, StopId, StopSequence, StopHeadsign, PickupType, DropOffType, ShapeDistTravelled, TimepointType FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE TransferProcedure (@table TransferType READONLY) AS INSERT INTO Transfer (FromStopId, ToStopId, TransferType, MinimumTransferTime) SELECT FromStopId, ToStopId, TransferType, MinimumTransferTime FROM @table");

                await connection.ExecuteCommandAsync("CREATE PROCEDURE TripProcedure (@table TripType READONLY) AS INSERT INTO Trip (Id, RouteId, ServiceId, Headsign, ShortName, Direction, BlockId, ShapeId, AccessibilityType) SELECT Id, RouteId, ServiceId, Headsign, ShortName, Direction, BlockId, ShapeId, AccessibilityType FROM @table");

                Console.WriteLine("CREATE: tables");

                GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>();
                GTFSFeed feed = reader.Read(option.Gtfs);

                DataTable agency = new DataTable();
                agency.Columns.Add("Id", typeof(string));
                agency.Columns.Add("Name", typeof(string));
                agency.Columns.Add("URL", typeof(string));
                agency.Columns.Add("Timezone", typeof(string));
                agency.Columns.Add("LanguageCode", typeof(string));
                agency.Columns.Add("Phone", typeof(string));
                agency.Columns.Add("FareURL", typeof(string));
                agency.Columns.Add("Email", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("AgencyProcedure", agency, feed.Agencies, (dt, agency) => dt.Rows.Add(agency.Id, agency.Name, agency.URL, agency.Timezone, agency.LanguageCode, agency.Phone, agency.FareURL, agency.Email));

                Console.WriteLine("INSERT: agency.txt");

                DataTable calendar = new DataTable();
                calendar.Columns.Add("ServiceId", typeof(string));
                calendar.Columns.Add("Monday", typeof(bool));
                calendar.Columns.Add("Tuesday", typeof(bool));
                calendar.Columns.Add("Wednesday", typeof(bool));
                calendar.Columns.Add("Thursday", typeof(bool));
                calendar.Columns.Add("Friday", typeof(bool));
                calendar.Columns.Add("Saturday", typeof(bool));
                calendar.Columns.Add("Sunday", typeof(bool));
                calendar.Columns.Add("StartDate", typeof(DateTime));
                calendar.Columns.Add("EndDate", typeof(DateTime));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("CalendarProcedure", calendar, feed.Calendars.GroupBy(c => c.ServiceId).Select(c => c.First()), (dt, calendar) => dt.Rows.Add(calendar.ServiceId, calendar.Monday, calendar.Tuesday, calendar.Wednesday, calendar.Thursday, calendar.Friday, calendar.Saturday, calendar.Sunday, calendar.StartDate, calendar.EndDate));

                Console.WriteLine("INSERT: calendar.txt");

                DataTable calendarDate = new DataTable();
                calendarDate.Columns.Add("ServiceId", typeof(string));
                calendarDate.Columns.Add("Date", typeof(DateTime));
                calendarDate.Columns.Add("ExceptionType", typeof(int));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("CalendarDateProcedure", calendarDate, feed.CalendarDates, (dt, calendarDate) => dt.Rows.Add(calendarDate.ServiceId, calendarDate.Date, calendarDate.ExceptionType));

                Console.WriteLine("INSERT: calendar_dates.txt");

                DataTable fareAttribute = new DataTable();
                fareAttribute.Columns.Add("FareId", typeof(string));
                fareAttribute.Columns.Add("Price", typeof(string));
                fareAttribute.Columns.Add("CurrencyType", typeof(string));
                fareAttribute.Columns.Add("PaymentMethod", typeof(int));
                fareAttribute.Columns.Add("Transfers", typeof(int));
                fareAttribute.Columns.Add("AgencyId", typeof(string));
                fareAttribute.Columns.Add("TransferDuration", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("FareAttributeProcedure", fareAttribute, feed.FareAttributes, (dt, fareAttribute) => dt.Rows.Add(fareAttribute.FareId, fareAttribute.Price, fareAttribute.CurrencyType, fareAttribute.PaymentMethod, fareAttribute.Transfers, fareAttribute.AgencyId, fareAttribute.TransferDuration));

                Console.WriteLine("INSERT: fare_attributes.txt");

                DataTable fareRule = new DataTable();
                fareRule.Columns.Add("FareId", typeof(string));
                fareRule.Columns.Add("RouteId", typeof(string));
                fareRule.Columns.Add("OriginId", typeof(string));
                fareRule.Columns.Add("DestinationId", typeof(string));
                fareRule.Columns.Add("ContainsId", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("FareRuleProcedure", fareRule, feed.FareRules, (dt, fareRule) => dt.Rows.Add(fareRule.FareId, fareRule.RouteId, fareRule.OriginId, fareRule.DestinationId, fareRule.ContainsId));

                Console.WriteLine("INSERT: fare_rules.txt");

                DataTable frequency = new DataTable();
                frequency.Columns.Add("TripId", typeof(string));
                frequency.Columns.Add("StartTime", typeof(string));
                frequency.Columns.Add("EndTime", typeof(string));
                frequency.Columns.Add("HeadwaySecs", typeof(string));
                frequency.Columns.Add("ExactTimes", typeof(bool));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("FrequencyProcedure", frequency, feed.Frequencies, (dt, frequency) => dt.Rows.Add(frequency.TripId, frequency.StartTime, frequency.EndTime, frequency.HeadwaySecs, frequency.ExactTimes));

                Console.WriteLine("INSERT: frequencies.txt");

                DataTable level = new DataTable();
                level.Columns.Add("Id", typeof(string));
                level.Columns.Add("Indexes", typeof(double));
                level.Columns.Add("Name", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("LevelProcedure", level, feed.Levels, (dt, level) => dt.Rows.Add(level.Id, level.Index, level.Name));

                Console.WriteLine("INSERT: levels.txt");

                DataTable pathway = new DataTable();
                pathway.Columns.Add("Id", typeof(string));
                pathway.Columns.Add("FromStopId", typeof(string));
                pathway.Columns.Add("ToStopId", typeof(string));
                pathway.Columns.Add("PathwayMode", typeof(int));
                pathway.Columns.Add("IsBidirectional", typeof(int));
                pathway.Columns.Add("Length", typeof(double));
                pathway.Columns.Add("TraversalTime", typeof(int));
                pathway.Columns.Add("StairCount", typeof(int));
                pathway.Columns.Add("MaxSlope", typeof(double));
                pathway.Columns.Add("MinWidth", typeof(double));
                pathway.Columns.Add("SignpostedAs", typeof(string));
                pathway.Columns.Add("ReversedSignpostedAs", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("PathwayProcedure", pathway, feed.Pathways, (dt, pathway) => dt.Rows.Add(pathway.Id, pathway.FromStopId, pathway.ToStopId, pathway.PathwayMode, pathway.IsBidirectional, pathway.Length, pathway.TraversalTime, pathway.StairCount, pathway.MaxSlope, pathway.MinWidth, pathway.SignpostedAs, pathway.ReversedSignpostedAs));

                Console.WriteLine("INSERT: pathways.txt");

                DataTable route = new DataTable();
                route.Columns.Add("Id", typeof(string));
                route.Columns.Add("AgencyId", typeof(string));
                route.Columns.Add("ShortName", typeof(string));
                route.Columns.Add("LongName", typeof(string));
                route.Columns.Add("Description", typeof(string));
                route.Columns.Add("Type", typeof(int));
                route.Columns.Add("Url", typeof(string));
                route.Columns.Add("Color", typeof(int));
                route.Columns.Add("TextColor", typeof(int));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("RouteProcedure", route, feed.Routes.GroupBy(r => r.Id).Select(r => r.First()), (dt, route) => dt.Rows.Add(route.Id, route.AgencyId, route.ShortName, route.LongName, route.Description, route.Type, route.Url, route.Color, route.TextColor));

                Console.WriteLine("INSERT: routes.txt");

                DataTable shape = new DataTable();
                shape.Columns.Add("Id", typeof(string));
                shape.Columns.Add("Latitude", typeof(double));
                shape.Columns.Add("Longitude", typeof(double));
                shape.Columns.Add("Sequence", typeof(int));
                shape.Columns.Add("DistanceTravelled", typeof(double));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("ShapeProcedure", shape, feed.Shapes, (dt, shape) => dt.Rows.Add(shape.Id, shape.Latitude, shape.Longitude, shape.Sequence, shape.DistanceTravelled));

                Console.WriteLine("INSERT: shapes.txt");

                DataTable stop = new DataTable();
                stop.Columns.Add("Id", typeof(string));
                stop.Columns.Add("Code", typeof(string));
                stop.Columns.Add("Name", typeof(string));
                stop.Columns.Add("Description", typeof(string));
                stop.Columns.Add("Latitude", typeof(double));
                stop.Columns.Add("Longitude", typeof(double));
                stop.Columns.Add("Zone", typeof(string));
                stop.Columns.Add("Url", typeof(string));
                stop.Columns.Add("LocationType", typeof(int));
                stop.Columns.Add("ParentStation", typeof(string));
                stop.Columns.Add("Timezone", typeof(string));
                stop.Columns.Add("WheelchairBoarding", typeof(string));
                stop.Columns.Add("LevelId", typeof(string));
                stop.Columns.Add("PlatformCode", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("StopProcedure", stop, feed.Stops.GroupBy(s => s.Id).Select(s => s.First()), (dt, stop) => dt.Rows.Add(stop.Id, stop.Code, stop.Name, stop.Description, stop.Latitude, stop.Longitude, stop.Zone, stop.Url, stop.LocationType, stop.ParentStation, stop.Timezone, stop.WheelchairBoarding, stop.LevelId, stop.PlatformCode));

                Console.WriteLine("INSERT: stops.txt");

                DataTable stopTime = new DataTable();
                stopTime.Columns.Add("TripId", typeof(string));
                stopTime.Columns.Add("ArrivalTime", typeof(string));
                stopTime.Columns.Add("DepartureTime", typeof(string));
                stopTime.Columns.Add("StopId", typeof(string));
                stopTime.Columns.Add("StopSequence", typeof(int));
                stopTime.Columns.Add("StopHeadsign", typeof(string));
                stopTime.Columns.Add("PickupType", typeof(int));
                stopTime.Columns.Add("DropOffType", typeof(int));
                stopTime.Columns.Add("ShapeDistTravelled", typeof(double));
                stopTime.Columns.Add("TimepointType", typeof(int));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("StopTimeProcedure", stopTime, feed.StopTimes, (dt, stopTime) => dt.Rows.Add(stopTime.TripId, stopTime.ArrivalTime, stopTime.DepartureTime, stopTime.StopId, stopTime.StopSequence, stopTime.StopHeadsign, stopTime.PickupType, stopTime.DropOffType, stopTime.ShapeDistTravelled, stopTime.TimepointType));

                Console.WriteLine("INSERT: stop_times.txt");

                DataTable transfer = new DataTable();
                transfer.Columns.Add("FromStopId", typeof(string));
                transfer.Columns.Add("ToStopId", typeof(string));
                transfer.Columns.Add("TransferType", typeof(int));
                transfer.Columns.Add("MinimumTransferTime", typeof(string));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("TransferProcedure", transfer, feed.Transfers, (dt, transfer) => dt.Rows.Add(transfer.FromStopId, transfer.ToStopId, transfer.TransferType, transfer.MinimumTransferTime));

                Console.WriteLine("INSERT: transfers.txt");

                DataTable trip = new DataTable();
                trip.Columns.Add("Id", typeof(string));
                trip.Columns.Add("RouteId", typeof(string));
                trip.Columns.Add("ServiceId", typeof(string));
                trip.Columns.Add("Headsign", typeof(string));
                trip.Columns.Add("ShortName", typeof(string));
                trip.Columns.Add("Direction", typeof(int));
                trip.Columns.Add("BlockId", typeof(string));
                trip.Columns.Add("ShapeId", typeof(string));
                trip.Columns.Add("AccessibilityType", typeof(int));

                await connection.ExecuteStoredProcedureFromTableInBatchesAsync("TripProcedure", trip, feed.Trips.GroupBy(t => t.Id).Select(t => t.First()), (dt, trip) => dt.Rows.Add(trip.Id, trip.RouteId, trip.ServiceId, trip.Headsign, trip.ShortName, trip.Direction, trip.BlockId, trip.ShapeId, trip.AccessibilityType));

                Console.WriteLine("INSERT: trips.txt");

                await connection.ExecuteCommandAsync("CREATE NONCLUSTERED INDEX StopTimeIndexStop ON StopTime (StopId, PickupType) INCLUDE (TripId, ArrivalTime, DepartureTime, StopSequence, StopHeadsign, DropOffType, ShapeDistTravelled, TimepointType) WITH (ONLINE = ON)");

                await connection.ExecuteCommandAsync("CREATE NONCLUSTERED INDEX StopTimeIndexTrip ON StopTime (TripId, PickupType) INCLUDE (ArrivalTime, DepartureTime, StopId, StopSequence, StopHeadsign, DropOffType, ShapeDistTravelled, TimepointType) WITH (ONLINE = ON)");

                Console.WriteLine("CREATE: indexes");
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine(string.Format("ERROR: {0}", exception.Message));
                Console.WriteLine("");

                Environment.Exit(1);
            }
        }
Beispiel #27
0
        public void ParseRoutes()
        {
            // create the reader.
            GTFSReader <GTFSFeed> reader = new GTFSReader <GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("routes")));

            // test result.
            Assert.IsNotNull(feed.Routes);
            var routes = feed.Routes.ToList();

            Assert.AreEqual(5, routes.Count);

            //route_id,agency_id,route_short_name,route_long_name,route_desc,route_type,route_url,route_color,route_text_color

            //AB,DTA,10,Airport - Bullfrog,,3,,,
            int idx = 0;

            Assert.AreEqual("AB", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("10", routes[idx].ShortName);
            Assert.AreEqual("Airport - Bullfrog", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(-3932017, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //BFC,DTA,20,Bullfrog - Furnace Creek Resort,,3,,,
            idx = 1;
            Assert.AreEqual("BFC", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("20", routes[idx].ShortName);
            Assert.AreEqual("Bullfrog - Furnace Creek Resort", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(-1, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //STBA,DTA,30,Stagecoach - Airport Shuttle,,3,,,
            idx = 2;
            Assert.AreEqual("STBA", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("30", routes[idx].ShortName);
            Assert.AreEqual("Stagecoach - Airport Shuttle", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(null, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //CITY,DTA,40,City,,3,,,
            idx = 3;
            Assert.AreEqual("CITY", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("40", routes[idx].ShortName);
            Assert.AreEqual("City", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(null, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);

            //AAMV,DTA,50,Airport - Amargosa Valley,,3,,,
            idx = 4;
            Assert.AreEqual("AAMV", routes[idx].Id);
            Assert.AreEqual("DTA", routes[idx].AgencyId);
            Assert.AreEqual("50", routes[idx].ShortName);
            Assert.AreEqual("Airport - Amargosa Valley", routes[idx].LongName);
            Assert.AreEqual(string.Empty, routes[idx].Description);
            Assert.AreEqual(RouteTypeExtended.BusService, routes[idx].Type);
            Assert.AreEqual(null, routes[idx].Color);
            Assert.AreEqual(null, routes[idx].TextColor);
        }
Beispiel #28
0
        /// <summary>
        /// Reads a fead from the given directory.
        /// </summary>
        public static GTFSFeed Read(this GTFSReader <GTFSFeed> reader, string path)
        {
            var directory = new DirectoryInfo(path);

            return(reader.Read(directory));
        }
Beispiel #29
0
        /// <summary>
        /// Builds a test feed.
        /// </summary>
        /// <returns></returns>
        protected virtual IGTFSFeed BuildTestFeed()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            return reader.Read(source);
        }
        public void ParseShapes()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("shapes")));

            // test result.
            Assert.IsNotNull(feed.Shapes);
            var shapes = feed.Shapes.ToList();
            Assert.AreEqual(44, shapes.Count);

            // @ 1: shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence,shape_dist_traveled
            // @ 2: shape_1,37.754211,-122.197868,1,
            int idx = 0;
            Assert.AreEqual("shape_1", shapes[idx].Id);
            Assert.AreEqual(37.754211, shapes[idx].Latitude);
            Assert.AreEqual(-122.197868, shapes[idx].Longitude);
            Assert.AreEqual(1, shapes[idx].Sequence);
            Assert.AreEqual(null, shapes[idx].DistanceTravelled);

            // @ 10: shape_3,37.73645,-122.19706,1,
            idx = 8;
            Assert.AreEqual("shape_3", shapes[idx].Id);
            Assert.AreEqual(37.73645, shapes[idx].Latitude);
            Assert.AreEqual(-122.19706, shapes[idx].Longitude);
            Assert.AreEqual(1, shapes[idx].Sequence);
            Assert.AreEqual(null, shapes[idx].DistanceTravelled);
        }
        public void TestMissingStopTime()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // remove.
            (feed.StopTimes.Get() as List<StopTime>)[2].StopSequence = 1024;

            // validate.
            Assert.IsFalse(GTFSFeedValidation.Validate(feed));
        }
        public void ParseStops()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("stops")));

            // test result.
            Assert.IsNotNull(feed.Stops);
            var stops = feed.Stops.ToList();
            Assert.AreEqual(9, stops.Count);

            // @ 1: stop_id,stop_name,stop_desc,stop_lat,stop_lon,zone_id,stop_url
            // @ 2: FUR_CREEK_RES,Furnace Creek Resort (Demo),,36.425288,-117.133162,,
            int idx = 0;
            Assert.AreEqual("FUR_CREEK_RES", stops[idx].Id);
            Assert.AreEqual("Furnace Creek Resort (Demo)", stops[idx].Name);
            Assert.AreEqual(string.Empty, stops[idx].Description);
            Assert.AreEqual(36.425288, stops[idx].Latitude);
            Assert.AreEqual(-117.133162, stops[idx].Longitude);
            Assert.AreEqual(string.Empty, stops[idx].Url);

            // @ 10: AMV,Amargosa Valley (Demo),,36.641496,-116.40094,,
            idx = 8;
            Assert.AreEqual("AMV", stops[idx].Id);
            Assert.AreEqual("Amargosa Valley (Demo)", stops[idx].Name);
            Assert.AreEqual(string.Empty, stops[idx].Description);
            Assert.AreEqual(36.641496, stops[idx].Latitude);
            Assert.AreEqual(-116.40094, stops[idx].Longitude);
            Assert.AreEqual(string.Empty, stops[idx].Url);
        }
        /// <summary>
        /// Loads a new instance.
        /// </summary>
        /// <param name="apiConfiguration"></param>
        /// <param name="instanceConfiguration"></param>
        /// <returns></returns>
        private static bool LoadInstance(ApiConfiguration apiConfiguration, InstanceConfiguration instanceConfiguration)
        {
            try
            {
                // get graph configuration.
                var graph = instanceConfiguration.Graph;
                var type = instanceConfiguration.Type;
                var format = instanceConfiguration.Format;
                var vehicleName = instanceConfiguration.Vehicle;

                try
                {
                    // create routing instance.
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Creating {0} instance...", instanceConfiguration.Name));
                    Router router = null;
                    RouterDataSource<Edge> data = null;

                    var graphFile = new FileInfo(graph);
                    switch (type)
                    {
                        case "raw":
                            switch (format)
                            {
                                case "osm-xml":
                                    using(var graphStream = graphFile.OpenRead())
                                    {
                                        data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                            new XmlOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                        router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                                    }
                                    break;
                                case "osm-pbf":
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        data = OsmSharp.Routing.Osm.Streams.GraphOsmStreamTarget.Preprocess(
                                            new PBFOsmStreamSource(graphStream), new OsmRoutingInterpreter());
                                        router = Router.CreateFrom(data, new OsmRoutingInterpreter());
                                    }
                                    break;
                                default:
                                    throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                        format, type));
                            }
                            break;
                        case "contracted":
                            // check for GTFS-feeds and give warning if they are there.
                            if(instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                            { // ... oeps a feed and a contracted network are not supported for now.
                                OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                    "NotSupported: GTFS and contracted graphs cannot (yet) be combined.");
                            }

                            switch(format)
                            {
                                case "osm-xml":
                                    if (string.IsNullOrWhiteSpace(vehicleName))
                                    { // invalid configuration.
                                        throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                                    }
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        var graphSource = new XmlOsmStreamSource(graphStream);
                                        router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                                    }
                                    break;
                                case "osm-pbf":
                                    if (string.IsNullOrWhiteSpace(vehicleName))
                                    { // invalid configuration.
                                        throw new Exception("Invalid configuration, a vehicle type is required when building contracted graphs on-the-fly.");
                                    }
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        var graphSource = new PBFOsmStreamSource(graphStream);
                                        router = Router.CreateCHFrom(graphSource, new OsmRoutingInterpreter(), Vehicle.GetByUniqueName(vehicleName));
                                    }
                                    break;
                                case "flat":
                                    var mobileRoutingSerializer = new CHEdgeSerializer();
                                    // keep this stream open, it is used while routing!
                                    var mobileGraphInstance = mobileRoutingSerializer.Deserialize(graphFile.OpenRead());
                                    router = Router.CreateCHFrom(mobileGraphInstance, new CHRouter(), new OsmRoutingInterpreter());
                                    break;
                                default:
                                    throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                        format, type));
                            }
                            break;
                        case "simple":
                            switch (format)
                            {
                                case "flat":
                                    using (var graphStream = graphFile.OpenRead())
                                    {
                                        var routingSerializer = new RoutingDataSourceSerializer();
                                        data = routingSerializer.Deserialize(graphStream);
                                        router = Router.CreateFrom(data, new Dykstra(), new OsmRoutingInterpreter());
                                    }
                                    break;
                                default:
                                    throw new Exception(string.Format("Invalid format {0} for type {1}.",
                                        format, type));
                            }
                            break;
                    }

                    if(instanceConfiguration.Feeds != null && instanceConfiguration.Feeds.Count > 0)
                    { // transit-data use the transit-api.
                        if(instanceConfiguration.Feeds.Count > 1)
                        { // for now only one feed at a time is supported.
                            OsmSharp.Logging.Log.TraceEvent("ApiBootstrapper", OsmSharp.Logging.TraceEventType.Warning,
                                "NotSupported: Only one GTFS-feed at a time is supported.");
                        }

                        var feed = instanceConfiguration.Feeds[0];
                        var reader = new GTFSReader<GTFSFeed>(false);
                        var gtfsFeed = reader.Read<GTFSFeed>(new GTFSDirectorySource(feed.Path));
                        var connectionsDb = new GTFSConnectionsDb(gtfsFeed);
                        var multimodalConnectionsDb = new MultimodalConnectionsDb(data, connectionsDb,
                            new OsmRoutingInterpreter(), Vehicle.Pedestrian);

                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name,
                                new MultimodalApi(multimodalConnectionsDb));
                        }
                    }
                    else
                    { // no transit-data just use the regular routing api implementation.
                        lock (_sync)
                        {
                            OsmSharp.Service.Routing.ApiBootstrapper.AddOrUpdate(instanceConfiguration.Name, router);
                        }
                    }

                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Information,
                        string.Format("Instance {0} created successfully!", instanceConfiguration.Name));
                }
                catch(Exception ex)
                {
                    OsmSharp.Logging.Log.TraceEvent("Bootstrapper", OsmSharp.Logging.TraceEventType.Error,
                        string.Format("Exception occured while creating instance {0}:{1}", 
                        instanceConfiguration.Name, ex.ToInvariantString()));
                    throw;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        public void ParseTransfers()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("transfers")));

            // test result.
            Assert.IsNotNull(feed.Transfers);
            var tranfers = feed.Transfers.ToList();
            Assert.AreEqual(3, tranfers.Count);

            //from_stop_id,to_stop_id,transfer_type,min_transfer_time

            //BULLFROG,STAGECOACH,2,300
            int idx = 0;
            Assert.AreEqual("BULLFROG", tranfers[idx].FromStopId);
            Assert.AreEqual("STAGECOACH", tranfers[idx].ToStopId);
            Assert.AreEqual(TransferType.MinimumTime, tranfers[idx].TransferType);
            Assert.AreEqual("300", tranfers[idx].MinimumTransferTime);

            //BULLFROG,BEATTY_AIRPORT,3,
            idx = 1;
            Assert.AreEqual("BULLFROG", tranfers[idx].FromStopId);
            Assert.AreEqual("BEATTY_AIRPORT", tranfers[idx].ToStopId);
            Assert.AreEqual(TransferType.NotPossible, tranfers[idx].TransferType);
            Assert.AreEqual(string.Empty, tranfers[idx].MinimumTransferTime);

            //EMSI,AMV,1,
            idx = 2;
            Assert.AreEqual("EMSI", tranfers[idx].FromStopId);
            Assert.AreEqual("AMV", tranfers[idx].ToStopId);
            Assert.AreEqual(TransferType.TimedTransfer, tranfers[idx].TransferType);
            Assert.AreEqual(string.Empty, tranfers[idx].MinimumTransferTime);
        }
        public void ParseCalendars()
        {
            // create the reader.
            GTFSReader<GTFSFeed> reader = new GTFSReader<GTFSFeed>();

            // build the source
            var source = this.BuildSource();

            // execute the reader.
            var feed = reader.Read(source, source.First(x => x.Name.Equals("calendar")));

            // test result.
            Assert.IsNotNull(feed.Calendars);
            var calendars = feed.Calendars.ToList();
            Assert.AreEqual(2, calendars.Count);

            // @ 1: service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date
            // @ 2: FULLW,1,1,1,1,1,1,1,20070101,20101231
            int idx = 0;
            Assert.AreEqual("FULLW", calendars[idx].ServiceId);
            Assert.AreEqual(true, calendars[idx].Monday);
            Assert.AreEqual(true, calendars[idx].Tuesday);
            Assert.AreEqual(true, calendars[idx].Wednesday);
            Assert.AreEqual(true, calendars[idx].Thursday);
            Assert.AreEqual(true, calendars[idx].Friday);
            Assert.AreEqual(true, calendars[idx].Saturday);
            Assert.AreEqual(true, calendars[idx].Sunday);
            Assert.AreEqual(new DateTime(2007, 01, 01), calendars[idx].StartDate);
            Assert.AreEqual(new DateTime(2010, 12, 31), calendars[idx].EndDate);

            // @3: WE,0,0,0,0,0,1,1,20070101,20101231
            idx = 1;
            Assert.AreEqual("WE", calendars[idx].ServiceId);
            Assert.AreEqual(false, calendars[idx].Monday);
            Assert.AreEqual(false, calendars[idx].Tuesday);
            Assert.AreEqual(false, calendars[idx].Wednesday);
            Assert.AreEqual(false, calendars[idx].Thursday);
            Assert.AreEqual(false, calendars[idx].Friday);
            Assert.AreEqual(true, calendars[idx].Saturday);
            Assert.AreEqual(true, calendars[idx].Sunday);
            Assert.AreEqual(new DateTime(2007, 01, 01), calendars[idx].StartDate);
            Assert.AreEqual(new DateTime(2010, 12, 31), calendars[idx].EndDate);
        }
        public void TestValidFeed()
        {
            // create the reader.
            var reader = new GTFSReader<GTFSFeed>();
            var source = GTFSAssert.BuildSource();

            // execute the reader.
            var feed = reader.Read(source);

            // validate.
            Assert.IsTrue(GTFSFeedValidation.Validate(feed));
        }
Beispiel #37
0
        public MainWindow()
        {
            InitializeComponent();

            Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-GB");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

            // Create StringBuilder
            _sb = new StringBuilder();

            // Read GTFS Static files
            _reader     = new GTFSReader <GTFSFeed>(strict: false);
            _feedStatic = _reader.Read(new DirectoryInfo("GTFS"));

            // Read extra files and create lists with objects
            string[] translationsRaw        = File.ReadAllLines("GTFS\\translations.txt");
            string[] stop_time_overridesRaw = File.ReadAllLines("GTFS\\stop_time_overrides.txt");

            // Create lists with objects
            _stops     = _feedStatic.Stops.ToDictionary(x => x.Id, x => x);
            _trips     = _feedStatic.Trips.ToDictionary(x => x.Id, x => x);
            _routes    = _feedStatic.Routes.ToDictionary(x => x.Id, x => x).ToRouteExtraDictionary();
            _agencies  = _feedStatic.Agencies.ToDictionary(x => x.Id, x => x);
            _calendars = _feedStatic.Calendars.ToDictionary(x => x.ServiceId, x => x);
            _transfers = _feedStatic.Transfers.ToDictionary(x => x.FromStopId, x => x);

            _calendarDates = new Dictionary <string, Dictionary <DateTime, ExceptionType> >();
            foreach (string serviceId in _calendars.Keys)
            {
                _calendarDates.Add(serviceId, new Dictionary <DateTime, ExceptionType>());
            }
            foreach (CalendarDate cd in _feedStatic.CalendarDates)
            {
                _calendarDates[cd.ServiceId].Add(cd.Date, cd.ExceptionType);
            }

            _translations = new Dictionary <string, Dictionary <string, string> >();
            for (int i = 1; i < translationsRaw.Length;)
            {
                string key = new Translation(translationsRaw[i]).Trans_Id;
                Dictionary <string, string> value = new Dictionary <string, string>();

                Translation valueValue = new Translation(translationsRaw[i++]);
                value.Add(valueValue.Language, valueValue.Trans);
                valueValue = new Translation(translationsRaw[i++]);
                value.Add(valueValue.Language, valueValue.Trans);
                valueValue = new Translation(translationsRaw[i++]);
                value.Add(valueValue.Language, valueValue.Trans);
                valueValue = new Translation(translationsRaw[i++]);
                value.Add(valueValue.Language, valueValue.Trans);

                _translations.Add(key, value);
            }

            _stopTimeOverrides = new List <StopTimeOverride>();
            for (int i = 1; i < stop_time_overridesRaw.Length; i++)
            {
                _stopTimeOverrides.Add(new StopTimeOverride(stop_time_overridesRaw[i]));
            }

            // Realtime GTFS
            //FileDownload.UpdateRealtime();
            _feedRealtime = Serializer.Deserialize <FeedMessage>(new FileStream(@"GTFS\c21ac6758dd25af84cca5b707f3cb3de", FileMode.Open, FileAccess.Read));

            // Update ListViews
            UpdateLv(SelectedLv.BeginStationRouteplanner);
            UpdateLv(SelectedLv.EndStationRouteplanner);
            UpdateLv(SelectedLv.StationTripviewer);
            UpdateLv(SelectedLv.StationRealtime);
            UpdateLv(SelectedLv.StationRoutefinder);

            Thread.CurrentThread.CurrentCulture   = new CultureInfo("nl-BE");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("nl-BE");
        }