Example #1
0
        /// <summary>
        /// Calculates the route.
        /// </summary>
        /// <param name="transportMode">The transport mode.</param>
        /// <param name="start">The start point.</param>
        /// <param name="end">The end point.</param>
        /// <returns>
        /// A new <see cref="RouteModel" /> with the route details.
        /// </returns>
        public RouteModel CalculatePointToPoint(VehicleEnum transportMode, GeoCoordinate start, GeoCoordinate end)
        {
            // calculate route.
            var startPoint = router.Resolve(transportMode, start);
            var endPoint   = router.Resolve(transportMode, end);
            var route      = router.Calculate(transportMode, startPoint, endPoint);

            if (route == null)
            {
                throw new RoutingException("No matching route found.");
            }

            var coordinates = route.Entries
                              .Select(x => new Coordinate(x.Latitude, x.Longitude))
                              .ToList();

            var lineString = new LineString(coordinates);

            var feature = new Feature(
                lineString,
                new Dictionary <string, object>
            {
                { "name", "Test route result." },
                { "distance", route.TotalDistance },
                { "journeytime", route.TotalTime },
            });

            var generator    = new InstructionGenerator();
            var instructions = generator.Generate(route, interpreter, new SimpleEnglishLanguageGenerator());

            return(new RouteModel
            {
                Results = new ResultSet(feature)
            });
        }
Example #2
0
        private ExecutionState <GroupState> Run(string code, InstructionExecutor <GroupState> executor = null)
        {
            (Synfron.Staxe.Matcher.Data.IMatchData matchData, bool success, int _, int?_, string _) = LanguageMatchEngine.Match(code);

            Assert.True(success);

            InstructionGenerator generator = new InstructionGenerator();
            IList <Instruction <GroupState> > instructions = generator.Generate(matchData);

            InstructionOptimizer <GroupState> optimizer = new InstructionOptimizer <GroupState>();

            instructions = optimizer.Optimize(instructions).ToArray();

            GroupState groupState = new GroupState();

            groupState.Group.Instructions = instructions.ToArray();
            ExecutionState <GroupState> executionState = new ExecutionState <GroupState>(groupState);

            executor = executor ?? new InstructionExecutor <GroupState>()
            {
                ExternalDynamicPointers = NativeLocator.GetNativePointer,
                ValueProvider           = new ValueProvider()
            };
            PrintDiagnostics.EnableDiagnostics(code, executor, executionState, true);

            executor.Execute(executionState);

            return(executionState);
        }
 private static InstructionGenerator <Instruction> .TryGetDelegate[] GetInstructionDelegatesFrom(InstructionCarGenerator.TryGetDelegateWithLanguageReference[] tryGetDelegates, ILanguageReference languageReference)
 {
     InstructionGenerator <Instruction> .TryGetDelegate[] tryGetDelegateArray = new InstructionGenerator <Instruction> .TryGetDelegate[tryGetDelegates.Length];
     for (int index = 0; index < tryGetDelegateArray.Length; ++index)
     {
         tryGetDelegateArray[index] = InstructionCarGenerator.GetInstructionDelegateFrom(tryGetDelegates[index], languageReference);
     }
     return(tryGetDelegateArray);
 }
Example #4
0
        public void TestMergeInstructions()
        {
            var route = new Route()
            {
                Shape = new Coordinate[]
                {
                    new Coordinate(0, 0),
                    new Coordinate(0, 0),
                    new Coordinate(0, 0)
                },
                ShapeMeta = new Route.Meta[]
                {
                    new Route.Meta()
                    {
                        Shape = 0
                    },
                    new Route.Meta()
                    {
                        Shape = 1
                    },
                    new Route.Meta()
                    {
                        Shape = 2
                    }
                },
                TotalDistance = 0,
                TotalTime     = 0
            };

            var generator = new InstructionGenerator <string>(route,
                                                              new InstructionGenerator <string> .TryGetDelegate[]
            {
                (RoutePosition pos, ILanguageReference langRef, out string instruction) =>
                {
                    instruction = string.Format("Instruction {0}", pos.Shape);
                    return(1);
                }
            },
                                                              (Route r, ILanguageReference langRef, string i1, string i2, out string i) =>
            {
                i = string.Format("Merged instruction: {0} -> {1}",
                                  i1, i2);
                return(true);
            }, new MockLanguageReference());

            generator.Run();

            var instructions = generator.Instructions;

            Assert.IsNotNull(instructions);
            Assert.AreEqual(1, instructions.Count);
            Assert.AreEqual("Merged instruction: Merged instruction: Instruction 0 -> Instruction 1 -> Instruction 2",
                            instructions[0]);
        }
