Exemple #1
0
        /// <summary>
        /// Creates a new Guided Variable Neighbourhood Search solver.
        /// </summary>
        /// <param name="router"></param>
        /// <param name="max"></param>
        /// <param name="deliveryTime"></param>
        /// <param name="thresholdPrecentage"></param>
        /// <param name="lambda"></param>
        /// <param name="sigma"></param>
        public GuidedVNS(Router router, Second max, Second deliveryTime, 
            float thresholdPrecentage, float lambda, float sigma)
            : base(max, deliveryTime)
        {
            _thresholdPercentage = thresholdPrecentage;
            _lambda = lambda;
            //            _sigma = sigma;

            _intra_improvements = new List<IImprovement>();
            //_intra_improvements.Add(
            //    new ArbitraryInsertionSolver());
            _intra_improvements.Add(
                new HillClimbing3OptSolver(true, true));

            _inter_improvements = new List<IInterImprovement>();
            _inter_improvements.Add(
                new RelocateImprovement());
            _inter_improvements.Add(
                new ExchangeInterImprovement());
            //_inter_improvements.Add(
            //    new TwoOptInterImprovement());
            _inter_improvements.Add(
                new RelocateExchangeInterImprovement());
            _inter_improvements.Add(
                new CrossExchangeInterImprovement());
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            var mapCSSInterpreter = new MapCSSInterpreter(new FileInfo(@"dark_roads.mapcss").OpenRead(), new MapCSSDictionaryImageSource());

            // initialize map.
            var map = new OsmSharp.UI.Map.Map();

            //// initialize router.
            try
            {
                _router = Router.CreateLiveFrom(new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource(new FileInfo(@"C:\Users\smccloud\Documents\GitHub\OsmSharp.Service.Tiles\OsmSharp.Service.Tiles.SelfHost\bin\Debug\stcloud.osm.pbf").OpenRead()), new OsmRoutingInterpreter());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            try
            {

                var layerTile = new LayerTile(@"http://localhost:1234/tiles_stcloud/{z}/{x}/{y}.png");
                map.AddLayer(layerTile);
                _layerRoute = new LayerRoute(new OsmSharp.Math.Geo.Projections.WebMercator());
                map.AddLayer(_layerRoute);
                _layerPrimitives = new LayerPrimitives(new OsmSharp.Math.Geo.Projections.WebMercator());
                map.AddLayer(_layerPrimitives);

                // set control properties.
                this.mapControl1.Map = map;
                this.mapControl1.MapCenter = new GeoCoordinate(45.5233, -94.14905);
                this.mapControl1.MapZoom = 14;
                this.mapControl1.Refresh();
                this.mapControl1.MapMouseClick += mapControl1_MapMouseClick;
                this.mapControl1.MapMouseMove += mapControl1_MapMouseMove;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Close();
            }
        }
        public void SQLServerRoutingRegressionTests1()
        {
            // the connectionstring.
            string connectionString =
                @"Server=windows8-test\sqlexpress;User Id=OsmSharp;Password=OsmSharp;Database=OsmData;";

            // drop whatever data is there.
            SqlConnection sqlConnection = new SqlConnection(connectionString);
            sqlConnection.Open();
            SQLServer.SimpleSchema.SchemaTools.SQLServerSimpleSchemaTools.Remove(sqlConnection);
            sqlConnection.Close();

            // create the source from the osm file.
            var xmlSource = new XmlDataProcessorSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "OsmSharp.Osm.Data.SQLServer.Unittests.Data.ukraine1.osm"));

            // create the SQLServer processor target.
            var testTarget = new SQLServerSimpleSchemaDataProcessorTarget(connectionString, true);
            testTarget.RegisterSource(xmlSource); // register the source.
            testTarget.Pull(); // pull the data from source to target.

            var source = new SQLServerSimpleSchemaSource(
                connectionString);
            var tagsIndex = new OsmTagsIndex();
            var interpreter = new OsmRoutingInterpreter();
            var routingData = new OsmSourceRouterDataSource(
                interpreter, tagsIndex, source, VehicleEnum.Car);

            IRouter<RouterPoint> router = new Router<PreProcessedEdge>(routingData, interpreter,
                new DykstraRoutingPreProcessed(routingData.TagsIndex));

            OsmSharpRoute route;

            RouterPoint point1 = router.Resolve(VehicleEnum.Car,
                new GeoCoordinate(50.3150034243338, 34.8784106812928));
            RouterPoint point2 = router.Resolve(VehicleEnum.Car,
                new GeoCoordinate(50.3092549484347, 34.8894929841615));
            route = router.Calculate(VehicleEnum.Car, point1, point2);

            Assert.IsNotNull(route);
        }
        public void RoutingSerializationRoutingTest()
        {
            const string embeddedString = "OsmSharp.UnitTests.test_network.osm";

            // create the tags index.
            var tagsIndex = new OsmTagsIndex();

            // creates a new interpreter.
            var interpreter = new OsmRoutingInterpreter();

            // do the data processing.
            var original =
                new DynamicGraphRouterDataSource<PreProcessedEdge>(tagsIndex);
            var targetData = new PreProcessedDataGraphProcessingTarget(
                original, interpreter, original.TagsIndex, VehicleEnum.Car);
            var dataProcessorSource = new XmlDataProcessorSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));
            targetData.RegisterSource(dataProcessorSource);
            targetData.Pull();

            // create serializer.
            var routingSerializer = new V1RoutingSerializer();

            // serialize/deserialize.
            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original);
                    byteArray = stream.ToArray();
                }
                catch (Exception ex)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            IBasicRouterDataSource<PreProcessedEdge> deserializedVersion =
                routingSerializer.Deserialize(new MemoryStream(byteArray));
            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

            // try to do some routing on the deserialized version.
            var basicRouter =
                new DykstraRoutingPreProcessed(deserializedVersion.TagsIndex);
            IRouter<RouterPoint> router = new Router<PreProcessedEdge>(
                deserializedVersion, interpreter, basicRouter);
            RouterPoint source = router.Resolve(VehicleEnum.Car,
                                                new GeoCoordinate(51.0578532, 3.7192229));
            RouterPoint target = router.Resolve(VehicleEnum.Car,
                                                new GeoCoordinate(51.0576193, 3.7191801));

            // calculate the route.
            OsmSharpRoute route = router.Calculate(VehicleEnum.Car, source, target);
            Assert.IsNotNull(route);
            Assert.AreEqual(5, route.Entries.Length);

            float latitude, longitude;
            deserializedVersion.GetVertex(20, out latitude, out longitude);
            Assert.AreEqual(latitude, route.Entries[0].Latitude, 0.00001);
            Assert.AreEqual(longitude, route.Entries[0].Longitude, 0.00001);
            Assert.AreEqual(RoutePointEntryType.Start, route.Entries[0].Type);

            deserializedVersion.GetVertex(21, out latitude, out longitude);
            Assert.AreEqual(latitude, route.Entries[1].Latitude, 0.00001);
            Assert.AreEqual(longitude, route.Entries[1].Longitude, 0.00001);
            Assert.AreEqual(RoutePointEntryType.Along, route.Entries[1].Type);

            deserializedVersion.GetVertex(16, out latitude, out longitude);
            Assert.AreEqual(latitude, route.Entries[2].Latitude, 0.00001);
            Assert.AreEqual(longitude, route.Entries[2].Longitude, 0.00001);
            Assert.AreEqual(RoutePointEntryType.Along, route.Entries[2].Type);

            deserializedVersion.GetVertex(22, out latitude, out longitude);
            Assert.AreEqual(latitude, route.Entries[3].Latitude, 0.00001);
            Assert.AreEqual(longitude, route.Entries[3].Longitude, 0.00001);
            Assert.AreEqual(RoutePointEntryType.Along, route.Entries[3].Type);

            deserializedVersion.GetVertex(23, out latitude, out longitude);
            Assert.AreEqual(latitude, route.Entries[4].Latitude, 0.00001);
            Assert.AreEqual(longitude, route.Entries[4].Longitude, 0.00001);
            Assert.AreEqual(RoutePointEntryType.Stop, route.Entries[4].Type);
        }
