Ejemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the RelationInfo class with specified ID, Tags, Member and optionaly EntityMetadata.
 /// </summary>
 /// <param name="id">The id of the relation.</param>
 /// <param name="tags">The collection of tags associated with the relation.</param>
 /// <param name="members">The members of the relation.</param>
 /// <param name="additionalInfo">The EntityMetadata structure with additinal properties. Default value is null.</param> 
 public RelationInfo(int id, TagsCollection tags, IList<RelationMemberInfo> members, EntityMetadata additionalInfo = null)
 {
     this.ID = id;
     this.Tags = tags;
     this.Members = members;
     this.Metadata = additionalInfo;
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the WayInfo class with specified ID, Nodes, collection of tags and optionaly EntityMetadata.
 /// </summary>
 /// <param name="id">The Id of the way.</param>
 /// <param name="tags">The collection of tags associated with the way.</param>
 /// <param name="nodes">The nodes of the way.</param>
 /// <param name="additionalInfo">The EntityMetadata structure with additinal properties. Default value is null.</param>
 public WayInfo(int id, TagsCollection tags, IList<int> nodes, EntityMetadata additionalInfo = null)
 {
     this.ID = id;
     this.Tags = tags;
     this.Nodes = nodes;
     this.Metadata = additionalInfo;
 }
Ejemplo n.º 3
0
        public void Clear_RemovesAllItems()
        {
            TagsCollection target = new TagsCollection(_tags);
            target.Clear();

            Assert.Empty(target);
        }
Ejemplo n.º 4
0
        public void Add_AddsTag()
        {
            TagsCollection target = new TagsCollection();
            target.Add(_tags[0]);

            Assert.Contains(_tags[0], target);
        }
Ejemplo n.º 5
0
        public void Add_ThrowsExceptionIfTagAlreadyPresent()
        {
            TagsCollection target = new TagsCollection();
            target.Add(_tagsDuplicitKeys[0]);

            Assert.Throws<ArgumentException>(delegate { target.Add(_tagsDuplicitKeys[1]); });
        }
Ejemplo n.º 6
0
        public void Constructor_IEnumerable_CreatesCollectionWithGivetTags()
        {
            TagsCollection target = new TagsCollection(_tags);

            Assert.Equal(_tags.Count(), target.Count());
            Assert.Contains(_tags[0], target);
            Assert.Contains(_tags[1], target);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the NodeInfo class with specified ID, latitude, longitude, collection of tags and optionaly EntityMetadata.
 /// </summary>
 /// <param name="id">The id of the node.</param>
 /// <param name="latitude">The latitude of the node.</param>
 /// <param name="longitude">The longitude of the node.</param>
 /// <param name="tags">The collection of thag associated with the node.</param>
 /// <param name="additionalInfo">The EntityMetadata structure with additinal properties. Default value is null.</param>
 public NodeInfo(int id, double latitude, double longitude, TagsCollection tags, EntityMetadata additionalInfo = null)
 {
     this.ID = id;
     this.Latitude = latitude;
     this.Longitude = longitude;
     this.Tags = tags;
     this.Metadata = additionalInfo;
 }
Ejemplo n.º 8
0
        public void Constructor_int_Coordinate_Tags_CreatesNodeAndInitializeProperties()
        {
            int id = 11;
            Coordinate coord = new Coordinate(-15.6, 68.7);
            TagsCollection tags = new TagsCollection();

            Node target = new Node(id, coord, tags);

            Assert.Equal(SRIDList.WSG84, target.Srid);
            Assert.Equal(id, target.ID);
            Assert.Equal(target.Position.X, coord.X);
            Assert.Equal(target.Position.Y, coord.Y);
            Assert.Same(tags, target.Tags);
        }
Ejemplo n.º 9
0
        public void Constructor_PropertiesWithoutEntityDetails_SetsProperties()
        {
            int id = 45;
            TagsCollection tags = new TagsCollection();
            List<RelationMemberInfo> members = new List<RelationMemberInfo>();

            RelationInfo target = new RelationInfo(id, tags, members);

            Assert.Equal(EntityType.Relation, target.EntityType);
            Assert.Equal(id, target.ID);
            Assert.Same(tags, target.Tags);
            Assert.Same(members, target.Members);
            Assert.Null(target.Metadata);
        }
Ejemplo n.º 10
0
        public void Constructor_int_tags_CreatesRelationAndIntializesProperties()
        {
            int id = 11;
            var members = new RelationMember[] { new RelationMember(new Node(1)), new RelationMember(new Node(2)), new RelationMember(new Node(3)) };
            TagsCollection tags = new TagsCollection();
            Relation target = new Relation(id, members, tags);

            Assert.Equal(id, target.ID);
            Assert.Equal(members.Length, target.Geometries.Count);
            for (int i = 0; i < members.Length; i++) {
                Assert.Same(members[i], target.Geometries[i]);
            }

            Assert.Same(tags, target.Tags);
        }
Ejemplo n.º 11
0
        public void Constructor_PropertiesWithoutEntityDetails_SetsProperties()
        {
            int id = 15;
            double latitude = 15.4;
            double longitude = -23.7;
            TagsCollection tags = new TagsCollection();

            NodeInfo target = new NodeInfo(id, latitude, longitude, tags);

            Assert.Equal(EntityType.Node, target.EntityType);
            Assert.Equal(id, target.ID);
            Assert.Equal(latitude, target.Latitude);
            Assert.Equal(longitude, target.Longitude);
            Assert.Same(tags, target.Tags);
            Assert.Null(target.Metadata);
        }
Ejemplo n.º 12
0
        public void Constructor_ID_Nodes_Tags_CreatesWayAddsNodesAndInitializesProperties()
        {
            int id = 11;
            TagsCollection tags = new TagsCollection();

            Way target = new Way(id, _nodes, tags);

            Assert.Equal(id, target.ID);
            Assert.Equal(SRIDList.WSG84, target.Srid);
            Assert.Equal(_nodes.Count, target.Nodes.Count);
            for (int i = 0; i < _nodes.Count; i++) {
                Assert.Same(_nodes[i], target.Nodes[i]);
            }

            Assert.Same(tags, target.Tags);
            Assert.Null(target.Metadata);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Deserializes a tags collection from a byte array.
        /// </summary>
        /// <param name="tagsBytes"></param>
        /// <returns></returns>
        public TagsCollectionBase Deserialize(byte[] tagsBytes)
        {
            RuntimeTypeModel typeModel = TypeModel.Create();
            typeModel.Add(typeof(List<KeyValuePair<string, string>>), true);

            List<KeyValuePair<string, string>> tagsList = null;
            using (MemoryStream stream = new MemoryStream(tagsBytes))
            {
                tagsList = typeModel.Deserialize(stream, null, typeof(List<KeyValuePair<string, string>>)) as List<KeyValuePair<string, string>>;
            }

            TagsCollection tagsCollection = new TagsCollection();
            foreach(KeyValuePair<string, string> tag in tagsList)
            {
                tagsCollection.Add(tag.Key, tag.Value);
            }
            return tagsCollection;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Deserializes a tags index from the given stream.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static ITagsCollectionIndexReadonly Deserialize(Stream stream)
        {
            byte[] intBytes = new byte[4];
            stream.Read(intBytes, 0, 4);
            int startOfTags = BitConverter.ToInt32(intBytes, 0);
            stream.Read(intBytes, 0, 4);
            int endOfFile = BitConverter.ToInt32(intBytes, 0);

            RuntimeTypeModel typeModel = TagIndexSerializer.CreateTypeModel();
            byte[] stringTableBytes = new byte[startOfTags - 8];
            stream.Read(stringTableBytes, 0, stringTableBytes.Length);
            MemoryStream memoryStream = new MemoryStream(stringTableBytes);
            List<string> strings = typeModel.Deserialize(memoryStream, null, typeof(List<string>)) as List<string>;
            memoryStream.Dispose();

            byte[] tagsIndexBytes = new byte[endOfFile - startOfTags];
            stream.Read(tagsIndexBytes, 0, tagsIndexBytes.Length);
            memoryStream = new MemoryStream(tagsIndexBytes);
            List<KeyValuePair<uint, List<KeyValuePair<uint, uint>>>> tagsIndexTableList = typeModel.Deserialize(memoryStream, null,
                typeof(List<KeyValuePair<uint, List<KeyValuePair<uint, uint>>>>)) as List<KeyValuePair<uint, List<KeyValuePair<uint, uint>>>>;
            memoryStream.Dispose();

            Dictionary<uint, TagsCollection> tagsIndexList = new Dictionary<uint, TagsCollection>();
            for(int idx = 0; idx < tagsIndexTableList.Count; idx++)
            {
                KeyValuePair<uint, List<KeyValuePair<uint, uint>>> serializedTagsCollection =
                    tagsIndexTableList[idx];
                TagsCollection tagsCollection = new TagsCollection();
                if (serializedTagsCollection.Value != null)
                {
                    foreach (KeyValuePair<uint, uint> pair in serializedTagsCollection.Value)
                    {
                        tagsCollection.Add(
                            new Tag(strings[(int)pair.Key], strings[(int)pair.Value]));
                    }
                }
                tagsIndexList.Add(serializedTagsCollection.Key, tagsCollection);
            }

            return new TagsIndexReadonly(tagsIndexList);
        }
Ejemplo n.º 15
0
        public void RoutingSerializationRoutingComparisonTest()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network_real1.osm";

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

            // do the data processing.
            var original = LiveGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                                   Assembly.GetExecutingAssembly()
                                                                   .GetManifestResourceStream(embeddedString)),
                                                               interpreter);

            // create serializer.
            var routingSerializer = new RoutingDataSourceLiveEdgeSerializer(false);

            // serialize/deserialize.
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original, metaData);
                    byteArray = stream.ToArray();
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            IBasicRouterDataSource <LiveEdge> deserializedVersion =
                routingSerializer.Deserialize(new MemoryStream(byteArray), out metaData);

            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

//            // try to do some routing on the deserialized version.
//            var basicRouter =
//                new DykstraRoutingLive(deserializedVersion.TagsIndex);
//            Router router = Router.CreateLiveFrom(
//                deserializedVersion, basicRouter, interpreter);

            //// loop over all nodes and resolve their locations.
            //var resolvedReference = new RouterPoint[original.VertexCount];
            //var resolved = new RouterPoint[original.VertexCount];
            //for (uint idx = 1; idx < original.VertexCount + 1; idx++)
            //{ // resolve each vertex.
            //    float latitude, longitude;
            //    if (original.GetVertex(idx, out latitude, out longitude))
            //    {
            //        resolvedReference[idx - 1] = referenceRouter.Resolve(Vehicle.Car, new GeoCoordinate(latitude, longitude));
            //        resolved[idx - 1] = router.Resolve(Vehicle.Car, new GeoCoordinate(latitude, longitude));
            //    }

            //    Assert.IsNotNull(resolvedReference[idx - 1]);
            //    Assert.IsNotNull(resolved[idx - 1]);

            //    Assert.AreEqual(resolvedReference[idx - 1].Location.Latitude,
            //        resolved[idx - 1].Location.Latitude, 0.0001);
            //    Assert.AreEqual(resolvedReference[idx - 1].Location.Longitude,
            //        resolved[idx - 1].Location.Longitude, 0.0001);
            //}

            //    // check all the routes having the same weight(s).
            //    for (int fromIdx = 0; fromIdx < resolved.Length; fromIdx++)
            //    {
            //        for (int toIdx = 0; toIdx < resolved.Length; toIdx++)
            //        {
            //            OsmSharpRoute referenceRoute = referenceRouter.Calculate(VehicleEnum.Car,
            //                resolvedReference[fromIdx], resolvedReference[toIdx]);
            //            OsmSharpRoute route = router.Calculate(VehicleEnum.Car,
            //                resolved[fromIdx], resolved[toIdx]);

            //            Assert.IsNotNull(referenceRoute);
            //            Assert.IsNotNull(route);
            //            //Assert.AreEqual(referenceRoute.TotalDistance, route.TotalDistance, 0.1);
            //            // TODO: meta data is missing in some CH routing; see issue
            //            //Assert.AreEqual(reference_route.TotalTime, route.TotalTime, 0.0001);
            //        }
            //    }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Return the Tag with the specified id
 /// </summary>
 /// <param name="identity"></param>
 /// <returns></returns>
 public static Tag GetTagById(int identity) => TagsCollection.Where(tag => tag.Id == identity).FirstOrDefault();
Ejemplo n.º 17
0
        public void TagsCollection_ToJson_Empty_ShouldReturnEmptyJson()
        {
            var tagsCollection = new TagsCollection();

            Assert.AreEqual("{}", JsonSerializer.Serialize(tagsCollection));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Generates an instruction for an immidiate turn.
        /// </summary>
        /// <param name="instruction"></param>
        /// <param name="first_street_count_to"></param>
        /// <param name="first_street_to"></param>
        /// <param name="first_direction"></param>
        /// <param name="second_street_to"></param>
        /// <param name="second_direction"></param>
        /// <returns></returns>
        public Instruction GenerateImmidiateTurn(Instruction instruction, int first_street_count_to, TagsCollection first_street_to,
                                                 RelativeDirection first_direction, TagsCollection second_street_to, RelativeDirection second_direction)
        {
//            if (first_street_count_to == 1)
//            {
//                instruction.Text = string.Format("Neem de 1ste afslag {0}, de {1} op, en ga onmiddellijk {2} op de {3}.",
//                    TurnDirection(first_direction.Direction),
//                    this.GetName("nl", first_street_to),
//                    TurnDirection(second_direction.Direction),
//                    this.GetName("nl", second_street_to));
//            }
//            else
//            {
//                instruction.Text = string.Format("Neem de {4}de afslag {0}, de {1} op, en ga onmiddellijk {2} op de {3}.",
//                    TurnDirection(first_direction.Direction),
//                    this.GetName("nl", first_street_to),
//                    TurnDirection(second_direction.Direction),
//                    this.GetName("nl", second_street_to),
//                    first_street_count_to);
            //            }
            instruction.Text = string.Format("Draai {0} en daarna direct {1}",
                                             TurnDirection(first_direction.Direction),
                                             TurnDirection(second_direction.Direction));

            // returns the instruction with text.
            return(instruction);
        }
Ejemplo n.º 19
0
 protected override void ClearData()
 {
     base.ClearData();
     Priority   = 0;
     Categories = new TagsCollection();
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the Node class with specified ID, Position and Tags.
 /// </summary>
 /// <param name="id">The ID of the node.</param>
 /// <param name="position">The position of the Node.</param>
 /// <param name="tags">The collection of tags associated with the Node.</param>
 public Node(int id, Coordinate position, TagsCollection tags)
     : base(position)
 {
     this.ID   = id;
     this.Tags = tags;
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Adds a given way.
        /// </summary>
        /// <param name="way"></param>
        public override void AddWay(Way way)
        {
            if (!_preIndexMode && _waysToCache != null &&
                _waysToCache.Contains(way.Id.Value))
            { // cache this way?
                _dataCache.AddWay(way);
            }

            // initialize the way interpreter.
            if (_interpreter.EdgeInterpreter.IsRoutable(way.Tags))
            {         // the way is a road.
                if (_preIndexMode)
                {     // index relevant and used nodes.
                    if (way.Nodes != null)
                    { // this way has nodes.
                        // add new routable tags type.
                        var routableWayTags = new TagsCollection(way.Tags);
                        routableWayTags.RemoveAll(x =>
                        {
                            return(!_interpreter.IsRelevantRouting(x.Key) &&
                                   !Vehicle.IsRelevantForOneOrMore(x.Key));
                        });
                        if (_storeTags)
                        {
                            _tagsIndex.Add(routableWayTags);
                        }

                        int wayNodesCount = way.Nodes.Count;
                        for (int idx = 0; idx < wayNodesCount; idx++)
                        {
                            var node = way.Nodes[idx];
                            if (_preIndex.Contains(node))
                            { // node is relevant.
                                _relevantNodes.Add(node);
                            }
                            else
                            { // node is used.
                                _preIndex.Add(node);
                            }
                        }

                        if (wayNodesCount > 0)
                        { // first node is always relevant.
                            _relevantNodes.Add(way.Nodes[0]);
                            if (wayNodesCount > 1)
                            { // last node is always relevant.
                                _relevantNodes.Add(way.Nodes[wayNodesCount - 1]);
                            }
                        }
                    }
                }
                else
                {     // add actual edges.
                    if (way.Nodes != null && way.Nodes.Count > 1)
                    { // way has at least two nodes.
                        if (this.CalculateIsTraversable(_interpreter.EdgeInterpreter, _tagsIndex,
                                                        way.Tags))
                        { // the edge is traversable, add the edges.
                            uint?       from          = this.AddRoadNode(way.Nodes[0]);
                            long        fromNodeId    = way.Nodes[0];
                            List <long> intermediates = new List <long>();
                            for (int idx = 1; idx < way.Nodes.Count; idx++)
                            { // the to-node.
                                long currentNodeId = way.Nodes[idx];
                                if (!_collectIntermediates ||
                                    _relevantNodes.Contains(currentNodeId) ||
                                    idx == way.Nodes.Count - 1)
                                { // node is an important node.
                                    uint?to       = this.AddRoadNode(currentNodeId);
                                    long toNodeId = currentNodeId;

                                    // add the edge(s).
                                    if (from.HasValue && to.HasValue)
                                    { // add a road edge.
                                        while (from.Value == to.Value)
                                        {
                                            if (intermediates.Count > 0)
                                            {
                                                uint?dummy = this.AddRoadNode(intermediates[0]);
                                                intermediates.RemoveAt(0);
                                                if (dummy.HasValue && from.Value != dummy.Value)
                                                {
                                                    this.AddRoadEdge(way.Tags, from.Value, dummy.Value, null);
                                                    from = dummy;
                                                }
                                            }
                                            else
                                            { // no use to continue.
                                                break;
                                            }
                                        }
                                        // build coordinates.
                                        var intermediateCoordinates = new List <GeoCoordinateSimple>(intermediates.Count);
                                        for (int coordIdx = 0; coordIdx < intermediates.Count; coordIdx++)
                                        {
                                            ICoordinate coordinate;
                                            if (!_coordinates.TryGet(intermediates[coordIdx], out coordinate))
                                            {
                                                break;
                                            }
                                            intermediateCoordinates.Add(new GeoCoordinateSimple()
                                            {
                                                Latitude  = coordinate.Latitude,
                                                Longitude = coordinate.Longitude
                                            });
                                        }

                                        if (intermediateCoordinates.Count == intermediates.Count &&
                                            from.Value != to.Value)
                                        { // all coordinates have been found.
                                            this.AddRoadEdge(way.Tags, from.Value, to.Value, intermediateCoordinates);
                                        }
                                    }

                                    // if this way has a restriction save the collapsed nodes information.
                                    if (_restricedWays.Contains(way.Id.Value) && to.HasValue && from.HasValue)
                                    { // loop over all intermediates and save.
                                        var collapsedInfo = new KeyValuePair <KeyValuePair <long, uint>, KeyValuePair <long, uint> >(
                                            new KeyValuePair <long, uint>(fromNodeId, from.Value), new KeyValuePair <long, uint>(toNodeId, to.Value));
                                        foreach (var intermedidate in intermediates)
                                        {
                                            _collapsedNodes[intermedidate] = collapsedInfo;
                                        }
                                    }

                                    from = to; // the to node becomes the from.
                                    intermediates.Clear();
                                }
                                else
                                { // this node is just an intermediate.
                                    intermediates.Add(currentNodeId);
                                }
                            }
                        }
                    }
                }
            }
        }
 private void OnToggleButtonClick(object selectedTag)
 {
     SelectedTags = TagsCollection.Where(t => t.IsChecked).ToAsyncObservableCollection();
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the Relation class with the specified ID, Members and tags.
 /// </summary>
 /// <param name="id">The ID of the Relation.</param>
 /// <param name="members">The memberes of the relation.</param>
 /// <param name="tags">The collectoin of tags associated with the relation.</param>
 public Relation(long id, IEnumerable <RelationMember> members, TagsCollection tags)
     : base(members)
 {
     this.ID   = id;
     this.Tags = tags;
 }
Ejemplo n.º 24
0
        private void OnOkButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                List <int>       emptyIndices = new List <int>();
                HashSet <string> original     = new HashSet <string>();
                HashSet <string> duplicates   = new HashSet <string>();
                int index = 0;
                foreach (UserTagView view in TagsCollection)
                {
                    if (string.IsNullOrEmpty(view.Name))
                    {
                        emptyIndices.Add(index);
                    }
                    else if (!original.Add(view.Name))
                    {
                        duplicates.Add(view.Name);
                    }
                    index++;
                }

                StringBuilder sb = new StringBuilder();
                if (emptyIndices.Count > 0)
                {
                    sb.Append("Вы не указали имена для тегов: ").AppendLine(string.Join(", ", emptyIndices));
                }
                if (duplicates.Count > 0)
                {
                    sb.AppendLine("В таблице присутствуют теги с одинаковыми именами:");
                    foreach (string name in duplicates)
                    {
                        sb.AppendLine(name);
                    }
                }

                if (sb.Length > 0)
                {
                    MessageBox.Show(sb.ToString(), "Ошибка!", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }


                int priority = 0;
                IEnumerable <UserTag> items = TagsCollection.Select(view =>
                {
                    UserTag tag  = (UserTag)view;
                    tag.Priority = priority++;
                    return(tag);
                });

                Options.UserTags.TrySync(items);
                Options.Save();

                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                UIHelper.ShowError(ex);
            }
        }
 private void OnClearSelectionCommand(object obj)
 {
     TagsCollection?.ForEach(x => x.IsChecked = false);
     TagsCollection = TagsCollection?.ToAsyncObservableCollection();
     SelectedTags   = null;
 }
        public void RoutingSerializationV2CHRoutingComparisonTest()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network_real1.osm";

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

            // do the data processing.
            var original = CHEdgeGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                                     Assembly.GetExecutingAssembly()
                                                                     .GetManifestResourceStream(embeddedString)),
                                                                 interpreter,
                                                                 Vehicle.Car);

            // create serializer.
            var routingSerializer = new OsmSharp.Routing.CH.Serialization.Sorted.CHEdgeDataDataSourceSerializer();

            // serialize/deserialize.
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original, metaData);
                    byteArray = stream.ToArray();
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            IBasicRouterDataSource <CHEdgeData> deserializedVersion =
                routingSerializer.Deserialize(new MemoryStream(byteArray), out metaData);

            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

            // create reference router.
            original = CHEdgeGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                                 Assembly.GetExecutingAssembly()
                                                                 .GetManifestResourceStream(embeddedString)),
                                                             interpreter,
                                                             Vehicle.Car);
            var    basicRouterOriginal = new CHRouter();
            Router referenceRouter     = Router.CreateCHFrom(
                original, basicRouterOriginal, interpreter);

            // try to do some routing on the deserialized version.
            var    basicRouter = new CHRouter();
            Router router      = Router.CreateCHFrom(
                deserializedVersion, basicRouter, interpreter);

            //this.TestCompareAll(original, referenceRouter, router);
        }