Example #5
0
        public void TestOverwritingInstructions()
        {
            var route = new Route()
            {
                Shape = new Coordinate[]
                {
                    new Coordinate(0, 0),
                    new Coordinate(0, 0),
                    new Coordinate(0, 0)
                },
                ShapeMeta = new Route.Meta[]
                {
                    new Route.Meta()
                    {
                        Shape = 0
                    },
                    new Route.Meta()
                    {
                        Shape = 1
                    },
                    new Route.Meta()
                    {
                        Shape = 2
                    }
                },
                TotalDistance = 0,
                TotalTime     = 0
            };

            var generator = new InstructionGenerator <string>(route,
                                                              new InstructionGenerator <string> .TryGetDelegate[]
            {
                (RoutePosition pos, ILanguageReference langRef, out string instruction) =>
                {
                    if (pos.Shape == 2)
                    {
                        instruction = "The one and only instruction!";
                        return(3);
                    }
                    instruction = string.Format("Instruction {0}", pos.Shape);
                    return(1);
                }
            }, new MockLanguageReference());

            generator.Run();

            var instructions = generator.Instructions;

            Assert.IsNotNull(instructions);
            Assert.AreEqual(1, instructions.Count);
            Assert.AreEqual("The one and only instruction!", instructions[0]);
        }
        /// <summary>
        /// Calculates routes, generates instructions and compares instructions.
        /// </summary>
        /// <param name="embeddedXml"></param>
        /// <param name="point1"></param>
        /// <param name="point2"></param>
        protected void DoInstructionComparisonTest(string embeddedXml, GeoCoordinate point1, GeoCoordinate point2)
        {
            Meter delta = 1;

            var interpreter = new OsmRoutingInterpreter();

            var router = this.CreateRouter(interpreter,
                                           embeddedXml);
            var referenceRouter = this.CreateReferenceRouter(interpreter,
                                                             embeddedXml);

            // resolve the three points in question.
            var point1resolved = router.Resolve(Vehicle.Car, point1, true);
            var point2resolved = router.Resolve(Vehicle.Car, point2, true);

            // calculate two smaller routes.
            var route12 = router.Calculate(Vehicle.Car,
                                           point1resolved, point2resolved);

            // resolve the three points in question.
            RouterPoint pointReference1resolved = referenceRouter.Resolve(Vehicle.Car, point1, true);
            RouterPoint pointReference2resolved = referenceRouter.Resolve(Vehicle.Car, point2, true);

            // test the resolved points.
            Assert.AreEqual(0, point1resolved.Location.DistanceReal(pointReference1resolved.Location).Value, delta.Value);
            Assert.AreEqual(0, point2resolved.Location.DistanceReal(pointReference2resolved.Location).Value, delta.Value);

            // calculate two smaller routes.
            Route routeReference12 = referenceRouter.Calculate(Vehicle.Car,
                                                               pointReference1resolved, pointReference2resolved);

            // compares the two routes.
            this.CompareRoutes(routeReference12, route12);

            // create the language generator.
            var languageGenerator = new LanguageTestGenerator();

            // generate the instructions.
            var instructions          = InstructionGenerator.Generate(route12, interpreter, languageGenerator);
            var instructionsReference = InstructionGenerator.Generate(routeReference12, interpreter, languageGenerator);

            Assert.AreEqual(instructions.Count, instructionsReference.Count);
            for (int idx = 0; idx < instructions.Count; idx++)
            {
                Assert.AreEqual(instructions[idx].Location.Center,
                                instructionsReference[idx].Location.Center);
                Assert.AreEqual(instructions[idx].Text,
                                instructionsReference[idx].Text);
            }
        }
Example #7
0
        /// <summary>
        /// Tests routing between two points and the associated instructions.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="stream"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public static void TestSerializeRoutingInstrictions(string name, Stream stream,
                                                            GeoCoordinate from, GeoCoordinate to)
        {
            PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("CHSerializedRouting");

            performanceInfo.Start();
            performanceInfo.Report("Routing & generating instructions...");

            TagsCollectionBase metaData = null;
            var routingSerializer       = new CHEdgeDataDataSourceSerializer();
            var graphDeserialized       = routingSerializer.Deserialize(
                stream, out metaData, true);

            var interpreter = new OsmRoutingInterpreter();
            var router      = Router.CreateCHFrom(
                graphDeserialized, new CHRouter(),
                interpreter);

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

            List <Instruction> instructions = new List <Instruction>();

            if (fromPoint != null && toPoint != null)
            {
                Route route = router.Calculate(Vehicle.Car, fromPoint, toPoint);
                if (route != null)
                {
                    instructions = InstructionGenerator.Generate(route, interpreter);
                }
            }

            performanceInfo.Stop();

            if (instructions.Count == 0)
            {
                OsmSharp.Logging.Log.TraceEvent("CHSerializedRouting", OsmSharp.Logging.TraceEventType.Information,
                                                "Routing unsuccesfull!");
            }
            else
            {
                foreach (Instruction instruction in instructions)
                {
                    OsmSharp.Logging.Log.TraceEvent("CHSerializedRouting", OsmSharp.Logging.TraceEventType.Information,
                                                    instruction.Text);
                }
            }
        }
Example #8
0
        public void UndefinedVariableTest()
        {
            string undefined = @"
			var test = 50;
			var testCopy = noTest;"            ;

            (Synfron.Staxe.Matcher.Data.IMatchData matchData, bool success, int _, int?_, string _) = LanguageMatchEngine.Match(undefined);

            Assert.True(success);

            InstructionGenerator generator = new InstructionGenerator();

            LanguageConstraintException exception = Assert.Throws <LanguageConstraintException>(() => generator.Generate(matchData));

            Assert.Contains("Variable 'noTest' is not declared.", exception.Message);
            Assert.Equal(undefined.IndexOf("noTest"), exception.Position);
        }