Exemple #5
0
        /// <summary>
        /// Raises the create event.
        /// </summary>
        /// <param name="bundle">Bundle.</param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            OsmSharp.Logging.Log.Enable();

            //			OsmSharp.IO.Output.OutputStreamHost.RegisterOutputStream (
            //				new OsmSharp.Android.UI.IO.Output.ConsoleOutputStream ());

            // create the MapCSS image source.
            var imageSource = new MapCSSDictionaryImageSource();
            imageSource.Add("styles/default/parking.png",
                            Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.images.parking.png"));
            imageSource.Add("styles/default/bus.png",
                            Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.images.bus.png"));
            imageSource.Add("styles/default/postbox.png",
                            Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.images.postbox.png"));

            //			// load mapcss style interpreter.
            //			var mapCSSInterpreter = new MapCSSInterpreter(
            //				Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.test.mapcss"),
            //				imageSource);

            // initialize the data source.
            //var dataSource = new MemoryDataSource();
            //			var source = new XmlOsmStreamReader(
            //				Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.test.osm"));
            //			var source = new PBFOsmStreamReader(
            //				Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.test.osm.pbf"));
            //			dataSource.PullFromSource(source);

            // initialize map.
            var map = new Map();
            //map.AddLayer(new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/osm/{0}/{1}/{2}.png"));
            //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter));
            //			map.AddLayer(new LayerScene(Scene2DSimple.Deserialize(
            //							Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.wvl.osm.pbf.scene.simple"), true)));
            map.AddLayer(
                new LayerScene(
                Scene2DLayered.Deserialize(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(@"OsmSharp.Android.UI.Sample.wvl.map"), true)));

            //			var routingSerializer = new V2RoutingDataSourceLiveEdgeSerializer(true);
            //			var graphSerialized = routingSerializer.Deserialize(
            //				//Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.test.osm.pbf.routing.3"));
            //				Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.wvl.pbf.routing.4"));
            ////
            ////			var graphLayer = new LayerDynamicGraphLiveEdge(graphSerialized, mapCSSInterpreter);
            ////			map.AddLayer(graphLayer);
            //
            //			// calculate route.
            //			Router router = Router.CreateLiveFrom(
            //				graphSerialized,
            //				new OsmRoutingInterpreter());

            var routingSerializer = new OsmSharp.Routing.CH.Serialization.Sorted.CHEdgeDataDataSourceSerializer(false);
            var graphDeserialized = routingSerializer.Deserialize(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.wvl.routing"), true);

            _router = Router.CreateCHFrom(
                graphDeserialized, new CHRouter(),
                new OsmRoutingInterpreter());
            GeoCoordinate point1 = new GeoCoordinate(51.158075, 2.961545);
            GeoCoordinate point2 = new GeoCoordinate(51.190503, 3.004793);
            RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, point1);
            RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, point2);
            Route route1 = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2);
            RouteTracker routeTracker = new RouteTracker(route1, new OsmRoutingInterpreter());
            _enumerator = route1.GetRouteEnumerable(20).GetEnumerator();

            _routeLayer = new LayerRoute(map.Projection);
            _routeLayer.AddRoute (route1, SimpleColor.FromKnownColor(KnownColor.Blue).Value);
            map.AddLayer(_routeLayer);

            //			// create gpx layer.
            //			LayerGpx gpxLayer = new LayerGpx(map.Projection);
            //			gpxLayer.AddGpx(
            //				Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.test.gpx"));
            //			map.AddLayer(gpxLayer);

            //			// set control properties.
            //			var mapView = new MapView(this);
            //			mapView.MapMaxZoomLevel = 20;
            //			mapView.MapMinZoomLevel = 12;
            //			//var mapView = new MapGLView (this);
            //			mapView.Map = map;
            //			//mapView.Center = new GeoCoordinate(51.158075, 2.961545); // gistel
            //			//mapView.MapCenter = new GeoCoordinate (50.88672, 3.23899);
            //			mapView.MapCenter = new GeoCoordinate(51.26337, 4.78739);
            //			//mapView.Center = new GeoCoordinate(51.156803, 2.958887);
            //			mapView.MapZoomLevel = 15;

            //			var mapView = new OpenGLRenderer2D(
            //				this, null);

            //            _mapView = new MapView<MapGLView>(this, new MapGLView(this));

            _mapView = new MapView(this, new MapViewSurface(this));
            //_mapView = new MapView(this, new MapViewGLSurface(this));
            _mapView.Map = map;

            (_mapView as IMapView).AutoInvalidate = true;
            _mapView.MapMaxZoomLevel = 20;
            _mapView.MapMinZoomLevel = 12;
            _mapView.MapTilt = 0;
            //var mapView = new MapGLView (this);
            _mapView.MapCenter = new GeoCoordinate(51.158075, 2.961545); // gistel
            //mapView.MapCenter = new GeoCoordinate (50.88672, 3.23899);
            //mapLayout.MapCenter = new GeoCoordinate(51.26337, 4.78739);
            //mapView.Center = new GeoCoordinate(51.156803, 2.958887);
            _mapView.MapZoom = 17;
            //MapViewAnimator mapViewAnimator = new MapViewAnimator(mapLayout);
            //_mapView.MapTapEvent += delegate(GeoCoordinate geoCoordinate)
            //{
            //    _mapView.ZoomToMarkers();
            //    //_mapView.AddMarker(geoCoordinate).Click += new EventHandler(MainActivity_Click);
            //    //mapViewAnimator.Stop();
            //    //mapViewAnimator.Start(geoCoordinate, 15, new TimeSpan(0, 0, 2));
            //};

            //Create the user interface in code
            var layout = new RelativeLayout (this);
            layout.AddView(_mapView);

            _mapView.AddMarker(new GeoCoordinate(51.1612, 2.9795));
            _mapView.AddMarker(new GeoCoordinate(51.1447, 2.9483));

            //_mapView.ZoomToMarkers();

            _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5);

            Timer timer = new Timer(250);
            timer.Elapsed += new ElapsedEventHandler(TimerHandler);
            timer.Start();

            SetContentView (layout);
        }
        /// <summary>
        /// Processes a routing operation.
        /// </summary>
        /// <param name="operation"></param>
        /// <returns></returns>
        public object ProcessRoutingOperation(RoutingOperation operation)
        {
            // create the response object.
            RoutingResponse response;

            if (!this.IsReady())
            { // return that the service is not ready.
                response = new RoutingResponse
                               {
                                   Status = OsmSharpServiceResponseStatusEnum.Failed,
                                   StatusMessage = "Service is not ready!"
                               };

                return response;
            }

            if (operation.Hooks == null || operation.Hooks.Length == 0)
            { // there are no hooks!
                response = new RoutingResponse
                               {
                                   Status = OsmSharpServiceResponseStatusEnum.Failed,
                                   StatusMessage = "No hooks found!"
                               };

                return response;
            }

            try
            {
                // create the default edge matcher.
                IEdgeMatcher matcher = new LevenshteinEdgeMatcher();

                // create the router.
                var router = new Router<SimpleWeighedEdge>(
                    _data, _interpreter, new DykstraRoutingLive(
                        _data.TagsIndex));

                // execute the requested operation.
                switch (operation.Type)
                {
                    case RoutingOperationType.ManyToMany:
                        response = this.DoManyToMany(operation, router, matcher);
                        break;
                    case RoutingOperationType.Regular:
                        response = this.DoRegular(operation, router, matcher);
                        break;
                    case RoutingOperationType.TSP:
                        response = this.DoTSP(operation, router, matcher, false);
                        break;
                    case RoutingOperationType.OpenTSP:
                        response = this.DoTSP(operation, router, matcher, true);
                        break;
                    case RoutingOperationType.ToClosest:
                        response = this.DoToClosest(operation, router, matcher);
                        break;
                    default:
                        throw new Exception(string.Format("Invalid operation type:{0}",
                            operation.Type));
                }
            }
            catch (Exception ex)
            { // any exception was thrown.
                // create the response.
                response = new RoutingResponse
                               {
                                   Status = OsmSharpServiceResponseStatusEnum.Failed,
                                   StatusMessage = ex.Message
                               };
            }
            return response;
        }