Ejemplo n.º 27
0
        public void Remove_Tag_DoNothingAndReturnsFalseIfCollectionDoesNotContainTag()
        {
            TagsCollection target = new TagsCollection(_tags);

            Tag testTag = new Tag("other-key", "other-value");
            Assert.False(target.Remove(testTag));
            this.CompareCollections(_tags, target);
        }
Ejemplo n.º 28
0
        public void Contains_string_ReturnsFalseIfCollectionDoesNotContainTag()
        {
            TagsCollection target = new TagsCollection(_tags);

            Assert.False(target.Contains("non-existing-key"));
        }
Ejemplo n.º 29
0
        public void RoutingSerializationDataSourceTest()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network.osm";

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

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

            // do the data processing.
            var original =
                new DynamicGraphRouterDataSource <LiveEdge>(tagsIndex);
            var targetData = new LiveGraphOsmStreamTarget(
                original, interpreter, tagsIndex, new HugeDictionary <long, uint>(), null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));

            targetData.RegisterSource(dataProcessorSource);
            targetData.Pull();

            // store some lat/lons.
            var verticesLocations = new List <GeoCoordinate>();

            for (uint vertex = 1; vertex <= 5; vertex++)
            {
                float latitude, longitude;
                if (original.GetVertex(vertex, out latitude, out longitude))
                {
                    verticesLocations.Add(
                        new GeoCoordinate(latitude, longitude));
                }
            }

            // create serializer.
            var routingSerializer = new RoutingDataSourceLiveEdgeSerializer(false);

            // serialize/deserialize.
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            IBasicRouterDataSource <LiveEdge> deserializedVersion;

            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original, metaData);
                    byteArray = stream.ToArray();
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }
            using (var stream = new MemoryStream(byteArray))
            {
                try
                {
                    deserializedVersion = routingSerializer.Deserialize(stream, out metaData, false);
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            //Assert.AreEqual(original.VertexCount, deserializedVersion.VertexCount);
            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

            for (uint vertex = 1; vertex <= 5; vertex++)
            {
                float latitude, longitude;
                if (deserializedVersion.GetVertex(vertex, out latitude, out longitude))
                {
                    Assert.AreEqual(verticesLocations[(int)vertex - 1].Latitude, latitude, 0.000001);
                    Assert.AreEqual(verticesLocations[(int)vertex - 1].Longitude, longitude, 0.000001);
                }
            }
        }
        /// <summary>
        /// Generates an instruction for an indirect turn.
        /// </summary>
        /// <param name="instruction"></param>
        /// <param name="street_count_turn"></param>
        /// <param name="street_count_before_turn"></param>
        /// <param name="street_to"></param>
        /// <param name="direction"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public Instruction GenerateIndirectFollowTurn(Instruction instruction, int street_count_turn, int street_count_before_turn, TagsCollection street_to,
                                                      RelativeDirectionEnum direction, List <PointPoi> list)
        {
            if (street_count_before_turn == 1)
            {
                instruction.Text = string.Format("Turn {1} to stay on {0}.",
                                                 this.GetName("en", street_to),
                                                 TurnDirection(direction));
            }
            else
            {
                instruction.Text = string.Format("Take the {1}d street {2} to stay on {0}.",
                                                 this.GetName("en", street_to),
                                                 street_count_before_turn,
                                                 TurnDirection(direction));
            }

            // returns the instruction with text.
            return(instruction);
        }