Example #9
0
        private void Generate_Click(object sender, RoutedEventArgs e)
        {
            float left = 0;
            float top  = 0;

            InstructionGenerator.TopLeft     = new Vector2(left, top);
            InstructionGenerator.FontSize    = 36;
            InstructionGenerator.FontRadius  = 0.05;
            InstructionGenerator.FontSpacing = 0.2;
            InstructionGenerator.ArcInterpolationDistance = 0.1;
            InstructionGenerator.Speed = 4000;
            StringBuilder output = new StringBuilder();

            output.Append(InstructionGenerator.Initialize());

            //foreach (float fontSize in new float[] { 10, 15, 20, 25, 30 })
            //{
            //    InstructionGenerator.FontSize = fontSize;
            //    output.Append(new string($"{fontSize:0} Checkbox".SelectMany(c => InstructionGenerator.Execute(c)).ToArray()));
            //    InstructionGenerator.TopLeft = new Vector2(left, InstructionGenerator.TopLeft.Y - (1.5f * fontSize) - InstructionGenerator.FontSpacing * fontSize);
            //}

            foreach (char c in Input.Text)
            {
                switch (c)
                {
                case '\r':
                    InstructionGenerator.TopLeft = new Vector2(left, InstructionGenerator.TopLeft.Y);
                    break;

                case '\n':
                    InstructionGenerator.TopLeft = new Vector2(InstructionGenerator.TopLeft.X, InstructionGenerator.TopLeft.Y - (1.5f * InstructionGenerator.FontSize) - InstructionGenerator.FontSpacing * InstructionGenerator.FontSize);
                    break;

                default:
                    output.Append(InstructionGenerator.Execute(c));
                    break;
                }
            }

            //output.Append(InstructionGenerator.GoHome());

            Output.Text = output.ToString();
        }
Example #10
0
        public void InvalidAssignmentTest()
        {
            string invalidAssignment = @"
			var callable = () {
			};

			callable() = 7;"            ;

            (Synfron.Staxe.Matcher.Data.IMatchData matchData, bool success, int _, int?_, string _) = LanguageMatchEngine.Match(invalidAssignment);

            Assert.True(success);

            InstructionGenerator generator = new InstructionGenerator();

            LanguageConstraintException exception = Assert.Throws <LanguageConstraintException>(() => generator.Generate(matchData));

            Assert.Contains("Cannot assign to the return of a function.", exception.Message);
            Assert.Equal(invalidAssignment.IndexOf("= 7"), exception.Position);
        }
Example #11
0
        /// <summary>
        /// Gets a feature collection representing the given route based on the given aggregation type.
        /// </summary>
        /// <param name="route"></param>
        /// <param name="aggregationType"></param>
        /// <returns></returns>
        public override FeatureCollection GetFeatures(Route route, RouteAggregationType aggregationType)
        {
            if (route == null)
            {
                throw new ArgumentNullException("route");
            }
            if (aggregationType == RouteAggregationType.All)
            {  // one LineString.
                var featureCollection = new FeatureCollection();
                var coordinates       = route.GetPoints();
                if (coordinates.Count > 1)
                {
                    var lineString = new LineString(coordinates.ToArray());

                    var attributes = new SimpleGeometryAttributeCollection();
                    attributes.Add("osmsharp:total_time", route.TotalTime.ToInvariantString());
                    attributes.Add("osmsharp:total_distance", route.TotalDistance.ToInvariantString());

                    var feature = new Feature(lineString, attributes);

                    featureCollection.Add(feature);
                }
                return(featureCollection);
            }
            else if (aggregationType == RouteAggregationType.Modal)
            { // modal.
                // aggregate.
                var aggregator   = new ModalAggregator(new OsmRoutingInterpreter());
                var microPlanner = new ModalMicroPlanner(new ModalLanguageGenerator(), new OsmRoutingInterpreter());
                var aggregated   = aggregator.Aggregate(route);
                var instructions = InstructionGenerator.Generate(microPlanner, route, aggregated);

                return(this.GetFeatures(route, instructions));
            }
            else // modal and instructions.
            { // instructions.
                var instructions = this.GetInstructions(route);

                return(this.GetFeatures(route, instructions));
            }
        }
Example #12
0
        public void BooleanTests(string expression, bool expectedResult)
        {
            (Synfron.Staxe.Matcher.Data.IMatchData matchData, bool success, int _, int?_, string _) = LanguageMatchEngine.Match(expression);

            Assert.True(success);

            InstructionGenerator generator = new InstructionGenerator();
            IList <Instruction <GroupState> > instructions = generator.Generate(matchData);

            InstructionOptimizer <GroupState> optimizer = new InstructionOptimizer <GroupState>();

            instructions = optimizer.Optimize(instructions);
            GroupState groupState = new GroupState();

            groupState.Group.Instructions = instructions.ToArray();
            ExecutionState <GroupState>      executionState = new ExecutionState <GroupState>(groupState);
            InstructionExecutor <GroupState> executor       = new InstructionExecutor <GroupState>();

            executor.Execute(executionState);

            Assert.Equal(expectedResult, ((DefaultBooleanValue <GroupState>)executionState.ListRegister.Last().Value).Data);
        }