Exemple #7
0
        /// <summary>
        /// Calculates the TSP.
        /// </summary>
        /// <param name="dataStream"></param>
        /// <param name="csvStream"></param>
        /// <param name="pbf"></param>
        /// <param name="vehicleEnum"></param>
        /// <returns></returns>
        private OsmSharpRoute CalculateTSP(Stream dataStream, Stream csvStream, bool pbf, VehicleEnum vehicleEnum)
        {
            // create the router.
            var interpreter = new OsmRoutingInterpreter();
            var tagsIndex = new OsmTagsIndex();

            // do the data processing.
            var osmData =
                new DynamicGraphRouterDataSource<PreProcessedEdge>(tagsIndex);
            var targetData = new PreProcessedDataGraphProcessingTarget(
                osmData, interpreter, osmData.TagsIndex, vehicleEnum);
            var dataProcessorSource = new XmlDataProcessorSource(dataStream);
            var sorter = new DataProcessorFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            IRouter<RouterPoint> router = new Router<PreProcessedEdge>(osmData, interpreter,
                new DykstraRoutingPreProcessed(osmData.TagsIndex));

            // read the source files.
            const int latitudeIdx = 2;
            const int longitudeIdx = 3;
            string[][] pointStrings = OsmSharp.Tools.DelimitedFiles.DelimitedFileHandler.ReadDelimitedFileFromStream(
                csvStream,
                DelimiterType.DotCommaSeperated);
            var points = new List<RouterPoint>();
            int cnt = 10;
            foreach (string[] line in pointStrings)
            {
                if (points.Count >= cnt)
                {
                    break;
                }
                var latitudeString = (string)line[latitudeIdx];
                var longitudeString = (string)line[longitudeIdx];

                //string route_ud = (string)line[1];

                double longitude = 0;
                double latitude = 0;
                if (double.TryParse(longitudeString, System.Globalization.NumberStyles.Any,
                    System.Globalization.CultureInfo.InvariantCulture, out longitude) &&
                   double.TryParse(latitudeString, System.Globalization.NumberStyles.Any,
                    System.Globalization.CultureInfo.InvariantCulture, out latitude))
                {
                    var point = new GeoCoordinate(latitude, longitude);

                    RouterPoint resolved = router.Resolve(VehicleEnum.Car, point);
                    if (resolved != null && router.CheckConnectivity(VehicleEnum.Car, resolved, 100))
                    {
                        points.Add(resolved);
                    }
                }
            }

            var tspSolver = new RouterTSPWrapper<RouterPoint, RouterTSP>(
                new RouterTSPAEXGenetic(), router, interpreter);
            return tspSolver.CalculateTSP(vehicleEnum, points.ToArray());
        }
Exemple #8
0
        /// <summary>
        /// Raises the create event.
        /// </summary>
        /// <param name="bundle">Bundle.</param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            OsmSharp.Logging.Log.Enable();
            OsmSharp.Logging.Log.RegisterListener(
                new OsmSharp.Android.UI.Log.LogTraceListener());

            // initialize map.
            var map = new Map();
            //map.AddLayer(new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/osm/{0}/{1}/{2}.png"));
            //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter));
            //			map.AddLayer(new LayerScene(Scene2DSimple.Deserialize(
            //							Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.wvl.osm.pbf.scene.simple"), true)));
            map.AddLayer(
                new LayerScene(
                    Scene2D.Deserialize(
                        Assembly.GetExecutingAssembly().GetManifestResourceStream(
                            @"OsmSharp.Android.UI.Sample.kempen-big/osm.pbf.scene.layered"), true)));

            var from = new GeoCoordinate(51.261203, 4.780760);
            var to = new GeoCoordinate(51.267797, 4.801362);

            var routingSerializer =
                new OsmSharp.Routing.CH.Serialization.Sorted.v2.CHEdgeDataDataSourceSerializer(false);
            TagsCollectionBase metaData = null;
            var graphDeserialized = routingSerializer.Deserialize(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "OsmSharp.Android.UI.Sample.kempen-big.osm.pbf.routing"), out metaData, true);

            _router = Router.CreateCHFrom(
                graphDeserialized, new CHRouter(),
                new OsmRoutingInterpreter());
            RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from);
            RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to);
            Route route1 = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2);
            RouteTracker routeTracker = new RouteTracker(route1, new OsmRoutingInterpreter());
            _enumerator = route1.GetRouteEnumerable(10).GetEnumerator();

            _routeLayer = new LayerRoute(map.Projection);
            _routeLayer.AddRoute (route1, SimpleColor.FromKnownColor(KnownColor.Blue, 125).Value, 12);
            map.AddLayer(_routeLayer);

            _mapView = new MapView(this, new MapViewSurface(this));
            //_mapView = new MapView(this, new MapViewGLSurface(this));
            _mapView.MapTapEvent += new MapViewEvents.MapTapEventDelegate(_mapView_MapTapEvent);
            _mapView.Map = map;

            _mapView.MapAllowPan = true;
            _mapView.MapAllowTilt = true;
            _mapView.MapAllowZoom = true;

            (_mapView as IMapView).AutoInvalidate = true;
            _mapView.MapMaxZoomLevel = 20;
            _mapView.MapMinZoomLevel = 10;
            _mapView.MapTilt = 0;
            _mapView.MapCenter = new GeoCoordinate(51.26371, 4.78601);
            _mapView.MapZoom = 16;

            _textView = new TextView(this);
            _textView.SetBackgroundColor(global::Android.Graphics.Color.White);
            _textView.SetTextColor(global::Android.Graphics.Color.Black);

            //Create the user interface in code
            var layout = new LinearLayout(this);
            layout.Orientation = Orientation.Vertical;
            layout.AddView(_textView);
            layout.AddView(_mapView);

            //_mapView.AddMarker(from);
            //_mapView.AddMarker(to);

            //_mapView.ZoomToMarkers();

            _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5, 17);

            //Timer timer = new Timer(500);
            //timer.Elapsed += new ElapsedEventHandler(TimerHandler);
            //timer.Start();

            SetContentView (layout);
        }
 /// <summary>
 /// Executes the CH contractions while verifying each step.
 /// </summary>
 /// <param name="xml"></param>
 /// <param name="crazyVerification"></param>
 private void DoTestCHSparseVerifiedContraction(string xml, bool crazyVerification)
 {
     _pathsBeforeContraction = new Dictionary<uint, Dictionary<uint, Dictionary<uint, PathSegment<long>>>>();
     _referenceRouter = null;
     if (crazyVerification)
     {
         this.BuildDykstraRouter(xml, new OsmRoutingInterpreter());
     }
     this.DoTestCHSparseVerifiedContraction(
         Assembly.GetExecutingAssembly().GetManifestResourceStream(xml));
 }