Ejemplo n.º 31
0
 public IStyle GetStyle(TagsCollection tags)
 {
     return(null);
 }
        /// <summary>
        /// Generates an instruction for an immidiate turn.
        /// </summary>
        /// <param name="instruction"></param>
        /// <param name="first_street_count_to"></param>
        /// <param name="first_street_to"></param>
        /// <param name="first_direction"></param>
        /// <param name="second_street_to"></param>
        /// <param name="second_direction"></param>
        /// <returns></returns>
        public Instruction GenerateImmidiateTurn(Instruction instruction, int first_street_count_to, TagsCollection first_street_to,
                                                 RelativeDirection first_direction, TagsCollection second_street_to, RelativeDirection second_direction)
        {
            if (first_street_count_to == 1)
            {
                instruction.Text = string.Format("Take the first turn {0}, on the {1}, and turn immidiately {2} on the {3}.",
                                                 TurnDirection(first_direction.Direction),
                                                 this.GetName("en", first_street_to),
                                                 TurnDirection(second_direction.Direction),
                                                 this.GetName("en", second_street_to));
            }
            else
            {
                instruction.Text = string.Format("Take the {4}d turn {0}, on the {1}, and turn immidiately {2} on the {3}.",
                                                 TurnDirection(first_direction.Direction),
                                                 this.GetName("en", first_street_to),
                                                 TurnDirection(second_direction.Direction),
                                                 this.GetName("en", second_street_to),
                                                 first_street_count_to);
            }

            // returns the instruction with text.
            return(instruction);
        }