Example #13
0
        private void RunCodeButton_Click(object sender, RoutedEventArgs e)
        {
            ListViewArea.Items.Clear();
            ListViewArea.Visibility = Visibility.Collapsed;
            Splitter.Visibility     = Visibility.Collapsed;
            var parser = new Parser(); //此处可使用同步线程,不过为了简单起见,就不做同步线程了
            var lexer  = new Lexer();

            StopButton.IsEnabled = true;
            ResultTextBox.Focus();
            var instructions = new InstructionGenerator();
            var interpreter  = new Interpreter();

            lexer.Chars = TextEditor.Text.ToCharArray();
            lexer.LexAnalyze();
            ResultTextBox.Text = "···········Running Code...\n\n";
            if (lexer.ErrorInfoStrb.ToString().Length == 0)
            {
                parser.Tokens = lexer.Words;
                parser.SyntaxAnalyze();
                if (!parser.IsParseError)
                {
                    instructions.Tree = parser.SyntaxTree;
                    instructions.GenerateInstructions();
                    if (instructions.Error == null)
                    {
                        interpreter.Codes = instructions.Codes;
                        interpreter.RunCode();
                        if (interpreter.Error == null)
                        {
                            ResultTextBox.Text += $"{interpreter.result}\n";
                            ResultTextBox.Text += "\n···········Process Complete!";
                        }

                        else
                        {
                            ResultTextBox.Text += interpreter.Error;
                            ResultTextBox.Text += "\n···········Process Failed!";
                        }
                    }
                    else
                    {
                        ResultTextBox.Text += instructions.Error;
                        ResultTextBox.Text += "\n···········Semantic Analysis Failed!\n";
                        ResultTextBox.Text += "\n···········Code Is Not Running!";
                    }
                }
                else
                {
                    ResultTextBox.Text += parser.Error;
                    ResultTextBox.Text += "\n···········Syntactic Analysis Failed!\n";
                    ResultTextBox.Text += "\n···········Semantic Analysis Not Implemented!";
                }


                StopButton.IsEnabled = false;
                if (TreeViewRadioButton.IsChecked != true || NoneRadioButton.IsChecked == true)
                {
                    TreeViewArea.Visibility = Visibility.Collapsed;
                    Splitter.Visibility     = Visibility.Collapsed;
                }
            }
            else
            {
                ResultTextBox.Text += lexer.ErrorInfoStrb.ToString();
                ResultTextBox.Text += "\n···········Lexical Analysis Failed!\n";
                ResultTextBox.Text += "\n···········Syntactic Analysis Not Implemented!";
            }
        }
Example #14
0
        private void RunInterpreterButton_Click(object sender, RoutedEventArgs e)
        {
            ListViewArea.Items.Clear();
            ListViewArea.Visibility = Visibility.Collapsed;
            Splitter.Visibility     = Visibility.Collapsed;
            var parser = new Parser(); //此处可使用同步线程,不过为了简单起见,就不做同步线程了
            var lexer  = new Lexer();

            StopButton.IsEnabled = true;
            ResultTextBox.Focus();
            var instructions = new InstructionGenerator();

            lexer.Chars = TextEditor.Text.ToCharArray();
            lexer.LexAnalyze();
            ResultTextBox.Text = "···········Interpreter Analyzing...\n\n";
            if (lexer.ErrorInfoStrb.ToString().Length == 0)
            {
                parser.Tokens = lexer.Words;
                parser.SyntaxAnalyze();
                if (!parser.IsParseError)
                {
                    instructions.Tree = parser.SyntaxTree;
                    var threadStart = new ThreadStart(instructions.GenerateInstructions);
                    _thread = new Thread(threadStart)
                    {
                        IsBackground = true
                    };
                    _thread.Start();
                    while (_thread.IsAlive)
                    {
                        Thread.Sleep(10);
                    }
                    if (instructions.Error == null)
                    {
                        foreach (var i in instructions.Codes)
                        {
                            ResultTextBox.Text += i.ToString();
                        }
                    }
                    else
                    {
                        ResultTextBox.Text += instructions.Error;
                    }
                    ResultTextBox.Text += "\n···········Semantic Analysis done!";
                }
                else
                {
                    ResultTextBox.Text += parser.Error;
                    ResultTextBox.Text += "\n···········Syntactic Analysis Failed!\n";
                    ResultTextBox.Text += "\n···········Semantic Analysis Not Implemented!";
                }


                StopButton.IsEnabled = false;
                if (TreeViewRadioButton.IsChecked != true || NoneRadioButton.IsChecked == true)
                {
                    TreeViewArea.Visibility = Visibility.Collapsed;
                    Splitter.Visibility     = Visibility.Collapsed;
                }
            }
            else
            {
                ResultTextBox.Text += lexer.ErrorInfoStrb.ToString();
                ResultTextBox.Text += "\n···········Lexical Analysis Failed!\n";
                ResultTextBox.Text += "\n···········Syntactic Analysis Not Implemented!";
            }
        }
Example #15
0
        /// <summary>
        /// Issue with generation instructions but where streetnames seem to be stripped.
        /// Some streetnames are missing from the instructions.
        /// </summary>
        protected void DoInstructionRegressionTest1()
        {
            OsmRoutingInterpreter interpreter = new OsmRoutingInterpreter();

            Router router = this.CreateRouter(interpreter, "OsmSharp.Test.Unittests.test_routing_regression1.osm");

            // resolve the three points in question.
            GeoCoordinate point35         = new GeoCoordinate(51.01257, 4.000753);
            RouterPoint   point35resolved = router.Resolve(Vehicle.Car, point35, true);
            GeoCoordinate point45         = new GeoCoordinate(51.01315, 3.999588);
            RouterPoint   point45resolved = router.Resolve(Vehicle.Car, point45, true);
            GeoCoordinate point40         = new GeoCoordinate(51.01250, 4.000013);
            RouterPoint   point40resolved = router.Resolve(Vehicle.Car, point40, true);

            // calculate two smaller routes.
            Route route3545             = router.Calculate(Vehicle.Car, point35resolved, point45resolved);
            Route route4540             = router.Calculate(Vehicle.Car, point45resolved, point40resolved);
            Route route3540concatenated = Route.Concatenate(route3545, route4540, true);

            Route route3540 = router.Calculate(Vehicle.Car, point35resolved, point40resolved);

            // check if both routes are equal.
            Assert.AreEqual(route3540.Entries.Length, route3540concatenated.Entries.Length);
            for (int idx = 0; idx < route3540.Entries.Length; idx++)
            {
                Assert.AreEqual(route3540.Entries[idx].Distance, route3540concatenated.Entries[idx].Distance);
                Assert.AreEqual(route3540.Entries[idx].Latitude, route3540concatenated.Entries[idx].Latitude);
                Assert.AreEqual(route3540.Entries[idx].Longitude, route3540concatenated.Entries[idx].Longitude);
                Assert.AreEqual(route3540.Entries[idx].Time, route3540concatenated.Entries[idx].Time);
                Assert.AreEqual(route3540.Entries[idx].Type, route3540concatenated.Entries[idx].Type);
                Assert.AreEqual(route3540.Entries[idx].WayFromName, route3540concatenated.Entries[idx].WayFromName);

                // something that is allowed to be different in this case!
                // route3540.Entries[idx].Points != null

                //    // check sidestreets.
                //    if (route3540.Entries[idx].SideStreets != null &&
                //        route3540.Entries[idx].SideStreets.Length > 0)
                //    { // check if the sidestreets represent the same information.
                //        for (int metricIdx = 0; metricIdx < route3540concatenated.Entries[idx].SideStreets.Length; metricIdx++)
                //        {
                //            Assert.AreEqual(route3540.Entries[idx].SideStreets[metricIdx].WayName,
                //                route3540concatenated.Entries[idx].SideStreets[metricIdx].WayName);
                //            Assert.AreEqual(route3540.Entries[idx].SideStreets[metricIdx].Latitude,
                //                route3540concatenated.Entries[idx].SideStreets[metricIdx].Latitude);
                //            Assert.AreEqual(route3540.Entries[idx].SideStreets[metricIdx].Longitude,
                //                route3540concatenated.Entries[idx].SideStreets[metricIdx].Longitude);
                //        }
                //    }
                //    else
                //    {
                //        Assert.IsTrue(route3540concatenated.Entries[idx].SideStreets == null ||
                //            route3540concatenated.Entries[idx].SideStreets.Length == 0);
                //    }


                //    if (route3540.Entries[idx].Tags != null &&
                //        route3540.Entries[idx].Tags.Length > 0)
                //    { // check if the Tags represent the same information.
                //        for (int metricIdx = 0; metricIdx < route3540concatenated.Entries[idx].Tags.Length; metricIdx++)
                //        {
                //            Assert.AreEqual(route3540.Entries[idx].Tags[metricIdx].Key,
                //                route3540concatenated.Entries[idx].Tags[metricIdx].Key);
                //            Assert.AreEqual(route3540.Entries[idx].Tags[metricIdx].Value,
                //                route3540concatenated.Entries[idx].Tags[metricIdx].Value);
                //        }
                //    }
                //    else
                //    {
                //        Assert.IsTrue(route3540concatenated.Entries[idx].Tags == null ||
                //            route3540concatenated.Entries[idx].Tags.Length == 0);
                //    }

                //    Assert.AreEqual(route3540.Entries[idx].Distance, route3540concatenated.Entries[idx].Distance);
            }
            if (route3540.Tags != null &&
                route3540.Tags.Length > 0)
            {
                for (int tagIdx = 0; tagIdx < route3540.Tags.Length; tagIdx++)
                {
                    if (route3540.Tags[tagIdx].Key != "debug_route")
                    {
                        Assert.AreEqual(route3540.Tags[tagIdx].Key, route3540concatenated.Tags[tagIdx].Key);
                        Assert.AreEqual(route3540.Tags[tagIdx].Value, route3540concatenated.Tags[tagIdx].Value);
                    }
                }
            }
            else
            {
                Assert.IsTrue(route3540concatenated.Tags == null ||
                              route3540concatenated.Tags.Length == 0);
            }
            if (route3540.Metrics != null)
            {
                for (int metricIdx = 0; metricIdx < route3540concatenated.Entries.Length; metricIdx++)
                {
                    Assert.AreEqual(route3540.Metrics[metricIdx].Key, route3540concatenated.Metrics[metricIdx].Key);
                    Assert.AreEqual(route3540.Metrics[metricIdx].Value, route3540concatenated.Metrics[metricIdx].Value);
                }
            }
            else
            {
                Assert.IsNull(route3540concatenated.Metrics);
            }

            // remove the point in between, the only difference between the regular and the concatenated route.
            route3540concatenated.Entries[7].Points = null;

            // create the language generator.
            var languageGenerator = new LanguageTestGenerator();

            // generate the instructions.
            List <Instruction> instructions =
                InstructionGenerator.Generate(route3540, interpreter, languageGenerator);
            List <Instruction> instructionsConcatenated =
                InstructionGenerator.Generate(route3540concatenated, interpreter, languageGenerator);

            Assert.AreEqual(instructions.Count, instructionsConcatenated.Count);
            for (int idx = 0; idx < instructions.Count; idx++)
            {
                Assert.AreEqual(instructions[idx].Location.Center,
                                instructionsConcatenated[idx].Location.Center);
                Assert.AreEqual(instructions[idx].Text,
                                instructionsConcatenated[idx].Text);
            }
        }
 public void Setup()
 {
     instructionGenerator = new InstructionGenerator();
 }
Example #17
0
        public void RoutingRegressionTest2()
        {
            OsmRoutingInterpreter interpreter = new OsmRoutingInterpreter();

            SimpleTagsIndex tags_index = new SimpleTagsIndex();

            // do the data processing.
            DynamicGraphRouterDataSource <LiveEdge> memory_data =
                new DynamicGraphRouterDataSource <LiveEdge>(tags_index);
            LiveGraphOsmStreamWriter target_data = new LiveGraphOsmStreamWriter(
                memory_data, interpreter, memory_data.TagsIndex);
            XmlOsmStreamSource data_processor_source = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.UnitTests.test_routing_regression1.osm"));
            OsmStreamFilterSort sorter = new OsmStreamFilterSort();

            sorter.RegisterSource(data_processor_source);
            target_data.RegisterSource(sorter);
            target_data.Pull();

            IBasicRouter <LiveEdge> basic_router = new DykstraRoutingLive(memory_data.TagsIndex);
            Router router = Router.CreateLiveFrom(memory_data, basic_router, interpreter);

            // resolve the three points in question.
            GeoCoordinate point35         = new GeoCoordinate(51.01257, 4.000753);
            RouterPoint   point35resolved = router.Resolve(Vehicle.Car, point35);
            GeoCoordinate point45         = new GeoCoordinate(51.01315, 3.999588);
            RouterPoint   point45resolved = router.Resolve(Vehicle.Car, point45);
            GeoCoordinate point40         = new GeoCoordinate(51.01250, 4.000013);
            RouterPoint   point40resolved = router.Resolve(Vehicle.Car, point40);

            // calculate two smaller routes.
            OsmSharpRoute route3545             = router.Calculate(Vehicle.Car, point35resolved, point45resolved);
            OsmSharpRoute route4540             = router.Calculate(Vehicle.Car, point45resolved, point40resolved);
            OsmSharpRoute route3540concatenated = OsmSharpRoute.Concatenate(route3545, route4540);

            OsmSharpRoute route3540 = router.Calculate(Vehicle.Car, point35resolved, point40resolved);

            // check if both routes are equal.
            Assert.AreEqual(route3540.Entries.Length, route3540concatenated.Entries.Length);
            for (int idx = 0; idx < route3540.Entries.Length; idx++)
            {
                Assert.AreEqual(route3540.Entries[idx].Distance, route3540concatenated.Entries[idx].Distance);
                Assert.AreEqual(route3540.Entries[idx].Latitude, route3540concatenated.Entries[idx].Latitude);
                Assert.AreEqual(route3540.Entries[idx].Longitude, route3540concatenated.Entries[idx].Longitude);
                Assert.AreEqual(route3540.Entries[idx].Time, route3540concatenated.Entries[idx].Time);
                Assert.AreEqual(route3540.Entries[idx].Type, route3540concatenated.Entries[idx].Type);
                Assert.AreEqual(route3540.Entries[idx].WayFromName, route3540concatenated.Entries[idx].WayFromName);

                // something that is allowed to be different in this case!
                // route3540.Entries[idx].Points != null

                // check sidestreets.
                if (route3540.Entries[idx].SideStreets != null &&
                    route3540.Entries[idx].SideStreets.Length > 0)
                { // check if the sidestreets represent the same information.
                    for (int metricIdx = 0; metricIdx < route3540concatenated.Entries[idx].SideStreets.Length; metricIdx++)
                    {
                        Assert.AreEqual(route3540.Entries[idx].SideStreets[metricIdx].WayName,
                                        route3540concatenated.Entries[idx].SideStreets[metricIdx].WayName);
                        Assert.AreEqual(route3540.Entries[idx].SideStreets[metricIdx].Latitude,
                                        route3540concatenated.Entries[idx].SideStreets[metricIdx].Latitude);
                        Assert.AreEqual(route3540.Entries[idx].SideStreets[metricIdx].Longitude,
                                        route3540concatenated.Entries[idx].SideStreets[metricIdx].Longitude);
                    }
                }
                else
                {
                    Assert.IsTrue(route3540concatenated.Entries[idx].SideStreets == null ||
                                  route3540concatenated.Entries[idx].SideStreets.Length == 0);
                }


                if (route3540.Entries[idx].Tags != null &&
                    route3540.Entries[idx].Tags.Length > 0)
                { // check if the Tags represent the same information.
                    for (int metricIdx = 0; metricIdx < route3540concatenated.Entries[idx].Tags.Length; metricIdx++)
                    {
                        Assert.AreEqual(route3540.Entries[idx].Tags[metricIdx].Key,
                                        route3540concatenated.Entries[idx].Tags[metricIdx].Key);
                        Assert.AreEqual(route3540.Entries[idx].Tags[metricIdx].Value,
                                        route3540concatenated.Entries[idx].Tags[metricIdx].Value);
                    }
                }
                else
                {
                    Assert.IsTrue(route3540concatenated.Entries[idx].Tags == null ||
                                  route3540concatenated.Entries[idx].Tags.Length == 0);
                }

                Assert.AreEqual(route3540.Entries[idx].Distance, route3540concatenated.Entries[idx].Distance);
            }
            if (route3540.Tags != null &&
                route3540.Tags.Length > 0)
            {
                for (int tagIdx = 0; tagIdx < route3540.Tags.Length; tagIdx++)
                {
                    if (route3540.Tags[tagIdx].Key != "debug_route")
                    {
                        Assert.AreEqual(route3540.Tags[tagIdx].Key, route3540concatenated.Tags[tagIdx].Key);
                        Assert.AreEqual(route3540.Tags[tagIdx].Value, route3540concatenated.Tags[tagIdx].Value);
                    }
                }
            }
            else
            {
                Assert.IsTrue(route3540concatenated.Tags == null ||
                              route3540concatenated.Tags.Length == 0);
            }
            if (route3540.Metrics != null)
            {
                for (int metricIdx = 0; metricIdx < route3540concatenated.Entries.Length; metricIdx++)
                {
                    Assert.AreEqual(route3540.Metrics[metricIdx].Key, route3540concatenated.Metrics[metricIdx].Key);
                    Assert.AreEqual(route3540.Metrics[metricIdx].Value, route3540concatenated.Metrics[metricIdx].Value);
                }
            }
            else
            {
                Assert.IsNull(route3540concatenated.Metrics);
            }

            // remove the point in between, the only difference between the regular and the concatenated route.
            route3540concatenated.Entries[7].Points = null;

            // create the language generator.
            var languageGenerator = new LanguageTestGenerator();

            // generate the instructions.
            var instructionGenerator        = new InstructionGenerator();
            List <Instruction> instructions =
                instructionGenerator.Generate(route3540, interpreter, languageGenerator);
            List <Instruction> instructionsConcatenated =
                instructionGenerator.Generate(route3540concatenated, interpreter, languageGenerator);

            Assert.AreEqual(instructions.Count, instructionsConcatenated.Count);
            for (int idx = 0; idx < instructions.Count; idx++)
            {
                Assert.AreEqual(instructions[idx].Location.Center,
                                instructionsConcatenated[idx].Location.Center);
                Assert.AreEqual(instructions[idx].Text,
                                instructionsConcatenated[idx].Text);
            }
        }
        public void EmitOpCode()
        {
            var instructionGenerator = new InstructionGenerator();

            instructionGenerator.Emit(OpCode.Create(OpType.Add));
        }
Example #19
0
 /// <summary>
 /// Calculates instructions for a given route.
 /// </summary>
 /// <param name="route"></param>
 /// <returns></returns>
 public override List <Instruction> GetInstructions(Route route)
 {
     return(InstructionGenerator.Generate(route, new OsmRoutingInterpreter()));
 }
Example #20
0
        public void TestSimpleTurn()
        {
            var route = new Route();

            route.Vehicle     = Vehicle.Car.UniqueName;
            route.Segments    = new RouteSegment[3];
            route.Segments[0] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = 50.999f,
                Longitude = 4,
                Points    = new RoutePoint[] {
                    new RoutePoint()
                    {
                        Latitude  = 50.999f,
                        Longitude = 4,
                        Name      = "Start"
                    }
                },
                SideStreets = null,
                Type        = RouteSegmentType.Start
            };
            route.Segments[1] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = 51,
                Longitude = 4,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "Street A"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                Type        = RouteSegmentType.Along,
                SideStreets = new RouteSegmentBranch[] {
                    new RouteSegmentBranch()
                    {
                        Latitude  = 51,
                        Longitude = 3.999f,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "name", Value = "Street B"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        Name = "Street B"
                    }
                }
            };
            route.Segments[2] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = 51,
                Longitude = 4.001f,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "Street B"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                Type   = RouteSegmentType.Stop,
                Points = new RoutePoint[] {
                    new RoutePoint()
                    {
                        Latitude  = 51,
                        Longitude = 4.001f,
                        Name      = "Stop"
                    }
                },
            };

            // create the language generator.
            var languageGenerator = new LanguageTestGenerator();

            // generate instructions.
            List <Instruction> instructions = InstructionGenerator.Generate(route, new OsmRoutingInterpreter(), languageGenerator);

            Assert.AreEqual(3, instructions.Count);
            Assert.AreEqual("GenerateDirectTurn:0_Right_0", instructions[1].Text);
        }
Example #21
0
        public void TestRoundaboutExtended()
        {
            var westWest        = new GeoCoordinate(51, 3.998);
            var west            = new GeoCoordinate(51, 3.999);
            var eastEast        = new GeoCoordinate(51, 4.002);
            var east            = new GeoCoordinate(51, 4.001);
            var north           = new GeoCoordinate(51.001, 4);
            var northNorth      = new GeoCoordinate(51.002, 4);
            var south           = new GeoCoordinate(50.999, 4);
            var southSouth      = new GeoCoordinate(50.998, 4);
            var southSouthSouth = new GeoCoordinate(50.997, 4);
            var center          = new GeoCoordinate(51, 4);

            var route = new Route();

            route.Vehicle     = Vehicle.Car.UniqueName;
            route.Segments    = new RouteSegment[6];
            route.Segments[0] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = (float)southSouth.Latitude,
                Longitude = (float)southSouth.Longitude,
                Points    = new RoutePoint[] {
                    new RoutePoint()
                    {
                        Latitude  = (float)southSouthSouth.Latitude,
                        Longitude = (float)southSouthSouth.Longitude,
                        Name      = "Start"
                    }
                },
                SideStreets = null,
                Type        = RouteSegmentType.Start
            };
            route.Segments[1] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = (float)southSouth.Latitude,
                Longitude = (float)southSouth.Longitude,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "SouthStreet"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = null,
                Type        = RouteSegmentType.Along
            };
            route.Segments[2] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = (float)south.Latitude,
                Longitude = (float)south.Longitude,
                Type      = RouteSegmentType.Along,
                Name      = "SouthStreet",
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "SouthStreet"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = new RouteSegmentBranch[] {
                    new RouteSegmentBranch()
                    {
                        Latitude  = (float)west.Latitude,
                        Longitude = (float)west.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "junction", Value = "roundabout"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        Name = "Street B"
                    },
                    new RouteSegmentBranch()
                    {
                        Latitude  = (float)east.Latitude,
                        Longitude = (float)east.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "junction", Value = "roundabout"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        Name = "Street B"
                    }
                }
            };
            route.Segments[3] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = (float)east.Latitude,
                Longitude = (float)east.Longitude,
                Type      = RouteSegmentType.Along,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "junction", Value = "roundabout"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = new RouteSegmentBranch[] {
                    new RouteSegmentBranch()
                    {
                        Latitude  = (float)eastEast.Latitude,
                        Longitude = (float)eastEast.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "name", Value = "EastStreet"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        Name = "EastStreet"
                    }
                }
            };
            route.Segments[4] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = (float)north.Latitude,
                Longitude = (float)north.Longitude,
                Type      = RouteSegmentType.Along,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "junction", Value = "roundabout"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = new RouteSegmentBranch[] {
                    new RouteSegmentBranch()
                    {
                        Latitude  = (float)west.Latitude,
                        Longitude = (float)west.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "junction", Value = "roundabout"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        }
                    }
                }
            };
            route.Segments[5] = new RouteSegment()
            {
                Distance  = 0,
                Latitude  = (float)northNorth.Latitude,
                Longitude = (float)northNorth.Longitude,
                Type      = RouteSegmentType.Stop,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "NorthStreet"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                Points = new RoutePoint[] {
                    new RoutePoint()
                    {
                        Latitude  = (float)north.Latitude,
                        Longitude = (float)north.Longitude,
                        Name      = "Stop"
                    }
                }
            };

            // create the language generator.
            var languageGenerator = new LanguageTestGenerator();

            // generate instructions.
            List <Instruction> instructions = InstructionGenerator.Generate(route, new OsmRoutingInterpreter(), languageGenerator);

            Assert.AreEqual(3, instructions.Count);
            Assert.AreEqual("GenerateRoundabout:3", instructions[1].Text);
        }
 public void EmitOpCodeWithModRegRM()
 {
     var instructionGenerator = new InstructionGenerator();
     //instructionGenerator.Emit(OpCode.Create(OpType.Mov), new ModRegRM());
 }
Example #23
0
        public void TestRoundabout()
        {
            GeoCoordinate westWest   = new GeoCoordinate(51, 3.998);
            GeoCoordinate west       = new GeoCoordinate(51, 3.999);
            GeoCoordinate eastEast   = new GeoCoordinate(51, 4.002);
            GeoCoordinate east       = new GeoCoordinate(51, 4.001);
            GeoCoordinate north      = new GeoCoordinate(51.001, 4);
            GeoCoordinate northNorth = new GeoCoordinate(51.002, 4);
            GeoCoordinate south      = new GeoCoordinate(50.999, 4);
            GeoCoordinate southSouth = new GeoCoordinate(50.998, 4);
            GeoCoordinate center     = new GeoCoordinate(51, 4);

            Route route = new Route();

            route.Vehicle    = Vehicle.Car;
            route.Entries    = new RoutePointEntry[5];
            route.Entries[0] = new RoutePointEntry()
            {
                Distance  = 0,
                Latitude  = (float)southSouth.Latitude,
                Longitude = (float)southSouth.Longitude,
                Points    = new RoutePoint[] {
                    new RoutePoint()
                    {
                        Latitude  = (float)southSouth.Latitude,
                        Longitude = (float)southSouth.Longitude,
                        Name      = "Start"
                    }
                },
                SideStreets = null,
                Type        = RoutePointEntryType.Start
            };
            route.Entries[1] = new RoutePointEntry()
            {
                Distance    = 0,
                Latitude    = (float)south.Latitude,
                Longitude   = (float)south.Longitude,
                Type        = RoutePointEntryType.Along,
                WayFromName = "SouthStreet",
                Tags        = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "SouthStreet"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = new RoutePointEntrySideStreet[] {
                    new RoutePointEntrySideStreet()
                    {
                        Latitude  = (float)west.Latitude,
                        Longitude = (float)west.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "junction", Value = "roundabout"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        WayName = "Street B"
                    },
                    new RoutePointEntrySideStreet()
                    {
                        Latitude  = (float)east.Latitude,
                        Longitude = (float)east.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "junction", Value = "roundabout"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        WayName = "Street B"
                    }
                }
            };
            route.Entries[2] = new RoutePointEntry()
            {
                Distance  = 0,
                Latitude  = (float)east.Latitude,
                Longitude = (float)east.Longitude,
                Type      = RoutePointEntryType.Along,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "junction", Value = "roundabout"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = new RoutePointEntrySideStreet[] {
                    new RoutePointEntrySideStreet()
                    {
                        Latitude  = (float)eastEast.Latitude,
                        Longitude = (float)eastEast.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "name", Value = "EastStreet"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        },
                        WayName = "EastStreet"
                    }
                }
            };
            route.Entries[3] = new RoutePointEntry()
            {
                Distance  = 0,
                Latitude  = (float)north.Latitude,
                Longitude = (float)north.Longitude,
                Type      = RoutePointEntryType.Along,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "junction", Value = "roundabout"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                SideStreets = new RoutePointEntrySideStreet[] {
                    new RoutePointEntrySideStreet()
                    {
                        Latitude  = (float)west.Latitude,
                        Longitude = (float)west.Longitude,
                        Tags      = new RouteTags[] {
                            new RouteTags()
                            {
                                Key = "junction", Value = "roundabout"
                            },
                            new RouteTags()
                            {
                                Key = "highway", Value = "residential"
                            }
                        }
                    }
                }
            };
            route.Entries[4] = new RoutePointEntry()
            {
                Distance  = 0,
                Latitude  = (float)northNorth.Latitude,
                Longitude = (float)northNorth.Longitude,
                Type      = RoutePointEntryType.Stop,
                Tags      = new RouteTags[] {
                    new RouteTags()
                    {
                        Key = "name", Value = "NorthStreet"
                    },
                    new RouteTags()
                    {
                        Key = "highway", Value = "residential"
                    }
                },
                Points = new RoutePoint[] {
                    new RoutePoint()
                    {
                        Latitude  = (float)north.Latitude,
                        Longitude = (float)north.Longitude,
                        Name      = "Stop"
                    }
                }
            };

            // create the language generator.
            var languageGenerator = new LanguageTestGenerator();

            // generate instructions.
            List <Instruction> instructions = InstructionGenerator.Generate(route, new OsmRoutingInterpreter(), languageGenerator);

            Assert.AreEqual(3, instructions.Count);
            Assert.AreEqual("GenerateRoundabout:1", instructions[1].Text);
        }