Exemple #10
0
        /// <summary>
        /// Raises the OnLoad event.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // initialize mapcss interpreter.
            var mapCSSInterpreter = new MapCSSInterpreter(new FileInfo(@"dark_roads.mapcss").OpenRead(), new MapCSSDictionaryImageSource());

            // initialize map.
            var map = new OsmSharp.UI.Map.Map();

            //// initialize router.
            try
            {
                _router = Router.CreateFrom(new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource(new FileInfo(@"C:\Users\smccloud\Documents\GitHub\OsmSharp.Service.Tiles\OsmSharp.Service.Tiles.SelfHost\bin\Debug\stcloud.osm.pbf").OpenRead()), new OsmRoutingInterpreter());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            //var scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), new List<float>(new float[] {
            //    16, 14, 12, 10 }));
            //var target = new StyleOsmStreamSceneTarget(
            //    mapCSSInterpreter, scene, new WebMercator());
            //var source = new PBFOsmStreamSource(
            //    new FileInfo(@"kempen.osm.pbf").OpenRead());
            //var progress = new OsmStreamFilterProgress();
            //progress.RegisterSource(source);
            //target.RegisterSource(progress);
            //target.Pull();

            ////var merger = new Scene2DObjectMerger();
            ////scene = merger.BuildMergedScene(scene);

            //map.AddLayer(new LayerScene(scene));
            //var dataSource = MemoryDataSource.CreateFromXmlStream(
            //    new FileInfo(@"D:\Dropbox\Dropbox\SharpSoftware\Projects\Eurostation ReLive\Server_Dropbox\OSM\relive_mechelen\mechelen_new.osm").OpenRead());
            //map.AddLayer(new LayerOsm(dataSource, mapCSSInterpreter, map.Projection));
            var layerTile = new LayerTile(@"http://*****:*****@"default.map").OpenRead(),
            //        true)));

            // initialize route/points layer.
            _layerRoute = new LayerRoute(new OsmSharp.Math.Geo.Projections.WebMercator());
            map.AddLayer(_layerRoute);
            _layerPrimitives = new LayerPrimitives(new OsmSharp.Math.Geo.Projections.WebMercator());
            map.AddLayer(_layerPrimitives);

            // set control properties.
            this.mapControl1.Map = map;
            this.mapControl1.MapCenter = new GeoCoordinate(45.5233, -94.14905);
            this.mapControl1.MapZoom = 14;
            this.mapControl1.Refresh();
            this.mapControl1.MapMouseClick += mapControl1_MapMouseClick;
            this.mapControl1.MapMouseMove += mapControl1_MapMouseMove;
        }
        /// <summary>
        /// Initializes this router API with an existing router.
        /// </summary>
        /// <param name="instance">The instance name.</param>
        /// <param name="router"></param>
        public static void Add(string instance, Router router)
        {
            // make sure vehicle are registered.
            Vehicle.RegisterVehicles();

            ApiBootstrapper.Add(instance, new RouterApi(router));
        }
        /// <summary>
        /// Initializes the View property.
        /// </summary>
        public override void LoadView()
        {
            base.LoadView ();

            // enable the logggin.
            OsmSharp.Logging.Log.Enable();
            OsmSharp.Logging.Log.RegisterListener(new OsmSharp.iOS.UI.Log.ConsoleTraceListener());

            // initialize map.
            var map = new Map();
            // add a tile layer.
            //map.AddLayer(new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/osm/{0}/{1}/{2}.png"));
            // add an online osm-data->mapCSS translation layer.
            //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter));
            // add a pre-processed vector data file.
            var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "OsmSharp.iOS.UI.Sample.kempen-big.osm.pbf.scene.layered");
            map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true)));

            // define dummy from and to points.
            var from = new GeoCoordinate(51.261203, 4.780760);
            var to = new GeoCoordinate(51.267797, 4.801362);

            // deserialize the pre-processed graph.
            var routingSerializer = new CHEdgeDataDataSourceSerializer(false);
            TagsCollectionBase metaData = null;
            var graphStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "OsmSharp.iOS.UI.Sample.kempen-big.osm.pbf.routing");
            var graphDeserialized = routingSerializer.Deserialize(graphStream, out metaData, true);

            // initialize router.
            _router = Router.CreateCHFrom(graphDeserialized, new CHRouter(), new OsmRoutingInterpreter());

            // resolve points.
            RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from);
            RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to);

            // calculate route.
            Route route = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2);
            RouteTracker routeTracker = new RouteTracker(route, new OsmRoutingInterpreter());
            _enumerator = route.GetRouteEnumerable(10).GetEnumerator();

            // add a router layer.
            _routeLayer = new LayerRoute(map.Projection);
            _routeLayer.AddRoute (route, SimpleColor.FromKnownColor(KnownColor.Blue, 125).Value, 12);
            map.AddLayer(_routeLayer);

            // define the mapview.
            _mapView = new MapView();
            //_mapView.MapTapEvent += new MapViewEvents.MapTapEventDelegate(_mapView_MapTapEvent);
            _mapView.Map = map;
            _mapView.MapMaxZoomLevel = 20;
            _mapView.MapMinZoomLevel = 10;
            _mapView.MapTilt = 0;
            _mapView.MapCenter = new GeoCoordinate(51.26371, 4.78601);
            _mapView.MapZoom = 18;

            // add markers.
            _mapView.AddMarker (from);
            _mapView.AddMarker (to);

            // create the route tracker animator.
            _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5, 17);

            // simulate a number of gps-location update along the calculated route.
            Timer timer = new Timer(250);
            timer.Elapsed += new ElapsedEventHandler(TimerHandler);
            timer.Start();

            View = _mapView;
        }
        /// <summary>
        /// Processes a resolve operation.
        /// </summary>
        /// <param name="operation"></param>
        /// <returns></returns>
        public object ProcessResolveResource(ResolveOperation operation)
        {
            // create the response object.
            var response = new ResolveResponse();

            if (!this.IsReady())
            { // return that the service is not ready.
                response.Status = OsmSharpServiceResponseStatusEnum.Failed;
                response.StatusMessage = "Service is not ready!";
                return response;
            }

            if (operation.Hooks == null || operation.Hooks.Length == 0)
            { // there are no hooks!
                response.Status = OsmSharpServiceResponseStatusEnum.Failed;
                response.StatusMessage = "No hooks found!";
                return response;
            }

            try
            {
                // create the default edge matcher.
                IEdgeMatcher matcher = new LevenshteinEdgeMatcher();

                // resolve the points and do the routing.
                var router = new Router<SimpleWeighedEdge>(
                    _data, _interpreter, new DykstraRoutingLive(
                        _data.TagsIndex));

                // create the coordinates list.
                response.ResolvedHooks = new RoutingHookResolved[operation.Hooks.Length];
                for (int idx = 0; idx < operation.Hooks.Length; idx++)
                {
                    // routing hook tags.
                    IDictionary<string, string> tags = operation.Hooks[idx].Tags.ConvertToDictionary();

                    // resolve the point.
                    RouterPoint resolved = router.Resolve(operation.Vehicle, new GeoCoordinate(
                        operation.Hooks[idx].Latitude, operation.Hooks[idx].Longitude), matcher, tags);

                    if (resolved != null)
                    { // the point was resolved successfully.
                        response.ResolvedHooks[idx] = new RoutingHookResolved
                        {
                            Id = operation.Hooks[idx].Id,
                            Latitude = (float)resolved.Location.Latitude,
                            Longitude = (float)resolved.Location.Longitude,
                            Succes = true
                        };
                    }
                    else
                    { // the hook was unsuccessfully resolved.
                        response.ResolvedHooks[idx] = new RoutingHookResolved
                        {
                            Id = operation.Hooks[idx].Id,
                            Succes = false
                        };
                    }
                }

                // report succes!
                response.Status = OsmSharpServiceResponseStatusEnum.Success;
                response.StatusMessage = string.Empty;
            }
            catch (Exception ex)
            { // any exception was thrown.
                response.Status = OsmSharpServiceResponseStatusEnum.Failed;
                response.StatusMessage = ex.Message;
            }
            return response;
        }
        /// <summary>
        /// Calculates the TSP.
        /// </summary>
        /// <param name="operation">The operation request.</param>
        /// <param name="router">The router.</param>
        /// <param name="matcher">Contains an algorithm to match points to the route network.</param>
        /// <param name="open">Flag indicating the type of TSP problem, open or not.</param>
        /// <returns></returns>
        private RoutingResponse DoTSP(
            RoutingOperation operation, Router<SimpleWeighedEdge> router, IEdgeMatcher matcher, bool open)
        {
            // create the response.
            var response = new RoutingResponse();

            // resolve the points and do the routing.
            var hooksPerRouterPoints = new Dictionary<RouterPoint, List<RoutingHook>>();
            var routerPoints = new List<RouterPoint>();
            var unroutableHooks = new List<RoutingHook>(); // save the unroutable hooks.
            for (int idx = 0; idx < operation.Hooks.Length; idx++)
            {
                // routing hook tags.
                IDictionary<string, string> tags = operation.Hooks[idx].Tags.ConvertToDictionary();

                // resolve the point.
                RouterPoint routerPoint = router.Resolve(operation.Vehicle, new GeoCoordinate(
                    operation.Hooks[idx].Latitude, operation.Hooks[idx].Longitude), matcher, tags);

                // check the result.
                if (routerPoint == null)
                { // this hook is not routable.
                    unroutableHooks.Add(operation.Hooks[idx]);
                }
                else
                { // a point to hook on was found!
                    List<RoutingHook> hooksAtPoint;
                    if (!hooksPerRouterPoints.TryGetValue(routerPoint, out hooksAtPoint))
                    { // the router point does not exist yet.
                        // check if the router point is routable.
                        if (router.CheckConnectivity(operation.Vehicle, routerPoint, 200))
                        {// the point is routable.
                            // create the hooks list at this point.
                            hooksAtPoint = new List<RoutingHook>();
                            hooksPerRouterPoints.Add(routerPoint, hooksAtPoint);

                            // add the new router point to the list.
                            routerPoint.Tags.Add(new KeyValuePair<string, string>("id", routerPoints.Count.ToString(
                                System.Globalization.CultureInfo.InvariantCulture)));
                            routerPoints.Add(routerPoint);

                            // add the hook.
                            hooksAtPoint.Add(operation.Hooks[idx]);
                        }
                        else
                        {// this hook is not routable.
                            unroutableHooks.Add(operation.Hooks[idx]);
                        }
                    }
                    else
                    {
                        // add the hook.
                        hooksAtPoint.Add(operation.Hooks[idx]);
                    }
                }
            }

            // add the unroutable hooks.
            response.UnroutableHooks = unroutableHooks.ToArray();

            // calculate all the weights.
            double[][] weights = router.CalculateManyToManyWeight(operation.Vehicle, routerPoints.ToArray(), routerPoints.ToArray());

            // calculate the TSP.
            var tspSolver = new RouterTSPAEXGenetic(300, 100);
            IRoute tspRoute = tspSolver.CalculateTSP(weights, routerPoints.Select(x => x.Location).ToArray(), 0, !open);

            // calculate the actual route.
            OsmSharpRoute route = null;
            foreach (Edge edge in tspRoute.Edges())
            {
                // calculate the actual edge-route.
                OsmSharpRoute edgeRoute = router.Calculate(operation.Vehicle,
                                                            routerPoints[edge.From], routerPoints[edge.To]);

                // add the routing hook tags.
                List<RoutingHook> fromHooks = hooksPerRouterPoints[routerPoints[edge.From]];
                edgeRoute.Entries[0].Points = new RoutePoint[fromHooks.Count];
                for (int hookIdx = 0; hookIdx < fromHooks.Count; hookIdx++)
                {
                    var hookPoint = new RoutePoint
                                        {
                                            Latitude = fromHooks[hookIdx].Latitude,
                                            Longitude = fromHooks[hookIdx].Longitude,
                                            Tags = fromHooks[hookIdx].Tags.ConvertToList().ConvertFrom()
                                        };

                    edgeRoute.Entries[0].Points[hookIdx] = hookPoint;
                }
                List<RoutingHook> toHooks = hooksPerRouterPoints[routerPoints[edge.To]];
                edgeRoute.Entries[edgeRoute.Entries.Length - 1].Points = new RoutePoint[toHooks.Count];
                for (int hookIdx = 0; hookIdx < toHooks.Count; hookIdx++)
                {
                    var hookPoint = new RoutePoint
                                        {
                                            Latitude = toHooks[hookIdx].Latitude,
                                            Longitude = toHooks[hookIdx].Longitude,
                                            Tags = toHooks[hookIdx].Tags.ConvertToList().ConvertFrom()
                                        };

                    edgeRoute.Entries[edgeRoute.Entries.Length - 1].Points[hookIdx] = hookPoint;
                }

                // concatenate routes.
                if (route == null)
                {
                    route = edgeRoute;
                }
                else
                {
                    route = OsmSharpRoute.Concatenate(route, edgeRoute);
                }
            }

            response.Route = route;

            // set the response as successfull.
            response.Status = OsmSharpServiceResponseStatusEnum.Success;

            return response;
        }
        /// <summary>
        /// Calculates the route from the source to the closest point.
        /// </summary>
        /// <param name="operation">The operation request.</param>
        /// <param name="router">The router.</param>
        /// <param name="matcher">Contains an algorithm to match points to the route network.</param>
        /// <returns></returns>
        private RoutingResponse DoToClosest(
            RoutingOperation operation, Router<SimpleWeighedEdge> router, IEdgeMatcher matcher)
        {
            // create the response.
            var response = new RoutingResponse();

            // resolve the points and do the routing.
            var hooksPerRouterPoints = new Dictionary<RouterPoint, List<RoutingHook>>();
            var routerPoints = new List<RouterPoint>();
            var unroutableHooks = new List<RoutingHook>(); // save the unroutable hooks.
            for (int idx = 0; idx < operation.Hooks.Length; idx++)
            {
                // routing hook tags.
                IDictionary<string, string> tags = operation.Hooks[idx].Tags.ConvertToDictionary();

                // resolve the point.
                RouterPoint routerPoint = router.Resolve(operation.Vehicle, new GeoCoordinate(
                    operation.Hooks[idx].Latitude, operation.Hooks[idx].Longitude), matcher, tags);

                // check the result.
                if (routerPoint == null)
                { // this hook is not routable.
                    if (idx == 0)
                    { // the first point has to be valid!
                        throw new Exception("Cannot resolve source point of a CalculateToClosest() operation.");
                    }
                    unroutableHooks.Add(operation.Hooks[idx]);
                }
                else
                { // a point to hook on was found!
                    List<RoutingHook> hooksAtPoint;
                    if (!hooksPerRouterPoints.TryGetValue(routerPoint, out hooksAtPoint))
                    { // the router point does not exist yet.
                        // check if the router point is routable.
                        if (router.CheckConnectivity(operation.Vehicle, routerPoint, 200))
                        {// the point is routable.
                            // create the hooks list at this point.
                            hooksAtPoint = new List<RoutingHook>();
                            hooksPerRouterPoints.Add(routerPoint, hooksAtPoint);

                            // add the new router point to the list.
                            routerPoint.Tags.Add(new KeyValuePair<string, string>("id", routerPoints.Count.ToString(
                                System.Globalization.CultureInfo.InvariantCulture)));
                            routerPoint.Tags.Add(new KeyValuePair<string, string>("idx", idx.ToString(
                                System.Globalization.CultureInfo.InvariantCulture)));
                            routerPoints.Add(routerPoint);

                            // add the hook.
                            hooksAtPoint.Add(operation.Hooks[idx]);
                        }
                        else
                        {// this hook is not routable.
                            if (idx == 0)
                            { // the first point has to be valid!
                                throw new Exception("Cannot resolve source point of a CalculateToClosest() operation.");
                            }
                            unroutableHooks.Add(operation.Hooks[idx]);
                        }
                    }
                    else
                    {
                        // add the hook.
                        hooksAtPoint.Add(operation.Hooks[idx]);
                    }
                }
            }

            // add the unroutable hooks.
            response.UnroutableHooks = unroutableHooks.ToArray();

            // extract the first point.
            RouterPoint first = routerPoints[0];
            routerPoints.RemoveAt(0);

            // calculate all the weights.
            OsmSharpRoute route = router.CalculateToClosest(operation.Vehicle, first, routerPoints.ToArray());

            if (route != null)
            {
                // add the routerpoint tags.
                string idxClosestString = route.Entries[route.Entries.Length - 1].Points[0].Tags[1].Value;
                int idxClosest = int.Parse(idxClosestString);

                // get the closest point.
                RoutingHook pointClosest = operation.Hooks[idxClosest];

                // get the routerpoint.
                RoutePoint routePoint = route.Entries[route.Entries.Length - 1].Points[0];

                // add the closest point tags.
                routePoint.Latitude = pointClosest.Latitude;
                routePoint.Longitude = pointClosest.Longitude;
                List<KeyValuePair<string, string>> tags = pointClosest.Tags.ConvertToList();
                tags.Add(new KeyValuePair<string, string>("id", pointClosest.Id.ToString())); // add the id-tag.
                routePoint.Tags = tags.ConvertFrom();

                response.Route = route;

                // set the response as successfull.
                response.Status = OsmSharpServiceResponseStatusEnum.Success;
            }

            return response;
        }
        /// <summary>
        /// Calculates a regular route.
        /// </summary>
        /// <param name="operation">The operation request.</param>
        /// <param name="router">The router.</param>
        /// <param name="matcher">Contains an algorithm to match points to the route network.</param>
        /// <returns></returns>
        private RoutingResponse DoRegular(
            RoutingOperation operation, Router<SimpleWeighedEdge> router, IEdgeMatcher matcher)
        {
            // create the response.
            var response = new RoutingResponse();

            OsmSharpRoute route = null;
            RouterPoint previous = null;
            var unroutableHooks = new List<RoutingHook>(); // keep a list of unroutable hooks.
            for (int idx = 0; idx < operation.Hooks.Length - 1; idx++)
            {
                // resolve the next point.
                RouterPoint next = router.Resolve(operation.Vehicle,
                                                  new GeoCoordinate(operation.Hooks[idx].Latitude,
                                                                    operation.Hooks[idx].Longitude), matcher,
                                                  operation.Hooks[idx].Tags.ConvertToDictionary());

                // check the routability.
                if (next != null &&
                    router.CheckConnectivity(operation.Vehicle, next, 200))
                { // the next point is routable.
                    if (previous != null)
                    {
                        // calculate the next part of the route.
                        OsmSharpRoute routePart = router.Calculate(operation.Vehicle,
                                                                 previous, next);
                        // concatenate the route part.
                        if (route == null)
                        {
                            route = routePart;
                        }
                        else
                        {
                            route = OsmSharpRoute.Concatenate(route, routePart);
                        }
                    }

                    // set the next to the previous.
                    previous = next;
                }
                else
                { // add the hook to the unroutable hooks list.
                   unroutableHooks.Add(operation.Hooks[idx]);
                }
            }

            // add the unroutable hooks.
            response.UnroutableHooks = unroutableHooks.ToArray();

            // set the response route.
            response.Route = route;

            // report succes!
            response.Status = OsmSharpServiceResponseStatusEnum.Success;
            response.StatusMessage = string.Empty;

            return response;
        }
        /// <summary>
        /// Calculates a matrix of weights between all given points.
        /// </summary>
        /// <param name="operation">The operation request.</param>
        /// <param name="router">The router.</param>
        /// <param name="matcher">Contains an algorithm to match points to the route network.</param>
        /// <returns></returns>
        private RoutingResponse DoManyToMany(
            RoutingOperation operation, Router<SimpleWeighedEdge> router, IEdgeMatcher matcher)
        {
            // create the response.
            var response = new RoutingResponse();

            // resolve the points and do the routing.
            var routerPoints = new List<RouterPoint>();
            var unroutableHooks = new List<RoutingHook>(); // save the unroutable hooks.
            for (int idx = 0; idx < operation.Hooks.Length; idx++)
            {
                // routing hook tags.
                IDictionary<string, string> tags = operation.Hooks[idx].Tags.ConvertToDictionary();

                // resolve the point.
                RouterPoint routerPoint = router.Resolve(operation.Vehicle, new GeoCoordinate(
                    operation.Hooks[idx].Latitude, operation.Hooks[idx].Longitude), matcher, tags);

                // check the result.
                if (routerPoint == null)
                {
                    // this hook is not routable.
                    unroutableHooks.Add(operation.Hooks[idx]);
                }
                else
                {
                    // a point to hook on was found!
                    // check if the router point is routable.
                    if (router.CheckConnectivity(operation.Vehicle, routerPoint, 200))
                    {
                        // the point is routable.

                        // add the new router point to the list.
                        routerPoint.Tags.Add(new KeyValuePair<string, string>("id", routerPoints.Count.ToString(
                            System.Globalization.CultureInfo.InvariantCulture)));
                        routerPoints.Add(routerPoint);
                    }
                    else
                    {
                        // this hook is not routable.
                        unroutableHooks.Add(operation.Hooks[idx]);
                    }
                }
            }

            // add the unroutable hooks.
            response.UnroutableHooks = unroutableHooks.ToArray();

            // calculate and fill the response.
            response.Weights = router.CalculateManyToManyWeight(operation.Vehicle, routerPoints.ToArray(),
                routerPoints.ToArray());

            // report succes!
            response.Status = OsmSharpServiceResponseStatusEnum.Success;
            response.StatusMessage = string.Empty;

            return response;
        }
 /// <summary>
 /// Executes the CH contractions while verifying each step.
 /// </summary>
 /// <param name="xml"></param>
 /// <param name="crazyVerification"></param>
 internal void DoTestCHEdgeDifferenceVerifiedContraction(string xml, bool crazyVerification)
 {
     _referenceRouter = null;
     if (crazyVerification)
     {
         this.BuildDykstraRouter(xml, new OsmRoutingInterpreter());
     }
     this.DoTestCHSparseVerifiedContraction(
         Assembly.GetExecutingAssembly().GetManifestResourceStream(xml));
 }
 /// <summary>
 /// Creates a new router wrapper.
 /// </summary>
 /// <param name="router"></param>
 public RouterApi(Router router)
 {
     _router = router;
 }
        /// <summary>
        /// Builds a raw router to compare against.
        /// </summary>
        /// <returns></returns>
        public void BuildDykstraRouter(string embeddedName,
            IOsmRoutingInterpreter interpreter)
        {
            var tagsIndex = new TagsIndex();

            // do the data processing.
            var data = new RouterDataSource<Edge>(new Graph<Edge>(), tagsIndex);
            var targetData = new GraphOsmStreamTarget(
                data, interpreter, tagsIndex, new Vehicle[] { Vehicle.Car });
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedName));
            var sorter = new OsmStreamFilterSort();
            sorter.RegisterSource(dataProcessorSource);
            targetData.RegisterSource(sorter);
            targetData.Pull();

            // initialize the router.
            _referenceRouter = Router.CreateFrom(data, new Dykstra(), interpreter);
        }