Ejemplo n.º 33
0
        public void Contains_string_ReturnsFalseForEmptyCollection()
        {
            TagsCollection target = new TagsCollection();

            Assert.False(target.Contains("key"));
        }
Ejemplo n.º 34
0
 protected AcJsonObjectNew(IFileAcManager manager, string id, bool enabled)
     : base(manager, id, enabled)
 {
     Tags = new TagsCollection();
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Generates an instruction for an indirect turn.
        /// </summary>
        /// <param name="instruction"></param>
        /// <param name="street_count_turn"></param>
        /// <param name="street_count_before_turn"></param>
        /// <param name="street_to"></param>
        /// <param name="direction"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public Instruction GenerateIndirectFollowTurn(Instruction instruction, int street_count_turn, int street_count_before_turn, TagsCollection street_to,
                                                      RelativeDirectionEnum direction, List <PointPoi> list)
        {
//            if (street_count_before_turn == 1)
//            {
//                instruction.Text = string.Format("Sla {1}af om op {0} te blijven.",
//                    this.GetName("nl",  street_to),
//                    TurnDirection(direction));
//            }
//            else
//            {
//                instruction.Text = string.Format("Neem de {1}de straat {2} om op {0} te blijven.",
//                    this.GetName("nl", street_to),
//                    street_count_before_turn,
//                    TurnDirection(direction));
//            }

            instruction.Text = string.Format("Draai {0}", TurnDirection(direction));

            // returns the instruction with text.
            return(instruction);
        }
Ejemplo n.º 36
0
 protected AcJsonObjectNew(IFileAcManager manager, string id, bool enabled)
         : base(manager, id, enabled) {
     Tags = new TagsCollection();
 }
Ejemplo n.º 37
0
        /*public override void PastLoad() {
         *  base.PastLoad();
         *  /* we don't need to add country and author to suggestion lists: one
         *     might be very invalid and other is missing here anyway #1#
         *
         *  /*if (!Enabled) return;
         *
         *  SuggestionLists.TrackSkinTeamsList.AddUnique(Team);
         *  SuggestionLists.TrackSkinDriverNamesList.AddUnique(DriverName);#1#
         * }*/

        protected override void LoadData(JObject json)
        {
            base.LoadData(json);
            Categories = new TagsCollection((json[@"categories"] as JArray)?.Select(x => x.ToString()));
            Priority   = json.GetDoubleValueOnly(@"priority", 0d);
        }
