Ejemplo n.º 1
0
        public GPXTrackSegment Filter(TimeSpan minInterval, GPXTrackSegment track)
        {
            GPXTrackSegment result = new GPXTrackSegment();

            if (track.Nodes.Count == 0)
            {
                return(result);
            }

            GPXPoint last = track.Nodes[0];

            result.Nodes.Add(last);

            int index = 1;

            while (index < track.Nodes.Count)
            {
                if (track.Nodes[index].Time - last.Time >= minInterval)
                {
                    last = track.Nodes[index];
                    result.Nodes.Add(last);
                }
                index++;
            }

            if (last.Time != track.Nodes.Last().Time)
            {
                result.Nodes.Add(track.Nodes.Last());
            }

            return(result);
        }
Ejemplo n.º 2
0
        public GPXTrackSegment Filter(TimeSpan minInterval, GPXTrackSegment track)
        {
            GPXTrackSegment result = new GPXTrackSegment();

            if (track.Nodes.Count == 0)
                return result;

            GPXPoint last = track.Nodes[0];
            result.Nodes.Add(last);

            int index = 1;
            while (index < track.Nodes.Count) {
                if (track.Nodes[index].Time - last.Time >= minInterval) {
                    last = track.Nodes[index];
                    result.Nodes.Add(last);
                }
                index++;
            }

            if (last.Time != track.Nodes.Last().Time) {
                result.Nodes.Add(track.Nodes.Last());
            }

            return result;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Matches the given GPX track to the map
        /// </summary>
        /// <param name="gpx">The GPS track log</param>
        /// <returns>List of the CandidatePoints that match GPS log the best</returns>
        public IList <CandidatePoint> Match(GPXTrackSegment gpx)
        {
            _candidatesGraph = new CandidatesGraph();

            CreateTrackCutout(gpx);

            //Find candidate points + ObservationProbability
            foreach (var gpxPoint in gpx.Nodes)
            {
                var candidates = FindCandidatePoints(gpxPoint);
                _candidatesGraph.CreateLayer(gpxPoint, candidates.OrderByDescending(c => c.ObservationProbability).Take(Math.Min(candidates.Count(), TMM.MaxCandidatesCount)));
            }

            // Calculate transmission probability
            _candidatesGraph.ConnectLayers();

            AssignTransmissionProbability();

            //Evaluates paths in the graph
            EvaluateGraph();

            //Extract result
            List <CandidatePoint> result  = new List <CandidatePoint>();
            CandidatePoint        current = _candidatesGraph.Layers[_candidatesGraph.Layers.Count - 1].Candidates.OrderByDescending(c => c.HighestProbability).FirstOrDefault();

            while (current != null)
            {
                result.Add(current);
                current = current.HighesScoreParent;
            }

            result.Reverse();
            return(result);
        }
        public void GPXTrackSegmentConstructorAcceptsListOfGPXPoints()
        {
            GPXPoint pt1 = new GPXPoint(10.4, 5.2);
            GPXPoint pt2 = new GPXPoint(10.8, 5.3);

            GPXTrackSegment target = new GPXTrackSegment(new GPXPoint[] { pt1, pt2 });

            Assert.Equal(2, target.NodesCount);
            Assert.Equal(pt1, target.Nodes[0]);
            Assert.Equal(pt2, target.Nodes[1]);
        }
Ejemplo n.º 5
0
        static List <Bucket> GetUpdatedBuckets(GPXTrackSegment toProcess, List <Polyline <IPointGeo> > path,
                                               List <Bucket> buckets, String trackId)
        {
            var start = toProcess.Nodes.First().Time.TimeOfDay;
            var end   = toProcess.Nodes.Last().Time.TimeOfDay;

            foreach (var b in buckets)
            {
                if (start >= b.Start && end <= b.End)
                {
                    b.Paths.Add(trackId, path);
                }
            }
            return(buckets);
        }
Ejemplo n.º 6
0
        static void GenerateGpxFiles(List <Bucket> buckets, string file, int positionFile)
        {
            foreach (var b in buckets)
            {
                if (b.Paths.Any())
                {
                    // Saving the Map to GPX instead of OSM - START
                    var tracks = new List <GPXTrack>();

                    foreach (var p in b.Paths)
                    {
                        GPXTrack track = new GPXTrack(p.Key);
                        foreach (var t in p.Value)
                        {
                            List <GPXPoint> list = new List <GPXPoint>();

                            foreach (var s in t.Segments)
                            {
                                GPXPoint start = new GPXPoint()
                                {
                                    Latitude = s.StartPoint.Latitude, Longitude = s.StartPoint.Longitude
                                };
                                GPXPoint end = new GPXPoint()
                                {
                                    Latitude = s.EndPoint.Latitude, Longitude = s.EndPoint.Longitude
                                };

                                list.Add(start);
                                list.Add(end);
                            }

                            GPXTrackSegment gpxTrack = new GPXTrackSegment(list);
                            track.Segments.Add(gpxTrack);
                        }
                        tracks.Add(track);
                    }

                    var gpx = new GPXDocument()
                    {
                        Tracks = tracks
                    };
                    gpx.Save("mapGpx" + positionFile + ".gpx");
                    // END
                }
            }
        }
Ejemplo n.º 7
0
        static void ProcessGPXFile(string path, STMatching processor, PathReconstructer reconstructor, string outputPath, int samplingPeriod, bool filterOutput)
        {
            GPXUtils.Filters.FrequencyFilter filter = new GPXUtils.Filters.FrequencyFilter();

            Console.Write("Loading {0} ...", Path.GetFileName(path));
            GPXDocument gpx = new GPXDocument();

            gpx.Load(path);

            Console.WriteLine("[{0} track(s); {1} segment(s)]", gpx.Tracks.Count, gpx.Tracks.Sum(track => track.Segments.Count));
            for (int trackIndex = 0; trackIndex < gpx.Tracks.Count; trackIndex++)
            {
                for (int segmentIndex = 0; segmentIndex < gpx.Tracks[trackIndex].Segments.Count; segmentIndex++)
                {
                    string name = string.IsNullOrEmpty(gpx.Tracks[trackIndex].Name) ? "t" + trackIndex.ToString() : gpx.Tracks[trackIndex].Name.Replace('\\', '-').Replace(":", "");
                    name += "_s" + segmentIndex.ToString();
                    Console.Write("\t" + name + " ");

                    try {
                        GPXTrackSegment toProcess = gpx.Tracks[trackIndex].Segments[segmentIndex];
                        if (samplingPeriod > 0)
                        {
                            toProcess = filter.Filter(new TimeSpan(0, 0, samplingPeriod), toProcess);
                        }

                        var result = processor.Match(toProcess);
                        Console.Write(".");

                        var reconstructedPath = reconstructor.Reconstruct(result);
                        Console.Write(".");

                        if (filterOutput)
                        {
                            reconstructor.FilterUturns(reconstructedPath, 100);
                        }
                        var pathOsm = reconstructor.SaveToOSM(reconstructedPath);

                        pathOsm.Save(Path.Combine(outputPath, Path.GetFileNameWithoutExtension(path) + "_" + name + ".osm"));
                        Console.WriteLine(".");
                    }
                    catch (Exception e) {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private GPXTrackSegment ReadTrackSegment(long id)
        {
            GPXTrackSegment parsedSegment = new GPXTrackSegment();

            if (_xmlReader.IsEmptyElement == false)
            {
                _xmlReader.Read();
                parsedSegment.Id = id;

                while (_xmlReader.NodeType != XmlNodeType.EndElement)
                {
                    if (_xmlReader.NodeType == XmlNodeType.Element)
                    {
                        if (_xmlReader.Name == "avgSpeed" && Convert.ToDouble(_xmlReader.GetAttribute("v")) != 0)
                        {
                            parsedSegment.AvgSpeed = Convert.ToDouble(_xmlReader.GetAttribute("v"));
                        }

                        if (_xmlReader.Name == "speed" && Convert.ToDouble(_xmlReader.GetAttribute("v")) != 0)
                        {
                            parsedSegment.Speed = Convert.ToDouble(_xmlReader.GetAttribute("v"));
                        }

                        switch (_xmlReader.Name)
                        {
                        case "trkpt":
                            parsedSegment.Nodes.Add(ReadPoint());
                            break;

                        default:
                            _xmlReader.Skip();
                            break;
                        }
                    }
                    else
                    {
                        _xmlReader.Skip();
                    }
                }
            }

            _xmlReader.Skip();
            return(parsedSegment);
        }
Ejemplo n.º 9
0
        void CreateTrackCutout(GPXTrackSegment track)
        {
            _trackCutout.Clear();

            BBox trackBBox = new BBox();

            foreach (var point in track.Nodes)
            {
                trackBBox.ExtendToCover(point);
            }
            trackBBox.Inflate(0.0015, 0.0015);

            foreach (var road in _graph.ConnectionGeometries)
            {
                if (Topology.Intersects(road.BBox, trackBBox))
                {
                    _trackCutout.Add(road);
                }
            }
        }
Ejemplo n.º 10
0
        static void ProcessGPXFile(string path, List <Double> tlist, int samplingPeriod, bool filterOutput)
        {
            LK.GPXUtils.Filters.FrequencyFilter filter = new LK.GPXUtils.Filters.FrequencyFilter();

            Console.Write("Loading {0} ...", Path.GetFileName(path));
            GPXDocument gpx = new GPXDocument();

            gpx.Load(path);

            Console.WriteLine("[{0} track(s); {1} segment(s)]", gpx.Tracks.Count, gpx.Tracks.Sum(track => track.Segments.Count));
            for (int trackIndex = 0; trackIndex < gpx.Tracks.Count; trackIndex++)
            {
                for (int segmentIndex = 0; segmentIndex < gpx.Tracks[trackIndex].Segments.Count; segmentIndex++)
                {
                    string name = string.IsNullOrEmpty(gpx.Tracks[trackIndex].Name) ? "t" + trackIndex.ToString() : gpx.Tracks[trackIndex].Name.Replace('\\', '-').Replace(":", "");
                    name += "_s" + segmentIndex.ToString();
                    //Console.Write("\t" + name + " ");

                    try
                    {
                        GPXTrackSegment toProcess = gpx.Tracks[trackIndex].Segments[segmentIndex];
                        if (samplingPeriod > 0)
                        {
                            toProcess = filter.Filter(new TimeSpan(0, 0, samplingPeriod), toProcess);
                        }


                        foreach (var t in toProcess.Nodes)
                        {
                            tlist.Add(Utils.Time2Double(t.Time));
                        }
                        //Console.WriteLine(".");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        private GPXTrackSegment ReadTrackSegment()
        {
            GPXTrackSegment parsedSegment = new GPXTrackSegment();

            if (_xmlReader.IsEmptyElement == false) {
                _xmlReader.Read();

                while (_xmlReader.NodeType != XmlNodeType.EndElement) {
                    if (_xmlReader.NodeType == XmlNodeType.Element) {
                        switch (_xmlReader.Name) {
                            case "trkpt":
                                parsedSegment.Nodes.Add(ReadPoint());
                                break;
                            default:
                                _xmlReader.Skip();
                                break;
                        }
                    }
                    else {
                        _xmlReader.Skip();
                    }
                }
            }

            _xmlReader.Skip();
            return parsedSegment;
        }
Ejemplo n.º 12
0
        public void GPXTrackSegmentConstructorCreatesEmptySegment()
        {
            GPXTrackSegment target = new GPXTrackSegment();

            Assert.Equal(0, target.NodesCount);
        }
Ejemplo n.º 13
0
        static void ProcessCSVFile(string path, string outputPath, int samplingPeriod)
        {
            double max_lat = -3.691978693, min_lat = -3.8881242275, max_lon = -38.4018707275, min_lon = -38.6374359131; //geo-bounding box for Fortaleza

            GPXDocument gpx = new GPXDocument();

            Console.Write("Parsing {0} ...", Path.GetFileName(path));

            string line;

            char[] seps = { ';', ',', '\t' };
            char   sep  = '.';

            String[] fields = { };

            long last_id = -1;

            int      id_field   = 0;
            int      lat_field  = 1;
            int      lon_field  = 2;
            int      time_field = 7;
            int      uf1_field  = 3;
            int      uf2_field  = 4;
            int      uf3_field  = 5;
            int      uf4_field  = 6;
            Boolean  header     = true;
            GPXTrack trk        = null;

            List <long> ids = new List <long>();

            if (samplingPeriod > 0)
            {
                DateTime dt = File.GetLastWriteTime(path);
                if ((DateTime.Now - dt).Days > samplingPeriod)
                {
                    Console.WriteLine("skiping");
                    return;
                }
            }

            // Read the file and display it line by line.
            System.IO.StreamReader csv = new System.IO.StreamReader(path);

            line = csv.ReadLine();
            if (line != null)
            {
                for (int i = 0; i < seps.Length; i++)
                {
                    if ((fields = line.Split(seps[i])).Length > 1)
                    {
                        sep = seps[i];
                        break;
                    }
                }
                if (sep == '.')
                {
                    throw new Exception(string.Format("Can not find any known separators.{';',',','TAB'}"));
                }

                for (int i = 0; i < fields.Length; i++)
                {
                    if (fields[i] == "id")
                    {
                        id_field = i;
                    }
                    else
                    if (fields[i] == "lat")
                    {
                        lat_field = i;
                    }
                    else
                    if (fields[i] == "lon")
                    {
                        lon_field = i;
                    }
                    else
                    if (fields[i] == "time")
                    {
                        time_field = i;
                    }
                    else
                    if (fields[i] == "uf1")
                    {
                        uf1_field = i;
                    }
                    else
                    if (fields[i] == "uf2")
                    {
                        uf2_field = i;
                    }
                    else
                    if (fields[i] == "uf3")
                    {
                        uf3_field = i;
                    }
                    else
                    if (fields[i] == "uf4")
                    {
                        uf4_field = i;
                    }
                    else
                    {
                        header = false;
                        Console.WriteLine(string.Format("Can not find header line.(id, lat, lon, time)"));
                        csv.Close();
                        csv = new System.IO.StreamReader(path);
                        break;
                    }
                }
            }
            if (!header)
            {
                line = csv.ReadLine();
            }
            while ((line = csv.ReadLine()) != null)
            {
                fields = line.Split(sep);
                long id = Convert.ToInt64(fields[id_field]);
                if (id != last_id)
                {
                    if (ids.Find(item => item == id) == 0)
                    {
                        ids.Add(id);
                    }
                    last_id = id;
                    //break;
                }
            }
            csv.Close();


            foreach (long next_id in ids)
            {
                Console.Write(next_id);

                int count = 0;

                csv = new System.IO.StreamReader(path);
                trk = new GPXTrack();
                GPXTrackSegment trkseg = new GPXTrackSegment();
                gpx.Tracks.Add(trk);
                trk.Name = "trk_" + next_id;
                line     = csv.ReadLine();

                while ((line = csv.ReadLine()) != null)
                {
                    fields = line.Split(sep);
                    long id = Convert.ToInt64(fields[id_field]);
                    if (id == next_id)
                    {
                        if (!(fields[lat_field] == "null" && fields[lon_field] == "null"))
                        {
                            var lat = Double.Parse(fields[lat_field], System.Globalization.CultureInfo.InvariantCulture);
                            var lon = Double.Parse(fields[lon_field], System.Globalization.CultureInfo.InvariantCulture);

                            if (lat > min_lat && lat < max_lat && lon > min_lon && lon < max_lon)
                            {
                                GPXPoint p = new GPXPoint();

                                p.Latitude  = lat;
                                p.Longitude = lon;
                                p.Time      = DateTime.ParseExact(fields[time_field], "ddd MMM dd yyyy HH:mm:ss 'GMT-0300 (BRT)'", System.Globalization.CultureInfo.InvariantCulture);

                                trkseg.Nodes.Add(p);
                                count++;
                            }
                        }
                    }
                }
                trk.Segments.Add(trkseg);
                csv.Close();
                Console.WriteLine("[" + count + "]");
            }

            String fileout = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(path) + ".gpx");

            Console.WriteLine(fileout);
            gpx.Save(fileout);
            Console.WriteLine("\tDone.");
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            string osmPath    = "";
            int    eps        = -1;
            int    minTraffic = -1;
            bool   showHelp   = false;

            OptionSet parameters = new OptionSet()
            {
                { "osm=", "path to the map file", v => osmPath = v },
                { "eps=", "size of the eps-neighborhood to be considered (integer)", v => eps = Convert.ToInt32(v) },
                { "minTraffic=", "minimum traffic considered (integer)", v => minTraffic = Convert.ToInt32(v) },
                { "h|?|help", v => showHelp = v != null },
            };

            try
            {
                parameters.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("TRoute: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `TRoute --help' for more information.");
                return;
            }

            if (showHelp || string.IsNullOrEmpty(osmPath) || eps < 0 || minTraffic < 0)
            {
                ShowHelp(parameters);
                return;
            }

            var osmFile = new OSMDB();

            osmFile.Load(osmPath);
            var roadGraph = new RoadGraph();

            roadGraph.Build(osmFile);

            // Getting all the nodes with traffic signals
            Dictionary <double, OSMNode> tagsNodes = new Dictionary <double, OSMNode>();

            foreach (var node in osmFile.Nodes)
            {
                foreach (var tag in node.Tags)
                {
                    if (tag.Value.Equals("traffic_signals"))
                    {
                        if (!tagsNodes.Keys.Contains(node.Latitude + node.Longitude))
                        {
                            tagsNodes.Add(node.Latitude + node.Longitude, node);
                        }
                    }
                }
            }

            var hotRoutes = new FlowScan().Run(roadGraph, eps, minTraffic);

            // Saving GPX file of the Hot Route
            HashSet <GPXPoint>        listPoints;
            HashSet <GPXTrackSegment> listSegments;
            GPXTrackSegment           segTrack;

            List <GPXTrack> track = new List <GPXTrack>();
            GPXTrack        tr;

            //Console.WriteLine(hotRoutes.Count);
            foreach (var hr in hotRoutes)
            {
                //Console.WriteLine("Number segs: " + hr.Segments.Count);
                listSegments = new HashSet <GPXTrackSegment>();

                foreach (var seg in hr.Segments)
                {
                    listPoints = new HashSet <GPXPoint>();

                    foreach (var segInner in seg.Geometry.Segments)
                    {
                        GPXPoint start;
                        if (tagsNodes.Keys.Contains(segInner.StartPoint.Latitude + segInner.StartPoint.Longitude))
                        {
                            OSMNode osmNode = tagsNodes[segInner.StartPoint.Latitude + segInner.StartPoint.Longitude];
                            start = new GPXPoint()
                            {
                                Id        = osmNode.ID, Latitude = segInner.StartPoint.Latitude,
                                Longitude = segInner.StartPoint.Longitude, TrafficSignal = true
                            };
                        }
                        else
                        {
                            OSMNode osmNode = osmFile.Nodes.ToList().First(x => x.Latitude == segInner.StartPoint.Latitude &&
                                                                           x.Longitude == segInner.StartPoint.Longitude);
                            start = new GPXPoint()
                            {
                                Id        = osmNode.ID, Latitude = segInner.StartPoint.Latitude,
                                Longitude = segInner.StartPoint.Longitude, TrafficSignal = false
                            };
                        }

                        GPXPoint end;
                        if (tagsNodes.Keys.Contains(segInner.EndPoint.Latitude + segInner.EndPoint.Longitude))
                        {
                            OSMNode osmNode = tagsNodes[segInner.EndPoint.Latitude + segInner.EndPoint.Longitude];
                            end = new GPXPoint()
                            {
                                Id        = osmNode.ID, Latitude = segInner.EndPoint.Latitude,
                                Longitude = segInner.EndPoint.Longitude, TrafficSignal = true
                            };
                        }
                        else
                        {
                            OSMNode osmNode = osmFile.Nodes.ToList().First(x => x.Latitude == segInner.EndPoint.Latitude &&
                                                                           x.Longitude == segInner.EndPoint.Longitude);
                            end = new GPXPoint()
                            {
                                Id        = osmNode.ID, Latitude = segInner.EndPoint.Latitude,
                                Longitude = segInner.EndPoint.Longitude, TrafficSignal = false
                            };
                        }

                        listPoints.Add(start);
                        listPoints.Add(end);
                    }

                    segTrack = new GPXTrackSegment(listPoints, seg.AvgSpeed, seg.Speed, seg.Id);
                    // passing the traffic
                    segTrack.Traffic = seg.Traffic;
                    listSegments.Add(segTrack);
                }

                tr = new GPXTrack();
                tr.Segments.AddRange(listSegments);
                track.Add(tr);
            }

            // Bucket Information
            GPXTrack        tBucket = new GPXTrack();
            GPXPoint        pBucket = new GPXPoint(0, 0, 0, false);
            GPXTrackSegment sBucket = new GPXTrackSegment();

            var bucketInfo = osmFile.Nodes.ToList().Find(x => x.ID == 0);

            if (bucketInfo != null)
            {
                pBucket.StartBucket = TimeSpan.Parse(bucketInfo.Tags.First().Value);
                pBucket.EndBucket   = TimeSpan.Parse(bucketInfo.Tags.Last().Value);
            }

            sBucket.Nodes.Add(pBucket);
            tBucket.Segments.Add(sBucket);

            var gpx = new GPXDocument()
            {
                Tracks = track
            };

            gpx.Tracks.Add(tBucket);
            gpx.Save("mapWithHotRoutes.gpx");
        }
Ejemplo n.º 15
0
        static void ProcessGPXFile(string path, TMM processor, PathReconstructer reconstructor, string outputPath, int samplingPeriod,
                                   bool filterOutput, List <Bucket> buckets)
        {
            GPXUtils.Filters.FrequencyFilter filter = new GPXUtils.Filters.FrequencyFilter();

            Console.Write("Loading {0} ...", Path.GetFileName(path));
            GPXDocument gpx = new GPXDocument();

            gpx.Load(path);

            Console.WriteLine("[{0} track(s); {1} segment(s)]", gpx.Tracks.Count, gpx.Tracks.Sum(track => track.Segments.Count));
            for (int trackIndex = 0; trackIndex < gpx.Tracks.Count; trackIndex++)
            {
                Console.WriteLine(gpx.Tracks[trackIndex].Name);

                for (int segmentIndex = 0; segmentIndex < gpx.Tracks[trackIndex].Segments.Count; segmentIndex++)
                {
                    string name = string.IsNullOrEmpty(gpx.Tracks[trackIndex].Name) ? "t" + trackIndex.ToString() : gpx.Tracks[trackIndex].Name.Replace('\\', '-').Replace(":", "");
                    name += "_s" + segmentIndex.ToString();
                    Console.Write("\t" + name + " ");

                    try
                    {
                        GPXTrackSegment toProcess = gpx.Tracks[trackIndex].Segments[segmentIndex];

                        if (samplingPeriod > 0)
                        {
                            toProcess = filter.Filter(new TimeSpan(0, 0, samplingPeriod), toProcess);
                        }

                        if (toProcess.NodesCount > 1)
                        {
                            var result = processor.Match(toProcess);
                            Console.Write(".");

                            var reconstructedPath = reconstructor.Reconstruct(result);

                            Console.Write(".");

                            if (filterOutput)
                            {
                                reconstructor.FilterUturns(reconstructedPath, 100);
                            }

                            Console.WriteLine(".");

                            var trackId = gpx.Tracks[trackIndex].Name.Replace("trk_", "");
                            buckets = GetUpdatedBuckets(toProcess, reconstructedPath, buckets, trackId);
                        }
                        else
                        {
                            throw new Exception(string.Format("Track segment discarded because number of nodes is less than 2."));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.Message);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        void CreateTrackCutout(GPXTrackSegment track)
        {
            _trackCutout.Clear();

            BBox trackBBox = new BBox();
            foreach (var point in track.Nodes) {
                trackBBox.ExtendToCover(point);
            }
            trackBBox.Inflate(0.0015, 0.0015);

            foreach (var road in _graph.ConnectionGeometries) {
                if (Topology.Intersects(road.BBox, trackBBox)) {
                    _trackCutout.Add(road);
                }
            }
        }
        public void GPXXmlDataWriterWriteTrackWithMultipleSegments()
        {
            MemoryStream ms = new MemoryStream();

            GPXTrack track = new GPXTrack();
            track.Name = "TRACK NAME";

            GPXPoint point1 = new GPXPoint(18.5, 50.1);
            GPXPoint point2 = new GPXPoint(10.3, 20.5);
            GPXPoint point3 = new GPXPoint(8.2, 28.8);

            GPXTrackSegment segment1 = new GPXTrackSegment();
            segment1.Nodes.Add(point1);
            segment1.Nodes.Add(point2);
            segment1.Nodes.Add(point3);
            track.Segments.Add(segment1);

            GPXTrackSegment segment2 = new GPXTrackSegment();
            segment2.Nodes.Add(point1);
            segment2.Nodes.Add(point2);
            track.Segments.Add(segment2);

            using (GPXXmlDataWriter target = new GPXXmlDataWriter(ms)) {
                target.WriteTrack(track);
            }

            ms.Seek(0, 0);

            XElement gpxRoot = XDocument.Load(new StreamReader(ms)).Root;

            XElement trackElement = gpxRoot.Element("trk");
            Assert.NotNull(trackElement);
            Assert.Equal(track.Name, trackElement.Element("name").Value);

            var trackSegments = trackElement.Elements("trkseg").ToList();
            Assert.Equal(track.Segments.Count, trackSegments.Count);

            var points = trackSegments[0].Elements("trkpt").ToList();
            Assert.Equal(track.Segments[0].NodesCount, points.Count);

            points = trackSegments[1].Elements("trkpt").ToList();
            Assert.Equal(track.Segments[1].NodesCount, points.Count);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Matches the given GPX track to the map
        /// </summary>
        /// <param name="gpx">The GPS track log</param>
        /// <returns>List of the CandidatePoints that match GPS log the best</returns>
        public IList<CandidatePoint> Match(GPXTrackSegment gpx)
        {
            _candidatesGraph = new CandidatesGraph();

            CreateTrackCutout(gpx);

            //Find candidate points + ObservationProbability
            foreach (var gpxPoint in gpx.Nodes) {
                var candidates = FindCandidatePoints(gpxPoint);

                _candidatesGraph.CreateLayer(gpxPoint, candidates.OrderByDescending(c => c.ObservationProbability).Take(Math.Min(candidates.Count(), STMatching.MaxCandidatesCount)));
            }

            // Calculate transmission probability
            _candidatesGraph.ConnectLayers();
            AssignTransmissionProbability();

            //Evaluates paths in the graph
            EvaluateGraph();

            //Extract result
            List<CandidatePoint> result = new List<CandidatePoint>();
            CandidatePoint current = _candidatesGraph.Layers[_candidatesGraph.Layers.Count - 1].Candidates.OrderByDescending(c => c.HighestProbability).FirstOrDefault();

            while (current != null) {
                result.Add(current);
                current = current.HighesScoreParent;
            }

            result.Reverse();
            return result;
        }
        public void GPXXmlDataWriterWriteSimpleTrack()
        {
            MemoryStream ms = new MemoryStream();

            GPXTrack track = new GPXTrack();
            track.Name = "TRACK NAME";

            GPXPoint point1 = new GPXPoint(18.5, 50.1);
            GPXPoint point2 = new GPXPoint(10.3, 20.5);

            GPXTrackSegment segment = new GPXTrackSegment();
            segment.Nodes.Add(point1);
            segment.Nodes.Add(point2);

            track.Segments.Add(segment);

            using (GPXXmlDataWriter target = new GPXXmlDataWriter(ms)) {
                target.WriteTrack(track);
            }

            ms.Seek(0, 0);

            XElement gpxRoot = XDocument.Load(new StreamReader(ms)).Root;

            XElement trackElement = gpxRoot.Element("trk");
            Assert.NotNull(trackElement);
            Assert.Equal(track.Name, trackElement.Element("name").Value);

            XElement trackSegmentElement = trackElement.Element("trkseg");
            Assert.NotNull(trackSegmentElement);

            var points = trackSegmentElement.Elements("trkpt").ToList();
            Assert.Equal(2, points.Count);
            Assert.Equal(point1.Latitude, double.Parse(points[0].Attribute("lat").Value, System.Globalization.CultureInfo.InvariantCulture));
            Assert.Equal(point1.Longitude, double.Parse(points[0].Attribute("lon").Value, System.Globalization.CultureInfo.InvariantCulture));
            Assert.Equal(point2.Latitude, double.Parse(points[1].Attribute("lat").Value, System.Globalization.CultureInfo.InvariantCulture));
            Assert.Equal(point2.Longitude, double.Parse(points[1].Attribute("lon").Value, System.Globalization.CultureInfo.InvariantCulture));
        }