Exemple #21
0
        private void InitializeRouting(OsmSharp.UI.Map.Map map)
        {
            //var osmInterpreter = new OsmRoutingInterpreter();
            //_router = Router.CreateLiveFrom(new XmlOsmStreamSource(new FileInfo(@"c:\OSM\bin\wechel.osm").OpenRead()),
            //    osmInterpreter);

            // creates a new interpreter.
            var interpreter = new OsmRoutingInterpreter();
            //            var routingSerializer = new OsmSharp.Routing.CH.Serialization.Sorted.CHEdgeDataDataSourceSerializer(true);
            var original = CHEdgeGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                                   new FileInfo(@"c:\OSM\bin\wechel.osm").OpenRead()),
                                                               interpreter,
                                                               Vehicle.Car);
            //byte[] byteArray;
            //var stream = new MemoryStream();
            //using (stream)
            //{
            //    try
            //    {
            //        routingSerializer.Serialize(stream, original);
            //        byteArray = stream.ToArray();
            //    }
            //    catch (Exception)
            //    {
            //        throw;
            //    }
            //}
            //stream = new MemoryStream(byteArray);
            //Stream stream = new FileInfo(@"c:\OSM\bin\test.osm.pbf.routing.3").OpenRead();

            //IBasicRouterDataSource<CHEdgeData> deserializedVersion =
            //    routingSerializer.Deserialize(stream);
            var basicRouter = new CHRouter();
            _router = Router.CreateCHFrom(
                original, basicRouter, interpreter);

            _routeLayer = new LayerRoute(map.Projection);
            map.AddLayer(_routeLayer);
        }
        public override void LoadView()
        {
            OsmSharp.Logging.Log.Enable ();
            //            OsmSharp.Logging.Log.RegisterListener(
            //                new OsmSharp.Android.UI.Log.LogTraceListener());
            base.LoadView ();

            // initialize a test-map.
            var map = new Map ();
            map.AddLayer (new LayerScene (Scene2D.Deserialize (
                Assembly.GetExecutingAssembly ().GetManifestResourceStream (
                    "OsmSharp.iOS.UI.Sample.kempen-big.osm.pbf.scene.layered"),
                        true)));

            // Perform any additional setup after loading the view, typically from a nib.
            MapView mapView = new MapView ();
            _mapView = mapView;
            //mapViewAnimator = new MapViewAnimator (mapView);
            mapView.Map = map;
            mapView.MapCenter = new GeoCoordinate(51.26371, 4.78601); // wechel
            //			mapView.MapTapEvent+= delegate(GeoCoordinate geoCoordinate) {
            //				mapView.AddMarker(geoCoordinate).TouchDown  += MapMarkerClicked;
            //			};

            mapView.MapMaxZoomLevel = 18;
            mapView.MapMinZoomLevel = 12;
            mapView.MapZoom = 16;
            mapView.MapTilt = 30;

            TagsCollectionBase metaData;
            var routingSerializer = new OsmSharp.Routing.CH.Serialization.Sorted.v2.CHEdgeDataDataSourceSerializer(false);
            var graphDeserialized = routingSerializer.Deserialize(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "OsmSharp.iOS.UI.Sample.kempen-big.osm.pbf.routing"), out metaData, true);

            _router = Router.CreateCHFrom(
                graphDeserialized, new CHRouter(),
                new OsmRoutingInterpreter());

            var from = new GeoCoordinate(51.261203, 4.780760);
            var to = new GeoCoordinate(51.267797, 4.801362);

            RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from);
            RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to);
            Route route1 = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2);
            _enumerator = route1.GetRouteEnumerable(10).GetEnumerator();

            _routeLayer = new LayerRoute(map.Projection);
            _routeLayer.AddRoute (route1);
            map.AddLayer(_routeLayer);

            View = mapView;

            mapView.AddMarker(from);
            mapView.AddMarker(to);

            RouteTracker routeTracker = new RouteTracker(route1, new OsmRoutingInterpreter());
            _routeTrackerAnimator = new RouteTrackerAnimator(mapView, routeTracker, 5);

            //            Timer timer = new Timer (250);
            //            timer.Elapsed += new ElapsedEventHandler (TimerHandler);
            //            timer.Start ();
        }
        /// <summary>
        /// Creates a new best placement min max no depot vrp router.
        /// </summary>
        /// <param name="router"></param>
        /// <param name="max"></param>
        /// <param name="deliveryTime"></param>
        /// <param name="k"></param>
        /// <param name="deltaPercentage"></param>
        /// <param name="useSeedCost"></param>
        /// <param name="thresholdPrecentage"></param>
        public CheapestInsertionSolverWithImprovements(Router router,
            Second max, Second deliveryTime, int k, float deltaPercentage, bool useSeedCost, 
            float thresholdPrecentage)
            : base(max, deliveryTime)
        {
            _k = k;
            _deltaPercentage = deltaPercentage;
            _useSeedCost = useSeedCost;
            //            _thresholdPercentage = thresholdPrecentage;

            _intraImprovements = new List<IImprovement>();
            //_intra_improvements.Add(
            //    new OsmSharp.Math.TSP.ArbitraryInsertion.ArbitraryInsertionSolver());
            _intraImprovements.Add(
                new HillClimbing3OptSolver(true, true));

            _interImprovements = new List<IInterImprovement>();
            _interImprovements.Add(
                new ExchangeInterImprovement());
            _interImprovements.Add(
                new RelocateImprovement());
            //_inter_improvements.Add(
            //    new TwoOptInterImprovement());
            _interImprovements.Add(
                new RelocateExchangeInterImprovement());
            _interImprovements.Add(
                new CrossExchangeInterImprovement());
        }
        public override void LoadView()
        {
            OsmSharp.Logging.Log.Enable ();

            base.LoadView ();

            // initialize a test-map.
            var map = new Map ();
            map.AddLayer (new LayerScene (Scene2DLayered.Deserialize (
                Assembly.GetExecutingAssembly ().GetManifestResourceStream ("OsmSharp.iOS.UI.Sample.wvl.map"),
                    true)));

            // Perform any additional setup after loading the view, typically from a nib.
            MapView mapView = new MapView ();
            _mapView = mapView;
            //mapViewAnimator = new MapViewAnimator (mapView);
            mapView.Map = map;
            mapView.MapCenter = new GeoCoordinate(51.158075, 2.961545); // gistel
            //			mapView.MapTapEvent+= delegate(GeoCoordinate geoCoordinate) {
            //				mapView.AddMarker(geoCoordinate).TouchDown  += MapMarkerClicked;
            //			};

            mapView.MapMaxZoomLevel = 18;
            mapView.MapMinZoomLevel = 12;
            mapView.MapZoom = 16;
            mapView.MapTilt = 30;

            var routingSerializer = new OsmSharp.Routing.CH.Serialization.Sorted.CHEdgeDataDataSourceSerializer(false);
            var graphDeserialized = routingSerializer.Deserialize(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.iOS.UI.Sample.wvl.routing"), true);

            _router = Router.CreateCHFrom(
                graphDeserialized, new CHRouter(graphDeserialized),
                new OsmRoutingInterpreter());

            //			long before = DateTime.Now.Ticks;
            //
            //			var routeLocations = new GeoCoordinate[] {
            //				new GeoCoordinate (50.8247730, 2.7524706),
            //				new GeoCoordinate (50.8496394, 2.7301512),
            //				new GeoCoordinate (50.8927741, 2.6138545),
            //				new GeoCoordinate (50.8296363, 2.8869437)
            //			};
            //
            //			var routerPoints = new RouterPoint[routeLocations.Length];
            //			for (int idx = 0; idx < routeLocations.Length; idx++) {
            //				routerPoints [idx] = router.Resolve (Vehicle.Car, routeLocations [idx]);
            //
            //				mapView.AddMarker (routeLocations [idx]);
            //			}
            //			OsmSharp.Routing.TSP.RouterTSPWrapper<RouterTSPAEXGenetic> tspRouter = new OsmSharp.Routing.TSP.RouterTSPWrapper<RouterTSPAEXGenetic> (
            //				new RouterTSPAEXGenetic (10, 20), router);
            //
            //			Route route = tspRouter.CalculateTSP (Vehicle.Car, routerPoints);
            //
            //			long after = DateTime.Now.Ticks;
            //
            //			OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information,"Routing & TSP in {0}ms",
            //			                                new TimeSpan (after - before).TotalMilliseconds);
            // 51.160477" lon="2.961497
            GeoCoordinate point1 = new GeoCoordinate(51.158075, 2.961545);
            GeoCoordinate point2 = new GeoCoordinate(51.190503, 3.004793);

            //GeoCoordinate point1 = new GeoCoordinate(51.159132, 2.958755);
            //GeoCoordinate point2 = new GeoCoordinate(51.160477, 2.961497);
            RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, point1);
            RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, point2);
            Route route1 = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2);
            _enumerator = route1.GetRouteEnumerable(10).GetEnumerator();

            //List<Instruction> instructions = InstructionGenerator.Generate(route1, new OsmRoutingInterpreter());
            //
            _routeLayer = new LayerRoute(map.Projection);
            _routeLayer.AddRoute (route1);
            map.AddLayer(_routeLayer);

            View = mapView;

            mapView.AddMarker(new GeoCoordinate(51.1612, 2.9795));
            mapView.AddMarker(new GeoCoordinate(51.1447, 2.9483));
            mapView.AddMarker(point1);
            mapView.AddMarker(point2);
            mapView.AddMarker(new GeoCoordinate(51.1612, 2.9795));
            mapView.AddMarker(new GeoCoordinate(51.1447, 2.9483));
            mapView.AddMarker(new GeoCoordinate(51.1612, 2.9795));
            mapView.AddMarker(new GeoCoordinate(51.1447, 2.9483));
            //
            //			//mapView.ZoomToMarkers();

            //GeoCoordinateBox box = new GeoCoordinateBox (new GeoCoordinate[] { point1, point2 });
            //
            mapView.MapTapEvent += delegate(GeoCoordinate geoCoordinate)
            {
                //_routeTrackerAnimator.Track(box.GenerateRandomIn());

                //_mapView.AddMarker(geoCoordinate).Click += new EventHandler(MainActivity_Click);
                //mapViewAnimator.Stop();
                //mapViewAnimator.Start(geoCoordinate, 15, new TimeSpan(0, 0, 2));
            };

            RouteTracker routeTracker = new RouteTracker(route1, new OsmRoutingInterpreter());
            _routeTrackerAnimator = new RouteTrackerAnimator(mapView, routeTracker, 5);
            //
            //				Timer timer = new Timer (150);
            //				timer.Elapsed += new ElapsedEventHandler (TimerHandler);
            //				timer.Start ();
            //
            //			Task.Factory.StartNew (() => {
            //				System.Threading.Thread.Sleep(200); // do something.
            //				InvokeOnMainThread (() => {
            //					mapView.ZoomToMarkers ();
            //				});
            //			});

            //
        }