Ejemplo n.º 38
0
        protected virtual void ClearData() {
            JsonObject = null;

            Tags = new TagsCollection();
            Name = null;
            Year = null;
            Country = null;
            Description = null;
            Country = null;
            Version = null;
            Author = null;
            Url = null;
        }
        private void ModifyTags(long id, TagsCollection neTags, string table, string refColumn)
        {
            OracleCommand command;

            TagsCollection tagsToInsert = null;
            if (neTags == null)
            {
                tagsToInsert = new SimpleTagsCollection();
            }
            else
            {
                tagsToInsert = new SimpleTagsCollection(neTags);
            }

            // suppose there are no tags present yet.
            TagsCollection tags_to_update = new SimpleTagsCollection();
            TagsCollection tags_to_delete = new SimpleTagsCollection();            

            // adjust the data based on the tags already present.
            command = this.CreateCommand(string.Format("select * from {0} where {1}=:{1}",table,refColumn));
            command.Parameters.Add(refColumn, id);

            OracleDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                string k = reader["key"].ToStringEmptyWhenNull();
                string v = reader["value"].ToStringEmptyWhenNull();

                if (tagsToInsert.ContainsKey(k))
                {
                    // there is at least an update or no insert.
                    string new_value = tagsToInsert[k];
                    tagsToInsert.RemoveKeyValue(new Tag(k, v));

                    // see if there is an update needed.
                    if (new_value != v)
                    {
                        // tags need to be updated.
                        tags_to_update.Add(k, new_value);
                    }
                }
                else
                { 
                    // tags are not found; delete them!
                    tags_to_delete.Add(k, v);
                }
            }
            reader.Close();

            // delete old tags.
            foreach(Tag tag in tags_to_delete)
            {
                command = this.CreateCommand(string.Format("delete from {0} where {1}=:{1} and key=:key", table, refColumn));
                command.Parameters.Add(new OracleParameter(refColumn, id));
                command.Parameters.Add(new OracleParameter("key", tag.Key));

                command.ExecuteNonQuery();
                command.Dispose();
            }

            // update tags.
            foreach (Tag pair in tags_to_update)
            {
                command = this.CreateCommand(string.Format("update {0} set value=:value where {1}=:{1} and key=:key", table, refColumn));
                command.Parameters.Add(new OracleParameter("value", pair.Value));
                command.Parameters.Add(new OracleParameter(refColumn, id));
                command.Parameters.Add(new OracleParameter("key", pair.Key));

                command.ExecuteNonQuery();
                command.Dispose();
            }

            // insert tags.
            foreach (Tag pair in tagsToInsert)
            {
                command = this.CreateCommand(string.Format("insert into {0} ({1},key,value) values (:{1},:key,:value)",table,refColumn));
                command.Parameters.Add(new OracleParameter(refColumn, id));
                command.Parameters.Add(new OracleParameter("key", pair.Key));
                command.Parameters.Add(new OracleParameter("value", pair.Value));

                command.ExecuteNonQuery();
                command.Dispose();
            }
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestSerialization(string name, string pbfFile)
        {
            var testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));

            var performanceInfo = new PerformanceInfoConsumer("SerializerFlatFile.Serialize", 2000);

            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var stream   = testFile.OpenRead();
            var source   = new PBFOsmStreamSource(stream);
            var progress = new OsmStreamFilterProgress();

            progress.RegisterSource(source);

            var testOutputFile = new FileInfo(@"test.routing");

            testOutputFile.Delete();
            var writeStream = testOutputFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite);

            var tagsIndex         = new TagsIndex();
            var interpreter       = new OsmRoutingInterpreter();
            var graph             = new RouterDataSource <Edge>(new Graph <Edge>(), tagsIndex);
            var routingSerializer = new RoutingDataSourceSerializer();

            var memoryMappedGraph = new Graph <Edge>(1024);
            var coordinates       = new HugeCoordinateIndex(1024);
            var memoryData        = new RouterDataSource <Edge>(memoryMappedGraph, tagsIndex);
            var targetData        = new GraphOsmStreamTarget(memoryData, new OsmRoutingInterpreter(), tagsIndex, coordinates);

            targetData.RegisterSource(progress);
            targetData.Pull();

            performanceInfo.Stop();

            memoryData.Compress();

            performanceInfo = new PerformanceInfoConsumer("SerializerFlatFile.Serialize", 100000);
            performanceInfo.Start();
            performanceInfo.Report("Writing file for {0}...", testFile.Name);

            var metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            routingSerializer.Serialize(writeStream, memoryData, metaData);
            stream.Dispose();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("SerializerFlatFile", OsmSharp.Logging.TraceEventType.Information,
                                            string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));
            performanceInfo.Stop();

            ////performanceInfo = new PerformanceInfoConsumer("SerializerFlatFile.Serialize", 100000);
            ////performanceInfo.Start();
            ////performanceInfo.Report("Reading file for {0}...", testFile.Name);

            //var testInputFile = new FileInfo(@"test.routing");
            //var readStream = testInputFile.OpenRead();

            //RoutingTest.TestSerialized(readStream);

            ////var deserializedGraph = routingSerializer.Deserialize(readStream, false);

            ////readStream.Dispose();

            ////OsmSharp.Logging.Log.TraceEvent("SerializerFlatFile", OsmSharp.Logging.TraceEventType.Information,
            ////    string.Format("Read: {0}KB", testInputFile.Length / 1024));

            ////OsmSharp.Logging.Log.TraceEvent("SerializerFlatFile", Logging.TraceEventType.Information, deserializedGraph.ToInvariantString());

            ////performanceInfo.Stop();
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Does the v1 serialization.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="graph"></param>
        /// <returns></returns>
        protected override void DoSerialize(LimitedStream stream,
                                            DynamicGraphRouterDataSource <CHEdgeData> graph)
        {
            // create an index per tile.
            var dataPerTile = new Dictionary <Tile, UnserializedTileData>();

            for (uint vertex = 1; vertex < graph.VertexCount + 1; vertex++)
            { // loop over all vertices and serialize all into the correct tile.
                float latitude, longitude;
                if (graph.GetVertex(vertex, out latitude, out longitude))
                { // the vertex was found.
                    // build the correct tile.
                    Tile tile = Tile.CreateAroundLocation(new GeoCoordinate(latitude, longitude), Zoom);
                    UnserializedTileData serializableGraphTile;
                    if (!dataPerTile.TryGetValue(tile, out serializableGraphTile))
                    { // create the new tile.
                        serializableGraphTile             = new UnserializedTileData();
                        serializableGraphTile.Ids         = new List <uint>();
                        serializableGraphTile.Latitude    = new List <ushort>();
                        serializableGraphTile.Longitude   = new List <ushort>();
                        serializableGraphTile.StringTable = new Dictionary <string, int>();
                        serializableGraphTile.Arcs        = new List <SerializableGraphArcs>();

                        dataPerTile.Add(tile, serializableGraphTile);
                    }

                    // create short latitude/longitude.
                    serializableGraphTile.Ids.Add(vertex);
                    serializableGraphTile.Latitude.Add((ushort)(((tile.TopLeft.Latitude - latitude)
                                                                 / tile.Box.DeltaLat) * ushort.MaxValue));
                    serializableGraphTile.Longitude.Add((ushort)(((longitude - tile.TopLeft.Longitude)
                                                                  / tile.Box.DeltaLon) * ushort.MaxValue));

                    // get the arcs.
                    KeyValuePair <uint, CHEdgeData>[] arcs = graph.GetArcs(vertex);

                    // serialize the arcs.
                    var serializableGraphArcs = new SerializableGraphArcs();
                    if (arcs != null && arcs.Length > 0)
                    {
                        serializableGraphArcs.DestinationId = new uint[arcs.Length];
                        serializableGraphArcs.Forward       = new bool[arcs.Length];
                        serializableGraphArcs.Backward      = new bool[arcs.Length];
                        serializableGraphArcs.Weight        = new float[arcs.Length];
                        serializableGraphArcs.TileX         = new int[arcs.Length];
                        serializableGraphArcs.TileY         = new int[arcs.Length];
                        serializableGraphArcs.Tags          = new SerializableTags[arcs.Length];

                        for (int idx = 0; idx < arcs.Length; idx++)
                        {
                            KeyValuePair <uint, CHEdgeData> arc = arcs[idx];
                            // get destination tile.
                            if (graph.GetVertex(arc.Key, out latitude, out longitude))
                            { // the destionation was found.
                                Tile destinationTile = Tile.CreateAroundLocation(
                                    new GeoCoordinate(latitude, longitude), Zoom);
                                serializableGraphArcs.DestinationId[idx] = arc.Key;
                                serializableGraphArcs.TileX[idx]         = destinationTile.X;
                                serializableGraphArcs.TileY[idx]         = destinationTile.Y;
                                serializableGraphArcs.Forward[idx]       = arc.Value.Forward;
                                serializableGraphArcs.Backward[idx]      = arc.Value.Backward;
                                serializableGraphArcs.Weight[idx]        = arc.Value.Weight;

                                // get the tags.
                                TagsCollection tagsCollection =
                                    graph.TagsIndex.Get(arc.Value.Tags);
                                if (tagsCollection != null)
                                {
                                    serializableGraphArcs.Tags[idx]        = new SerializableTags();
                                    serializableGraphArcs.Tags[idx].Keys   = new int[tagsCollection.Count];
                                    serializableGraphArcs.Tags[idx].Values = new int[tagsCollection.Count];
                                    int tagsIndex = 0;
                                    foreach (var tag in tagsCollection)
                                    {
                                        int key;
                                        if (!serializableGraphTile.StringTable.TryGetValue(
                                                tag.Key, out key))
                                        { // string not yet in string table.
                                            key = serializableGraphTile.StringTable.Count;
                                            serializableGraphTile.StringTable.Add(tag.Key,
                                                                                  key);
                                        }
                                        int value;
                                        if (!serializableGraphTile.StringTable.TryGetValue(
                                                tag.Value, out value))
                                        { // string not yet in string table.
                                            value = serializableGraphTile.StringTable.Count;
                                            serializableGraphTile.StringTable.Add(tag.Value,
                                                                                  value);
                                        }
                                        serializableGraphArcs.Tags[idx].Keys[tagsIndex]   = key;
                                        serializableGraphArcs.Tags[idx].Values[tagsIndex] = value;
                                        tagsIndex++;
                                    }
                                }
                            }
                        }
                    }
                    serializableGraphTile.Arcs.Add(serializableGraphArcs);
                }
            }

            // LAYOUT OF V2: {HEADER}{compressionflag(1byte)}{#tiles(4byte)}{tilesMetaEnd(8byte)}{tiles-meta-data-xxxxxxx}{tiles-data}
            // {HEADER} : already written before this method.
            // {#tiles(4byte)} : the number of tiles in this file (calculate the offset of the {tiles-data}
            //                   section using (TileMetaSize * dataPerTile.Count + 4 + 8)
            // {tilesMetaEnd(8byte)} : the end of the meta tiles.
            // {tiles-meta-data-xxxxxxx} : the serialized tile metadata.
            // {tiles-data} : the actual tile data.

            // calculate the space needed for the tile offset.
            const long tileMetaOffset = 1 + 4 + 8;
            long       tileOffset     = TileMetaSize * dataPerTile.Count +
                                        tileMetaOffset; // all tile metadata + a tile count + tags offset.

            // build the tile metadata while writing the tile data.
            stream.Seek(tileOffset, SeekOrigin.Begin);
            var metas = new SerializableGraphTileMetas();

            metas.Length = new int[dataPerTile.Count];
            metas.Offset = new long[dataPerTile.Count];
            metas.TileX  = new int[dataPerTile.Count];
            metas.TileY  = new int[dataPerTile.Count];
            int metasIndex = 0;

            foreach (var unserializedTileData in dataPerTile)
            {
                // create the tile meta.
                metas.TileX[metasIndex]  = unserializedTileData.Key.X;
                metas.TileY[metasIndex]  = unserializedTileData.Key.Y;
                metas.Offset[metasIndex] = stream.Position;

                // create the tile.
                var serializableGraphTile = new SerializableGraphTile();
                serializableGraphTile.Arcs        = unserializedTileData.Value.Arcs.ToArray();
                serializableGraphTile.Ids         = unserializedTileData.Value.Ids.ToArray();
                serializableGraphTile.Latitude    = unserializedTileData.Value.Latitude.ToArray();
                serializableGraphTile.Longitude   = unserializedTileData.Value.Longitude.ToArray();
                serializableGraphTile.StringTable = new string[unserializedTileData.Value.StringTable.Count];
                foreach (var stringEntry in unserializedTileData.Value.StringTable)
                {
                    serializableGraphTile.StringTable[stringEntry.Value] =
                        stringEntry.Key;
                }

                // serialize the tile.
                if (!_compress)
                { // compresses the file.
                    _runtimeTypeModel.Serialize(stream, serializableGraphTile);
                }
                else
                { // first compress the data, then write.
                    var uncompressed = new MemoryStream();
                    _runtimeTypeModel.Serialize(uncompressed, serializableGraphTile);
                    var uncompressedBuffer = uncompressed.ToArray();

                    byte[] compressed = GZipStream.CompressBuffer(uncompressedBuffer);
                    stream.Write(compressed, 0, compressed.Length);
                }

                // calculate the length of the data that was just serialized.
                metas.Length[metasIndex] = (int)(stream.Position - metas.Offset[metasIndex]);

                metasIndex++;
            }

            // serialize all tile meta data.
            stream.Seek(tileMetaOffset, SeekOrigin.Begin);
            _runtimeTypeModel.Serialize(stream, metas);
            long tileMetaEnd = stream.Position; // save the meta and.

            // save all the offsets.
            stream.Seek(0, SeekOrigin.Begin);
            byte[] compressionFlag = new[] { (byte)(_compress ? 1 : 0) };
            stream.Write(compressionFlag, 0, 1);
            byte[] tileCountBytes = BitConverter.GetBytes(metas.TileX.Length);
            stream.Write(tileCountBytes, 0, tileCountBytes.Length);     // 4 bytes
            byte[] tileMetaEndBytes = BitConverter.GetBytes(tileMetaEnd);
            stream.Write(tileMetaEndBytes, 0, tileMetaEndBytes.Length); // 8 bytes

            stream.Flush();
        }
Ejemplo n.º 42
0
        public void Remove_string_ReturnsFalseForEmptyCollection()
        {
            TagsCollection target = new TagsCollection();
            bool removed = target.Remove("key");

            Assert.False(removed);
        }
Ejemplo n.º 43
0
        public void RoutingSerializationCompressedRoutingTest()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network.osm";

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

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

            // do the data processing.
            var original =
                new DynamicGraphRouterDataSource <LiveEdge>(tagsIndex);
            var targetData = new LiveGraphOsmStreamTarget(
                original, interpreter, tagsIndex, new HugeDictionary <long, uint>(), null, false);
            var dataProcessorSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString));

            targetData.RegisterSource(dataProcessorSource);
            targetData.Pull();

            // create serializer.
            var routingSerializer = new RoutingDataSourceLiveEdgeSerializer(true);

            // serialize/deserialize.
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                try
                {
                    routingSerializer.Serialize(stream, original, metaData);
                    byteArray = stream.ToArray();
                }
                catch (Exception)
                {
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    throw;
                }
            }

            var deserializedVersion = routingSerializer.Deserialize(new MemoryStream(byteArray), out metaData);

            Assert.AreEqual(original.TagsIndex.Get(0), deserializedVersion.TagsIndex.Get(0));

            // try to do some routing on the deserialized version.
            var basicRouter = new DykstraRoutingLive();
            var router      = Router.CreateLiveFrom(deserializedVersion, basicRouter, interpreter);
            var source      = router.Resolve(Vehicle.Car,
                                             new GeoCoordinate(51.0578532, 3.7192229));
            var target = router.Resolve(Vehicle.Car,
                                        new GeoCoordinate(51.0576193, 3.7191801));

            // calculate the route.
            var route = router.Calculate(Vehicle.Car, source, target);

            Assert.IsNotNull(route);
            Assert.AreEqual(5, route.Segments.Length);

            float latitude, longitude;

            //deserializedVersion.GetVertex(20, out latitude, out longitude);
            Assert.AreEqual(51.0578537, route.Segments[0].Latitude, 0.00001);
            Assert.AreEqual(3.71922255, route.Segments[0].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Start, route.Segments[0].Type);

            //deserializedVersion.GetVertex(21, out latitude, out longitude);
            Assert.AreEqual(51.0578537, route.Segments[1].Latitude, 0.00001);
            Assert.AreEqual(3.71956515, route.Segments[1].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[1].Type);

            //deserializedVersion.GetVertex(16, out latitude, out longitude);
            Assert.AreEqual(51.05773, route.Segments[2].Latitude, 0.00001);
            Assert.AreEqual(3.719745, route.Segments[2].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[2].Type);

            //deserializedVersion.GetVertex(22, out latitude, out longitude);
            Assert.AreEqual(51.05762, route.Segments[3].Latitude, 0.00001);
            Assert.AreEqual(3.71965766, route.Segments[3].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Along, route.Segments[3].Type);

            deserializedVersion.GetVertex(23, out latitude, out longitude);
            Assert.AreEqual(51.05762, route.Segments[4].Latitude, 0.00001);
            Assert.AreEqual(3.71917963, route.Segments[4].Longitude, 0.00001);
            Assert.AreEqual(RouteSegmentType.Stop, route.Segments[4].Type);
        }
Ejemplo n.º 44
0
        public void Remove_string_DoNothingAndReturnsFalseIfCollectionDoesNotContainTag()
        {
            Tag[] tags = new Tag[] { new Tag("test-key-1", "test-value"), new Tag("test-key-2", "test-value") };

            TagsCollection target = new TagsCollection(tags);

            Assert.False(target.Remove("non-existing-tag"));
        }
Ejemplo n.º 45
0
        public void RoutingSerializationFlatfileCHEdgeData()
        {
            const string embeddedString = "OsmSharp.Test.Unittests.test_network_real1.osm";

            // load the network.
            var referenceNetwork = CHEdgeGraphOsmStreamTarget.Preprocess(new XmlOsmStreamSource(
                                                                             Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedString)), new OsmRoutingInterpreter(), Vehicle.Car);

            // serialize network.
            var routingSerializer       = new CHEdgeFlatfileSerializer();
            TagsCollectionBase metaData = new TagsCollection();

            metaData.Add("some_key", "some_value");
            DynamicGraphRouterDataSource <CHEdgeData> network;

            byte[] byteArray;
            using (var stream = new MemoryStream())
            {
                routingSerializer.Serialize(stream, referenceNetwork, metaData);
                byteArray = stream.ToArray();
            }
            using (var stream = new MemoryStream(byteArray))
            {
                network = routingSerializer.Deserialize(stream, out metaData, false) as DynamicGraphRouterDataSource <CHEdgeData>;
            }

            // compare networks.
            Assert.IsNotNull(network);
            Assert.AreEqual(referenceNetwork.VertexCount, network.VertexCount);
            for (uint vertex = 0; vertex < network.VertexCount; vertex++)
            {
                float referenceLatitude, referenceLongitude, latitude, longitude;
                Assert.IsTrue(referenceNetwork.GetVertex(vertex, out referenceLatitude, out referenceLongitude));
                Assert.IsTrue(network.GetVertex(vertex, out latitude, out longitude));
                Assert.AreEqual(referenceLatitude, latitude);
                Assert.AreEqual(referenceLongitude, longitude);

                var referenceArcs = referenceNetwork.GetEdges(vertex);
                var arcs          = network.GetEdges(vertex);
                Assert.AreEqual(referenceArcs.Length, arcs.Length);
                for (int idx = 0; idx < referenceArcs.Length; idx++)
                {
                    var referenceArc = referenceArcs[idx];
                    // find the same edge in the new arcs.
                    var arc = arcs.First((x) => { return(x.Key == referenceArcs[idx].Key); });

                    Assert.AreEqual(referenceArc.Key, arc.Key);
                    Assert.AreEqual(referenceArc.Value.Weight, arc.Value.Weight);
                    Assert.AreEqual(referenceArc.Value.Forward, arc.Value.Forward);
                    Assert.AreEqual(referenceArc.Value.RepresentsNeighbourRelations, arc.Value.RepresentsNeighbourRelations);
                    Assert.AreEqual(referenceArc.Value.Tags, arc.Value.Tags);
                    if (referenceArc.Value.Coordinates == null)
                    { // other arc coordinates also null?
                        Assert.IsNull(arc.Value.Coordinates);
                    }
                    else
                    { // compare coordinates.
                        for (int coordIdx = 0; coordIdx < referenceArc.Value.Coordinates.Length; coordIdx++)
                        {
                            Assert.AreEqual(referenceArc.Value.Coordinates[coordIdx].Latitude,
                                            arc.Value.Coordinates[coordIdx].Latitude);
                            Assert.AreEqual(referenceArc.Value.Coordinates[coordIdx].Longitude,
                                            arc.Value.Coordinates[coordIdx].Longitude);
                        }
                    }

                    // check tags.
                    var referenceTags = referenceNetwork.TagsIndex.Get(referenceArc.Value.Tags);
                    var tags          = network.TagsIndex.Get(arc.Value.Tags);
                    if (referenceTags == null)
                    { // other tags also have to be null.
                        Assert.IsNull(tags);
                    }
                    else
                    { // contents need to be the same.
                        Assert.AreEqual(referenceTags.Count, tags.Count);
                        foreach (var referenceTag in referenceTags)
                        {
                            Assert.IsTrue(tags.ContainsKeyValue(referenceTag.Key, referenceTag.Value));
                        }
                    }
                }
            }
        }
Ejemplo n.º 46
0
        public void Constructor_CreatesEmptyTagsCollection()
        {
            TagsCollection target = new TagsCollection();

            Assert.Empty(target);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Tests an empty tags collection.
        /// </summary>
        protected void TestTagsCollectionEmpty()
        {
            TagsCollectionBase collection = new TagsCollection();

            Assert.AreEqual(0, collection.Count);
        }
Ejemplo n.º 48
0
        public void Remove_string_RemovesItemAndReturnsTrueIfCollectionContainsTag()
        {
            Tag[] tags = new Tag[] { new Tag("test-key-1", "test-value"), new Tag("test-key-2", "test-value") };

            TagsCollection target = new TagsCollection(tags);

            Assert.True(target.Remove(tags[1].Key));
            Assert.Equal(1, target.Count);
            Assert.Contains(tags[0], target);
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Initializes a new instance of the Node class with specified ID, Longitude, Latitude and Tags.
 /// </summary>
 /// <param name="id">The ID of the node.</param>
 /// <param name="longitude">The longitude of the Node.</param>
 /// <param name="latitude">The latitude of the Node.</param>
 /// <param name="tags">The collection of tags associated with the Node.</param>
 public Node(int id, double longitude, double latitude, TagsCollection tags)
     : this(id, new Coordinate(longitude, latitude), tags)
 {
 }
Ejemplo n.º 50
0
        public void Remove_Tag_ReturnsFalseForEmptyCollection()
        {
            TagsCollection target = new TagsCollection();
            bool removed = target.Remove(new Tag("key", "value"));

            Assert.False(removed);
        }
Ejemplo n.º 51
0
        public void TestSimpleTagsCollectionEmpty()
        {
            var collection = new TagsCollection();

            Assert.AreEqual(0, collection.Count);
        }
Ejemplo n.º 52
0
        public void Remove_Tag_RemovesItemAndReturnsTrueIfCollectionContainsTag()
        {
            TagsCollection target = new TagsCollection(_tags);

            Assert.True(target.Remove(_tags[0]));
            this.CompareCollections(_tags.Skip(1), target);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Returns the tags with the given id.
 /// </summary>
 /// <param name="tagsId"></param>
 /// <returns></returns>
 public TagsCollectionBase Get(uint tagsId)
 {
     OsmTags osmTags = _tagsCollectionTable.Get(tagsId);
     if (osmTags != null)
     {
         TagsCollection collection = new TagsCollection();
         for (int idx = 0; idx < osmTags.Tags.Length; idx++)
         {
             collection.Add(
                 _tagsTable.Get(osmTags.Tags[idx]));
         }
         return collection;
     }
     return null;
 }
 /// <summary>
 /// Returns true if the edge is traversable.
 /// </summary>
 /// <param name="edgeInterpreter"></param>
 /// <param name="tagsIndex"></param>
 /// <param name="tags"></param>
 /// <returns></returns>
 protected override bool CalculateIsTraversable(IEdgeInterpreter edgeInterpreter,
                                                ITagsIndex tagsIndex, TagsCollection tags)
 {
     return(edgeInterpreter.IsRoutable(tags));
 }
Ejemplo n.º 55
0
        public void Item_Set_AddsItemToEmptyCollection()
        {
            TagsCollection target = new TagsCollection();

            target["test-key"] = "test-value";

            Assert.Equal(1, target.Count);
            Assert.Equal("test-value", target["test-key"]);
        }
Ejemplo n.º 56
0
        public void Clear_DoesNothingOnEmptyCollection()
        {
            TagsCollection target = new TagsCollection();

            Assert.DoesNotThrow(() => target.Clear());
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Interprets an OSM-object and returns the corresponding geometry.
        /// </summary>
        /// <param name="osmObject"></param>
        /// <returns></returns>
        public override GeometryCollection Interpret(ICompleteOsmGeo osmObject)
        {
            // DISCLAIMER: this is a very very very simple geometry interpreter and
            // contains hardcoded all relevant tags.

            GeometryCollection collection = new GeometryCollection();
            TagsCollectionBase tags;

            if (osmObject != null)
            {
                switch (osmObject.Type)
                {
                case CompleteOsmType.Node:
                    TagsCollection newCollection = new TagsCollection(
                        osmObject.Tags);
                    newCollection.RemoveKey("FIXME");
                    newCollection.RemoveKey("node");
                    newCollection.RemoveKey("source");

                    if (newCollection.Count > 0)
                    {     // there is still some relevant information left.
                        collection.Add(new Point((osmObject as Node).Coordinate));
                    }
                    break;

                case CompleteOsmType.Way:
                    tags = osmObject.Tags;

                    bool isArea = false;
                    if ((tags.ContainsKey("building") && !tags.IsFalse("building")) ||
                        (tags.ContainsKey("landuse") && !tags.IsFalse("landuse")) ||
                        (tags.ContainsKey("amenity") && !tags.IsFalse("amenity")) ||
                        (tags.ContainsKey("harbour") && !tags.IsFalse("harbour")) ||
                        (tags.ContainsKey("historic") && !tags.IsFalse("historic")) ||
                        (tags.ContainsKey("leisure") && !tags.IsFalse("leisure")) ||
                        (tags.ContainsKey("man_made") && !tags.IsFalse("man_made")) ||
                        (tags.ContainsKey("military") && !tags.IsFalse("military")) ||
                        (tags.ContainsKey("natural") && !tags.IsFalse("natural")) ||
                        (tags.ContainsKey("office") && !tags.IsFalse("office")) ||
                        (tags.ContainsKey("place") && !tags.IsFalse("place")) ||
                        (tags.ContainsKey("power") && !tags.IsFalse("power")) ||
                        (tags.ContainsKey("public_transport") && !tags.IsFalse("public_transport")) ||
                        (tags.ContainsKey("shop") && !tags.IsFalse("shop")) ||
                        (tags.ContainsKey("sport") && !tags.IsFalse("sport")) ||
                        (tags.ContainsKey("tourism") && !tags.IsFalse("tourism")) ||
                        (tags.ContainsKey("waterway") && !tags.IsFalse("waterway")) ||
                        (tags.ContainsKey("wetland") && !tags.IsFalse("wetland")) ||
                        (tags.ContainsKey("water") && !tags.IsFalse("water")) ||
                        (tags.ContainsKey("aeroway") && !tags.IsFalse("aeroway")))
                    {     // these tags usually indicate an area.
                        isArea = true;
                    }

                    if (tags.IsTrue("area"))
                    {     // explicitly indicated that this is an area.
                        isArea = true;
                    }
                    else if (tags.IsFalse("area"))
                    {     // explicitly indicated that this is not an area.
                        isArea = false;
                    }

                    if (isArea)
                    {     // area tags leads to simple polygon
                        LineairRing lineairRing = new LineairRing((osmObject as CompleteWay).GetCoordinates().ToArray <GeoCoordinate>());
                        lineairRing.Attributes = new SimpleGeometryAttributeCollection(tags);
                        collection.Add(lineairRing);
                    }
                    else
                    {     // no area tag leads to just a line.
                        LineString lineString = new LineString((osmObject as CompleteWay).GetCoordinates().ToArray <GeoCoordinate>());
                        lineString.Attributes = new SimpleGeometryAttributeCollection(tags);
                        collection.Add(lineString);
                    }
                    break;

                case CompleteOsmType.Relation:
                    CompleteRelation relation = (osmObject as CompleteRelation);
                    tags = relation.Tags;

                    string typeValue;
                    if (tags.TryGetValue("type", out typeValue))
                    {     // there is a type in this relation.
                        if (typeValue == "multipolygon")
                        { // this relation is a multipolygon.
                            Geometry geometry = this.InterpretMultipolygonRelation(relation);
                            if (geometry != null)
                            {     // add the geometry.
                                collection.Add(geometry);
                            }
                        }
                        else if (typeValue == "boundary")
                        {     // this relation is a boundary.
                        }
                    }
                    break;
                }
            }
            return(collection);
        }
Ejemplo n.º 58
0
        public void Item_Set_SetsTagValue()
        {
            TagsCollection target = new TagsCollection(_tags);
            target[_tags[0].Key] = "new-value";

            Assert.Equal("new-value", target[_tags[0].Key]);
        }
Ejemplo n.º 59
0
        private void CompareTags(TagsCollection expected, TagsCollection actual)
        {
            if (expected == null && actual == null) {
                return;
            }

            Assert.Equal(expected.Count, actual.Count);
            Assert.True(expected.All(tag => actual.Contains(tag)));
        }
Ejemplo n.º 60
0
        //=====================================================================
        // VIEW MODEL FUNCTIONS
        //=====================================================================

        public void AddTagToCollection(string tag)
        {
            TagsCollection.Add(tag);
        }