Exemple #25
0
        /// <summary>
        /// Raises the create event.
        /// </summary>
        /// <param name="bundle">Bundle.</param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            // enable the logggin.
            OsmSharp.Logging.Log.Enable();
            OsmSharp.Logging.Log.RegisterListener(new OsmSharp.Android.UI.Log.LogTraceListener());

            // initialize map.
            var map = new Map();
            // add a tile layer.
            //map.AddLayer(new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/osm/{0}/{1}/{2}.png"));
            // add an online osm-data->mapCSS translation layer.
            //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter));
            // add a pre-processed vector data file.
            var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"OsmSharp.Android.UI.Sample.kempen-big.osm.pbf.scene.layered");
            map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true)));

            // define dummy from and to points.
            var from = new GeoCoordinate(51.261203, 4.780760);
            var to = new GeoCoordinate(51.267797, 4.801362);

            // deserialize the pre-processed graph.
            var routingSerializer = new CHEdgeDataDataSourceSerializer(false);
            TagsCollectionBase metaData = null;
            var graphStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.kempen-big.osm.pbf.routing");
            var graphDeserialized = routingSerializer.Deserialize(graphStream, out metaData, true);

            // initialize router.
            _router = Router.CreateCHFrom(graphDeserialized, new CHRouter(), new OsmRoutingInterpreter());

            // resolve points.
            RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from);
            RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to);

            // calculate route.
            Route route = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2);
            RouteTracker routeTracker = new RouteTracker(route, new OsmRoutingInterpreter());
            _enumerator = route.GetRouteEnumerable(10).GetEnumerator();

            // add a router layer.
            _routeLayer = new LayerRoute(map.Projection);
            _routeLayer.AddRoute (route, SimpleColor.FromKnownColor(KnownColor.Blue, 125).Value, 12);
            map.AddLayer(_routeLayer);

            // define the mapview.
            _mapView = new MapView(this, new MapViewSurface(this));
            //_mapView = new MapView(this, new MapViewGLSurface(this));
            //_mapView.MapTapEvent += new MapViewEvents.MapTapEventDelegate(_mapView_MapTapEvent);
            (_mapView as IMapView).AutoInvalidate = true;
            _mapView.Map = map;
            _mapView.MapMaxZoomLevel = 20;
            _mapView.MapMinZoomLevel = 10;
            _mapView.MapTilt = 0;
            _mapView.MapCenter = new GeoCoordinate(51.26371, 4.78601);
            _mapView.MapZoom = 18;

            // add markers.
            _mapView.AddMarker (from);
            _mapView.AddMarker (to);

            // initialize a text view to display routing instructions.
            _textView = new TextView(this);
            _textView.SetBackgroundColor(global::Android.Graphics.Color.White);
            _textView.SetTextColor(global::Android.Graphics.Color.Black);

            // add the mapview to the linear layout.
            var layout = new LinearLayout(this);
            layout.Orientation = Orientation.Vertical;
            layout.AddView(_textView);
            layout.AddView(_mapView);

            // create the route tracker animator.
            _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5, 18);

            // simulate a number of gps-location update along the calculated route.
            Timer timer = new Timer(500);
            timer.Elapsed += new ElapsedEventHandler(TimerHandler);
            timer.Start();

            SetContentView (layout);
        }
        /// <summary>
        /// Calculates a route to test on.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        private OsmSharpRoute Calculate(GeoCoordinate from, GeoCoordinate to)
        {
            if (_router == null)
            {
                var interpreter = new OsmRoutingInterpreter();
                var tagsIndex = new OsmTagsIndex();

                // do the data processing.
                var memoryData =
                    new DynamicGraphRouterDataSource<SimpleWeighedEdge>(tagsIndex);
                var targetData = new SimpleWeighedDataGraphProcessingTarget(
                    memoryData, interpreter, memoryData.TagsIndex, VehicleEnum.Car);
                var dataProcessorSource = new XmlDataProcessorSource(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream(
                        "OsmSharp.UnitTests.test_instructions.osm"));
                var sorter = new DataProcessorFilterSort();
                sorter.RegisterSource(dataProcessorSource);
                targetData.RegisterSource(sorter);
                targetData.Pull();

                _router = new Router<SimpleWeighedEdge>(
                    memoryData, interpreter, new DykstraRoutingLive(memoryData.TagsIndex));
            }

            RouterPoint fromPoint = _router.Resolve(VehicleEnum.Car, from);
            RouterPoint toPoint = _router.Resolve(VehicleEnum.Car, to);
            return _router.Calculate(VehicleEnum.Car, fromPoint, toPoint);
        }
        /// <summary>
        /// Tests routing within a bounding box.
        /// </summary>
        /// <param name="router"></param>
        /// <param name="box"></param>
        /// <param name="testCount"></param>
        public static void TestRouting(Router router, GeoCoordinateBox box, int testCount)
        {
            var performanceInfo = new PerformanceInfoConsumer("CHSerializedRouting");
            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes: Resolving...", testCount);
            int successCount = 0;
            int totalCount = testCount;
            var resolvedPoints = new List<RouterPoint>();
            while (testCount > 0)
            {
                var from = box.GenerateRandomIn();
                var to = box.GenerateRandomIn();

                var fromPoint = router.Resolve(Vehicle.Car, from);
                var toPoint = router.Resolve(Vehicle.Car, to);

                resolvedPoints.Add(fromPoint);
                resolvedPoints.Add(toPoint);

                testCount--;
            }
            performanceInfo.Stop();

            performanceInfo = new PerformanceInfoConsumer("CHSerializedRouting");
            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes: Routing...", testCount);
            for (int idx = 0; idx < resolvedPoints.Count; idx = idx + 2)
            {
                var fromPoint = resolvedPoints[idx];
                var toPoint = resolvedPoints[idx + 1];
                if (fromPoint != null && toPoint != null)
                {
                    var route = router.Calculate(Vehicle.Car, fromPoint, toPoint, float.MaxValue, true);
                    if (route != null)
                    {
                        successCount++;
                    }
                }
            }
            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHSerializedRouting", OsmSharp.Logging.TraceEventType.Information,
                string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }