Exemple #1
0
    // This method verifies a.GetDistance(b), where b is a S2LatLng, by comparing
    // its result against a.GetDistance(c), c being the point rectangle created
    // from b.
    private static void VerifyGetRectPointDistance(S2LatLngRect a, S2LatLng p)
    {
        S1Angle distance1 = BruteForceRectPointDistance(a, p.Normalized());
        S1Angle distance2 = a.GetDistance(p.Normalized());

        Assert2.Near(Math.Abs(distance1.Radians - distance2.Radians), 0, 1e-10);
    }
Exemple #2
0
        public static ulong[] GetCellIdsForLatLong(double latitude, double longitude)
        {
            var latLong = S2LatLng.FromDegrees(latitude, longitude);
            var cell    = S2CellId.FromLatLng(latLong);
            var cellId  = cell.ParentForLevel(15);
            var cells   = cellId.GetEdgeNeighbors();
            var cellIds = new List <ulong>
            {
                cellId.Id
            };

            foreach (var cellEdge1 in cells)
            {
                if (!cellIds.Contains(cellEdge1.Id))
                {
                    cellIds.Add(cellEdge1.Id);
                }

                foreach (var cellEdge2 in cellEdge1.GetEdgeNeighbors())
                {
                    if (!cellIds.Contains(cellEdge2.Id))
                    {
                        cellIds.Add(cellEdge2.Id);
                    }
                }
            }

            return(cellIds.ToArray());
        }
Exemple #3
0
        public void AddUser(Guid uid, double lon, double lat)
        {
            var lonLat = S2LatLng.FromDegrees(lat, lon);

            var cellId = S2CellId.FromLatLng(lonLat);

            var cellIdStorageLevel = cellId.ParentForLevel(_level);

            var userList = new UserList {
                s2CellId = cellIdStorageLevel, list = new List <Guid>()
            };

            var item = tree.Search(userList.s2CellId);

            if (item != null)
            {
                userList = new UserList {
                    s2CellId = item.Key, list = item.Pointer
                };

                tree.Delete(userList.s2CellId);
            }

            if (userList.list == null)
            {
                userList.list = new List <Guid>();
            }
            userList.list.Add(uid);

            tree.Insert(userList.s2CellId, userList.list);
        }
Exemple #4
0
    public void Test_S2LatLngRect_FromPoint()
    {
        S2LatLng p = S2LatLng.FromDegrees(23, 47);

        Assert.Equal(S2LatLngRect.FromPoint(p), new S2LatLngRect(p, p));
        Assert.True(S2LatLngRect.FromPoint(p).IsPoint());
    }
    // Returns the bounding rectangle of the edge chain that connects the
    // vertices defined so far.  This bound satisfies the guarantee made
    // above, i.e. if the edge chain defines a loop, then the bound contains
    // the S2LatLng coordinates of all S2Points contained by the loop.
    public S2LatLngRect GetBound()
    {
        // To save time, we ignore numerical errors in the computed S2LatLngs while
        // accumulating the bounds and then account for them here.
        //
        // S2LatLng(S2Point) has a maximum error of 0.955 * S2Constants.DoubleEpsilon in latitude.
        // In the worst case, we might have rounded "inwards" when computing the
        // bound and "outwards" when computing the latitude of a contained point P,
        // therefore we expand the latitude bounds by 2 * S2Constants.DoubleEpsilon in each
        // direction.  (A more complex analysis shows that 1.5 * S2Constants.DoubleEpsilon is
        // enough, but the expansion amount should be a multiple of S2Constants.DoubleEpsilon in
        // order to avoid rounding errors during the expansion itself.)
        //
        // S2LatLng(S2Point) has a maximum error of S2Constants.DoubleEpsilon in longitude, which
        // is simply the maximum rounding error for results in the range [-Pi, Pi].
        // This is true because the Gnu implementation of atan2() comes from the IBM
        // Accurate Mathematical Library, which implements correct rounding for this
        // instrinsic (i.e., it returns the infinite precision result rounded to the
        // nearest representable value, with ties rounded to even values).  This
        // implies that we don't need to expand the longitude bounds at all, since
        // we only guarantee that the bound contains the *rounded* latitudes of
        // contained points.  The *true* latitudes of contained points may lie up to
        // S2Constants.DoubleEpsilon outside of the returned bound.
        S2LatLng kExpansion = S2LatLng.FromRadians(2 * S2.DoubleEpsilon, 0);

        return(bound_.Expanded(kExpansion).PolarClosure());
    }
Exemple #6
0
    private static void TestIntervalOps(S2LatLngRect x, S2LatLngRect y, string expected_relation, S2LatLngRect expected_union, S2LatLngRect expected_intersection)
    {
        // Test all of the interval operations on the given pair of intervals.
        // "expected_relation" is a sequence of "T" and "F" characters corresponding
        // to the expected results of Contains(), InteriorContains(), Intersects(),
        // and InteriorIntersects() respectively.

        Assert.Equal(x.Contains(y), expected_relation[0] == 'T');
        Assert.Equal(x.InteriorContains(y), expected_relation[1] == 'T');
        Assert.Equal(x.Intersects(y), expected_relation[2] == 'T');
        Assert.Equal(x.InteriorIntersects(y), expected_relation[3] == 'T');

        Assert.Equal(x.Contains(y), x.Union(y) == x);
        Assert.Equal(x.Intersects(y), !x.Intersection(y).IsEmpty());

        Assert.Equal(x.Union(y), expected_union);
        Assert.Equal(x.Intersection(y), expected_intersection);

        if (y.Size() == S2LatLng.FromRadians(0, 0))
        {
            S2LatLngRect r = x;
            r.AddPoint(y.Lo());
            Assert.Equal(r, expected_union);
        }
    }
Exemple #7
0
        /// <summary>
        ///     Filter out any points outside of the queried area from the input list.
        /// </summary>
        /// <param name="list">List of items return by Amazon DynamoDB. It may contains points outside of the actual area queried.</param>
        /// <param name="geoQueryRequest">List of items within the queried area.</param>
        /// <returns></returns>
        private IEnumerable <IDictionary <string, AttributeValue> > Filter(IEnumerable <IDictionary <string, AttributeValue> > list,
                                                                           GeoQueryRequest geoQueryRequest)
        {
            var result = new List <IDictionary <String, AttributeValue> >();

            S2LatLngRect?latLngRect    = null;
            S2LatLng?    centerLatLng  = null;
            double       radiusInMeter = 0;

            if (geoQueryRequest is QueryRectangleRequest)
            {
                latLngRect = S2Util.GetBoundingLatLngRect(geoQueryRequest);
            }
            foreach (var item in list)
            {
                var geoJson  = item[_config.GeoJsonAttributeName].S;
                var geoPoint = GeoJsonMapper.GeoPointFromString(geoJson);

                var latLng = S2LatLng.FromDegrees(geoPoint.lat, geoPoint.lng);
                if (latLngRect != null && latLngRect.Value.Contains(latLng))
                {
                    result.Add(item);
                }
                else if (centerLatLng != null && radiusInMeter > 0 &&
                         centerLatLng.Value.GetEarthDistance(latLng) <= radiusInMeter)
                {
                    result.Add(item);
                }
            }

            return(result);
        }
        public List <S2CellId> GetS2CellIds(ushort level, int maxCells)
        {
            //var geofence = Geofence.FromMultiPolygon(this);
            var bbox          = GetBoundingBox();
            var regionCoverer = new S2RegionCoverer
            {
                MinLevel = level,
                MaxLevel = level,
                MaxCells = maxCells,
            };
            var region = new S2LatLngRect(
                S2LatLng.FromDegrees(bbox.MinimumLatitude, bbox.MinimumLongitude),
                S2LatLng.FromDegrees(bbox.MaximumLatitude, bbox.MaximumLongitude)
                );
            var coverage = new List <S2CellId>();

            regionCoverer.GetCovering(region, coverage);
            var result = new List <S2CellId>();

            foreach (var cellId in coverage)
            {
                var cell = new S2Cell(cellId);
                for (var i = 0; i <= 3; i++)
                {
                    var vertex = cell.GetVertex(i);
                    var coord  = new S2LatLng(new S2Point(vertex.X, vertex.Y, vertex.Z));
                    //if (geofence.Intersects(coord.LatDegrees, coord.LngDegrees))
                    if (GeofenceService.InPolygon(this, coord.LatDegrees, coord.LngDegrees))
                    {
                        result.Add(cellId);
                    }
                }
            }
            return(result);
        }
        /**
         * This method verifies a.getDistance(b), where b is a S2LatLng, by comparing
         * its result against a.getDistance(c), c being the point rectangle created
         * from b.
         */

        private static void verifyGetRectPointDistance(S2LatLngRect a, S2LatLng p)
        {
            var distance1 = bruteForceRectPointDistance(a, p.Normalized);
            var distance2 = a.GetDistance(p.Normalized);

            assertEquals(distance1.Radians, distance2.Radians, 1e-10);
        }
Exemple #10
0
 public void Test_MakeLatLngRect_ValidInput()
 {
     Assert.True(MakeLatLngRect("-10:-10, 10:10", out var rect));
     Assert.Equal(rect, new S2LatLngRect(
                      S2LatLng.FromDegrees(-10, -10),
                      S2LatLng.FromDegrees(10, 10)));
 }
Exemple #11
0
 public void Test_S2LatLng_TestDistance()
 {
     Assert.Equal(0.0, S2LatLng.FromDegrees(90, 0).GetDistance(S2LatLng.FromDegrees(90, 0)).Radians);
     Assert2.Near(77.0, S2LatLng.FromDegrees(-37, 25).GetDistance(S2LatLng.FromDegrees(-66, -155)).GetDegrees(), 1e-13);
     Assert2.Near(115.0, S2LatLng.FromDegrees(0, 165).GetDistance(S2LatLng.FromDegrees(0, -80)).GetDegrees(), 1e-13);
     Assert2.Near(180.0, S2LatLng.FromDegrees(47, -127).GetDistance(S2LatLng.FromDegrees(-47, 53)).GetDegrees(), 2e-6);
 }
Exemple #12
0
        public void testConversion()
        {
            // Test special cases: poles, "date line"
            assertDoubleNear(
                new S2LatLng(S2LatLng.FromDegrees(90.0, 65.0).ToPoint()).Lat.Degrees, 90.0);
            assertEquals(
                new S2LatLng(S2LatLng.FromRadians(-S2.PiOver2, 1).ToPoint()).Lat.Radians, -S2.PiOver2);
            assertDoubleNear(
                Math.Abs(new S2LatLng(S2LatLng.FromDegrees(12.2, 180.0).ToPoint()).Lng.Degrees), 180.0);
            assertEquals(
                Math.Abs(new S2LatLng(S2LatLng.FromRadians(0.1, -S2.Pi).ToPoint()).Lng.Radians),
                S2.Pi);

            // Test a bunch of random points.
            for (var i = 0; i < 100000; ++i)
            {
                var p = randomPoint();
                assertTrue(S2.ApproxEquals(p, new S2LatLng(p).ToPoint()));
            }

            // Test generation from E5
            var test = S2LatLng.FromE5(123456, 98765);

            assertDoubleNear(test.Lat.Degrees, 1.23456);
            assertDoubleNear(test.Lng.Degrees, 0.98765);
        }
    public void Test_LoopTestBase_GetAreaConsistentWithOrientation()
    {
        // Test that GetArea() returns an area near 0 for degenerate loops that
        // contain almost no points, and an area near 4*Pi for degenerate loops that
        // contain almost all points.

        const int kMaxVertices = 6;

        for (int i = 0; i < 50; ++i)
        {
            int num_vertices = 3 + S2Testing.Random.Uniform(kMaxVertices - 3 + 1);
            // Repeatedly choose N vertices that are exactly on the equator until we
            // find some that form a valid loop.
            S2PointLoopSpan loop = new();
            do
            {
                for (int i2 = 0; i2 < num_vertices; ++i2)
                {
                    // We limit longitude to the range [0, 90] to ensure that the loop is
                    // degenerate (as opposed to following the entire equator).
                    loop.Add(
                        S2LatLng.FromRadians(0, S2Testing.Random.RandDouble() * S2.M_PI_2).ToPoint());
                }
            } while (!new S2Loop(loop, S2Debug.DISABLE).IsValid());
            bool ccw = S2.IsNormalized(loop);
            // The error bound is sufficient for current tests but not guaranteed.
            _ = i + ": " + loop.ToDebugString();
            Assert2.Near(ccw ? 0 : S2.M_4_PI, S2.GetArea(loop), 1e-14);
            Assert.Equal(!ccw, new S2Loop(loop).Contains(new S2Point(0, 0, 1)));
        }
    }
        private S2CellId getCellId(double latDegrees, double lngDegrees)
        {
            var id = S2CellId.FromLatLng(S2LatLng.FromDegrees(latDegrees, lngDegrees));

            Trace.WriteLine(Convert.ToString(unchecked ((long)id.Id), 16));
            return(id);
        }
        private static List <Coordinate> GetS2Cells(BoundingBox bbox)
        {
            var regionCoverer = new S2RegionCoverer
            {
                MinLevel = 15,
                MaxLevel = 15,
                //MaxCells = 100,
            };
            var region = new S2LatLngRect(
                S2LatLng.FromDegrees(bbox.MinimumLatitude, bbox.MinimumLongitude),
                S2LatLng.FromDegrees(bbox.MaximumLatitude, bbox.MaximumLongitude)
                );
            var cellIds = regionCoverer.GetCovering(region);
            var list    = new List <Coordinate>();

            foreach (var cellId in cellIds)
            {
                var center = cellId.ToLatLng();
                list.Add(new Coordinate(center.LatDegrees, center.LngDegrees));
            }
            // TODO: Check if point is within geofence
            //var filtered = FilterCoordinates(coordinates);
            //return filtered;
            return(list);
        }
Exemple #16
0
        /// <summary>
        /// Find the cell of the given level that covers the given Geoposition.
        /// This method uses the library given S2RegionCoverer to find the leaf cell containing the given Geoposition
        /// and uses binary operation on the leaf cell's Id to find the higher level cell containing the leaf.
        /// This is somehow more accurate than using the S2RegionCoverer for the higher level cell, where some errors occured.
        /// </summary>
        /// <param name="pos">Position in the cell</param>
        /// <param name="level">Level of the cell</param>
        /// <returns>The cell covering the given position that matches the specifications</returns>
        private S2Cell FindExactCell(BasicGeoposition pos, int level)
        {
            var point = S2LatLngRect.FromPoint(S2LatLng.FromDegrees(pos.Latitude, pos.Longitude));

            var cells = new List <S2CellId>();

            // find leaf cell
            var coverer = new S2RegionCoverer()
            {
                MinLevel = 30,
                MaxLevel = 30,
                MaxCells = 1
            };

            coverer.GetCovering(point, cells);

            var leaf = new S2Cell(cells[0]);

            int   shift = 64 - (3 + level * 2 + 1);
            ulong id    = leaf.Id.Id & ulong.MaxValue << shift;

            id |= 0 | ((ulong)1 << shift);

            return(new S2Cell(new S2CellId(id)));
        }
Exemple #17
0
        public static ulong GetPokeCell(ICoordinate poke)
        {
            var latLng = S2LatLng.FromDegrees((double)poke.Latitude, (double)poke.Longitude);
            var hash   = S2CellId.FromLatLng(latLng).ParentForLevel(20).Id;

            return(hash);
        }
Exemple #18
0
    // This function assumes that GetDirectedHausdorffDistance() always returns
    // a distance from some point in a to b. So the function mainly tests whether
    // the returned distance is large enough, and only does a weak test on whether
    // it is small enough.
    private static void VerifyGetDirectedHausdorffDistance(S2LatLngRect a, S2LatLngRect b)
    {
        S1Angle hausdorff_distance = a.GetDirectedHausdorffDistance(b);

        const double kResolution  = 0.1;
        S1Angle      max_distance = S1Angle.Zero;

        int sample_size_on_lat =
            (int)(a.Lat.GetLength() / kResolution) + 1;
        int sample_size_on_lng =
            (int)(a.Lng.GetLength() / kResolution) + 1;
        double delta_on_lat = a.Lat.GetLength() / sample_size_on_lat;
        double delta_on_lng = a.Lng.GetLength() / sample_size_on_lng;

        double lng = a.Lng.Lo;

        for (int i = 0; i <= sample_size_on_lng; ++i, lng += delta_on_lng)
        {
            double lat = a.Lat.Lo;
            for (int j = 0; j <= sample_size_on_lat; ++j, lat += delta_on_lat)
            {
                S2LatLng latlng        = S2LatLng.FromRadians(lat, lng).Normalized();
                S1Angle  distance_to_b = b.GetDistance(latlng);

                if (distance_to_b >= max_distance)
                {
                    max_distance = distance_to_b;
                }
            }
        }

        Assert.True(max_distance.Radians <= hausdorff_distance.Radians + 1e-10);
        Assert.True(max_distance.Radians >= hausdorff_distance.Radians - kResolution);
    }
Exemple #19
0
    public void Test_S2LatLngRect_GetVertex()
    {
        S2LatLngRect r1 = new(new R1Interval(0, S2.M_PI_2), new S1Interval(-Math.PI, 0));

        Assert.Equal(r1.Vertex(0), S2LatLng.FromRadians(0, Math.PI));
        Assert.Equal(r1.Vertex(1), S2LatLng.FromRadians(0, 0));
        Assert.Equal(r1.Vertex(2), S2LatLng.FromRadians(S2.M_PI_2, 0));
        Assert.Equal(r1.Vertex(3), S2LatLng.FromRadians(S2.M_PI_2, Math.PI));

        // Make sure that GetVertex() returns vertices in CCW order.
        for (int i = 0; i < 4; ++i)
        {
            double       lat = S2.M_PI_4 * (i - 2);
            double       lng = S2.M_PI_2 * (i - 2) + 0.2;
            S2LatLngRect r   = new(
                new R1Interval(lat, lat + S2.M_PI_4),
                new S1Interval(
                    Math.IEEERemainder(lng, S2.M_2_PI),
                    Math.IEEERemainder(lng + S2.M_PI_2, S2.M_2_PI)));
            for (int k = 0; k < 4; ++k)
            {
                Assert.True(S2Pred.Sign(
                                r.Vertex(k - 1).ToPoint(),
                                r.Vertex(k).ToPoint(),
                                r.Vertex(k + 1).ToPoint()) > 0);
            }
        }
    }
        public void testGetClosestPoint()
        {
            var kMargin = 1e-6;

            var a = S2LatLng.FromDegrees(-0.5, 0).ToPoint();
            var b = S2LatLng.FromDegrees(+0.5, 0).ToPoint();

            // On edge at end points.
            assertEquals(a, S2EdgeUtil.GetClosestPoint(a, a, b));
            assertEquals(b, S2EdgeUtil.GetClosestPoint(b, a, b));

            // On edge in between.
            var mid = S2LatLng.FromDegrees(0, 0).ToPoint();

            assertEquals(mid, S2EdgeUtil.GetClosestPoint(mid, a, b));

            // End points are closest
            assertEquals(a, S2EdgeUtil.GetClosestPoint(S2LatLng.FromDegrees(-1, 0).ToPoint(), a, b));
            assertEquals(b, S2EdgeUtil.GetClosestPoint(S2LatLng.FromDegrees(+1, 0).ToPoint(), a, b));

            // Intermediate point is closest.
            var x = S2LatLng.FromDegrees(+0.1, 1).ToPoint();
            var expectedClosestPoint = S2LatLng.FromDegrees(+0.1, 0).ToPoint();

            assertTrue(expectedClosestPoint.ApproxEquals(S2EdgeUtil.GetClosestPoint(x, a, b), kMargin));
        }
        public void testIntervalOps(S2LatLngRect x, S2LatLngRect y, String expectedRelation,
                                    S2LatLngRect expectedUnion, S2LatLngRect expectedIntersection)
        {
            // Test all of the interval operations on the given pair of intervals.
            // "expected_relation" is a sequence of "T" and "F" characters corresponding
            // to the expected results of Contains(), InteriorContains(), Intersects(),
            // and InteriorIntersects() respectively.

            assertEquals(x.Contains(y), expectedRelation[0] == 'T');
            assertEquals(x.InteriorContains(y), expectedRelation[1] == 'T');
            assertEquals(x.Intersects(y), expectedRelation[2] == 'T');
            assertEquals(x.InteriorIntersects(y), expectedRelation[3] == 'T');

            assertEquals(x.Contains(y), x.Union(y).Equals(x));
            assertEquals(x.Intersects(y), !x.Intersection(y).IsEmpty);

            assertTrue(x.Union(y).Equals(expectedUnion));
            assertTrue(x.Intersection(y).Equals(expectedIntersection));

            if (y.Size == S2LatLng.FromRadians(0, 0))
            {
                var r = x.AddPoint(y.Lo);
                assertTrue(r == expectedUnion);
            }
        }
Exemple #22
0
        public List <Guid> Search(double lon, double lat, int radius)
        {
            var latlng = S2LatLng.FromDegrees(lat, lon);

            var centerPoint = pointFromLatLng(lat, lon);

            var centerAngle = ((double)radius) / EarthRadiusM;

            var cap = S2Cap.FromAxisAngle(centerPoint, S1Angle.FromRadians(centerAngle));

            var regionCoverer = new S2RegionCoverer();

            regionCoverer.MaxLevel = 13;

            //  regionCoverer.MinLevel = 13;


            //regionCoverer.MaxCells = 1000;
            // regionCoverer.LevelMod = 0;


            var covering = regionCoverer.GetCovering(cap);



            var res = new List <Guid>();


            foreach (var u in covering)
            {
                var sell = new S2CellId(u.Id);

                if (sell.Level < _level)
                {
                    var begin = sell.ChildBeginForLevel(_level);
                    var end   = sell.ChildEndForLevel(_level);
                    do
                    {
                        var cur = tree.Search(new S2CellId(begin.Id));

                        if (cur != null)
                        {
                            res.AddRange(cur.Pointer);
                        }

                        begin = begin.Next;
                    } while (begin.Id != end.Id);
                }
                else
                {
                    var item = tree.Search(sell);
                    if (item != null)
                    {
                        res.AddRange(item.Pointer);
                    }
                }
            }
            return(res);
        }
        private void assertPointApproximatelyEquals(
            S2Loop s2Loop, int vertexIndex, double lat, double lng, double error)
        {
            var latLng = new S2LatLng(s2Loop.Vertex(vertexIndex));

            assertDoubleNear(latLng.LatDegrees, lat, error);
            assertDoubleNear(latLng.LngDegrees, lng, error);
        }
Exemple #24
0
        public static ulong GenerateGeohash(GeoPoint geoPoint)
        {
            var latLng = S2LatLng.FromDegrees(geoPoint.lat, geoPoint.lng);
            var cell   = new S2Cell(latLng);
            var cellId = cell.Id;

            return(cellId.Id);
        }
        public static ulong GenerateGeohash(double latitude, double longitude)
        {
            var latLng = S2LatLng.FromDegrees(latitude, longitude);
            var cell   = new S2Cell(latLng);
            var cellId = cell.Id;

            return(cellId.Id);
        }
Exemple #26
0
        public List <Guid> Search(double lon, double lat, int radius)
        {
            var latlng = S2LatLng.FromDegrees(lat, lon);

            var centerPoint = Index.pointFromLatLng(lat, lon);

            var centerAngle = ((double)radius) / Index.EarthRadiusM;

            var cap = S2Cap.FromAxisAngle(centerPoint, S1Angle.FromRadians(centerAngle));

            var regionCoverer = new S2RegionCoverer();

            regionCoverer.MaxLevel = 13;

            //  regionCoverer.MinLevel = 13;


            //regionCoverer.MaxCells = 1000;
            // regionCoverer.LevelMod = 0;


            var covering = regionCoverer.GetCovering(cap);



            var res = new List <Guid>();


            foreach (var u in covering)
            {
                var sell = new S2CellId(u.Id);

                if (sell.Level < _level)
                {
                    var begin = sell.ChildBeginForLevel(_level);
                    var end   = sell.ChildEndForLevel(_level);

                    var qres = rtree.Query(new Range <S2CellId>(begin, end));

                    foreach (var r in qres)
                    {
                        res.AddRange(r.Content);
                    }
                }
                else
                {
                    var qres = rtree.Query(new Range <S2CellId>(sell));
                    if (qres.Count > 0)
                    {
                        foreach (var r in qres)
                        {
                            res.AddRange(r.Content);
                        }
                    }
                }
            }
            return(res);
        }
Exemple #27
0
    private static S2LatLngRect RectFromDegrees(double lat_lo, double lng_lo, double lat_hi, double lng_hi)
    {
        // Convenience method to construct a rectangle.  This method is
        // intentionally *not* in the S2LatLngRect interface because the
        // argument order is ambiguous, but hopefully it's not too confusing
        // within the context of this unit test.

        return(new S2LatLngRect(S2LatLng.FromDegrees(lat_lo, lng_lo).Normalized(), S2LatLng.FromDegrees(lat_hi, lng_hi).Normalized()));
    }
Exemple #28
0
    public override S2LatLng ToLatLng(R2Point p)
    {
        // This formula is more accurate near zero than the atan(exp()) version.
        double x = to_radians_ * Math.IEEERemainder(p.X, x_wrap_);
        double k = Math.Exp(2 * to_radians_ * p.Y);
        double y = double.IsInfinity(k) ? S2.M_PI_2 : Math.Asin((k - 1) / (k + 1));

        return(S2LatLng.FromRadians(y, x));
    }
Exemple #29
0
 public void Test_E6()
 {
     for (var i = 0; i < kIters; i++)
     {
         var ll    = S2LatLng.FromPoint(S2Testing.RandomPoint());
         var ll_e6 = S2LatLng.FromE6(ll.Lat().E6(), ll.Lng().E6());
         ExpectMaxDigits(ll_e6, 6);
     }
 }
Exemple #30
0
    public override R2Point FromLatLng(S2LatLng ll)
    {
        // This formula is more accurate near zero than the log(tan()) version.
        // Note that latitudes of +/- 90 degrees yield "y" values of +/- infinity.
        double sin_phi = Math.Sin(ll.LatRadians);
        double y       = 0.5 * Math.Log((1 + sin_phi) / (1 - sin_phi));

        return(new R2Point(from_radians_ * ll.LngRadians, from_radians_ * y));
    }
        public static void DrawS2Cells(List<ulong> cellsIds, GMapOverlay mapLayer)
        {
            for (int i=0; i<cellsIds.Count; i++)
            {
                S2CellId cellId = new S2CellId(cellsIds[i]);
                S2Cell cell = new S2Cell(cellId);

                List<PointLatLng> points = new List<PointLatLng>();
                for (int j=0; j<4; j++)
                {
                    S2LatLng point = new S2LatLng(cell.GetVertex(j));
                    points.Add(new PointLatLng(point.LatDegrees, point.LngDegrees));
                }
                GMapPolygon polygon = new GMapPolygon(points, "mypolygon");
                polygon.Fill = new SolidBrush(Color.FromArgb(50, Color.Red));
                polygon.Stroke = new Pen(Color.Red, 1);
                mapLayer.Polygons.Add(polygon);
            }
        }
        public void AddPoint(S2Point b)
        {
            // assert (S2.isUnitLength(b));

            var bLatLng = new S2LatLng(b);

            if (bound.IsEmpty)
            {
                bound = bound.AddPoint(bLatLng);
            }
            else
            {
                // We can't just call bound.addPoint(bLatLng) here, since we need to
                // ensure that all the longitudes between "a" and "b" are included.
                bound = bound.Union(S2LatLngRect.FromPointPair(aLatLng, bLatLng));

                // Check whether the Min/Max latitude occurs in the edge interior.
                // We find the normal to the plane containing AB, and then a vector
                // "dir" in this plane that also passes through the equator. We use
                // RobustCrossProd to ensure that the edge normal is accurate even
                // when the two points are very close together.
                var aCrossB = S2.RobustCrossProd(a, b);
                var dir = S2Point.CrossProd(aCrossB, new S2Point(0, 0, 1));
                var da = dir.DotProd(a);
                var db = dir.DotProd(b);

                if (da*db < 0)
                {
                    // Minimum/maximum latitude occurs in the edge interior. This affects
                    // the latitude bounds but not the longitude bounds.
                    var absLat = Math.Acos(Math.Abs(aCrossB[2]/aCrossB.Norm));
                    var lat = bound.Lat;
                    if (da < 0)
                    {
                        // It's possible that absLat < lat.lo() due to numerical errors.
                        lat = new R1Interval(lat.Lo, Math.Max(absLat, bound.Lat.Hi));
                    }
                    else
                    {
                        lat = new R1Interval(Math.Min(-absLat, bound.Lat.Lo), lat.Hi);
                    }
                    bound = new S2LatLngRect(lat, bound.Lng);
                }
            }
            a = b;
            aLatLng = bLatLng;
        }
 private void assertPointApproximatelyEquals(
     S2Loop s2Loop, int vertexIndex, double lat, double lng, double error)
 {
     var latLng = new S2LatLng(s2Loop.Vertex(vertexIndex));
     assertDoubleNear(latLng.LatDegrees, lat, error);
     assertDoubleNear(latLng.LngDegrees, lng, error);
 }
        private static S1Angle bruteForceRectPointDistance(S2LatLngRect a, S2LatLng b)
        {
            if (a.Contains(b))
            {
                return S1Angle.FromRadians(0);
            }

            var bToLoLat = getDistance(b, a.LatLo, a.Lng);
            var bToHiLat = getDistance(b, a.LatHi, a.Lng);
            var bToLoLng =
                S2EdgeUtil.GetDistance(b.ToPoint(), new S2LatLng(a.LatLo, a.LngLo).ToPoint(),
                                       new S2LatLng(a.LatHi, a.LngLo).ToPoint());
            var bToHiLng =
                S2EdgeUtil.GetDistance(b.ToPoint(), new S2LatLng(a.LatLo, a.LngHi).ToPoint(),
                                       new S2LatLng(a.LatHi, a.LngHi).ToPoint());
            return S1Angle.Min(bToLoLat, S1Angle.Min(bToHiLat, S1Angle.Min(bToLoLng, bToHiLng)));
        }
        public void testGetDistanceRandomPairs()
        {
            // Test random pairs.
            for (var i = 0; i < 10000; ++i)
            {
                var a =
                    S2LatLngRect.FromPointPair(new S2LatLng(randomPoint()), new S2LatLng(randomPoint()));
                var b =
                    S2LatLngRect.FromPointPair(new S2LatLng(randomPoint()), new S2LatLng(randomPoint()));
                verifyGetDistance(a, b);


                var c = new S2LatLng(randomPoint());
                verifyGetRectPointDistance(a, c);
                verifyGetRectPointDistance(b, c);
            }
        }
        public void testBasic()
        {
            // Most of the S2LatLngRect methods have trivial implementations that
            // use the R1Interval and S1Interval classes, so most of the testing
            // is done in those unit tests.

            // Test basic properties of empty and full caps.
            var empty = S2LatLngRect.Empty;
            var full = S2LatLngRect.Full;
            assertTrue(empty.IsValid);
            assertTrue(empty.IsEmpty);
            assertTrue(full.IsValid);
            assertTrue(full.IsFull);

            // assertTrue various constructors and accessor methods.
            var d1 = rectFromDegrees(-90, 0, -45, 180);
            assertDoubleNear(d1.LatLo.Degrees, -90);
            assertDoubleNear(d1.LatHi.Degrees, -45);
            assertDoubleNear(d1.LngLo.Degrees, 0);
            assertDoubleNear(d1.LngHi.Degrees, 180);
            assertTrue(d1.Lat.Equals(new R1Interval(-S2.PiOver2, -S2.PiOver4)));
            assertTrue(d1.Lng.Equals(new S1Interval(0, S2.Pi)));

            // FromCenterSize()
            assertTrue(
                S2LatLngRect.FromCenterSize(S2LatLng.FromDegrees(80, 170), S2LatLng.FromDegrees(40, 60))
                            .ApproxEquals(rectFromDegrees(60, 140, 90, -160)));
            assertTrue(S2LatLngRect
                           .FromCenterSize(S2LatLng.FromDegrees(10, 40), S2LatLng.FromDegrees(210, 400)).IsFull);
            assertTrue(
                S2LatLngRect.FromCenterSize(S2LatLng.FromDegrees(-90, 180), S2LatLng.FromDegrees(20, 50))
                            .ApproxEquals(rectFromDegrees(-90, 155, -80, -155)));

            // FromPoint(), FromPointPair()
            assertEquals(S2LatLngRect.FromPoint(d1.Lo), new S2LatLngRect(d1.Lo, d1.Lo));
            assertEquals(
                S2LatLngRect.FromPointPair(S2LatLng.FromDegrees(-35, -140), S2LatLng.FromDegrees(15, 155)),
                rectFromDegrees(-35, 155, 15, -140));
            assertEquals(
                S2LatLngRect.FromPointPair(S2LatLng.FromDegrees(25, -70), S2LatLng.FromDegrees(-90, 80)),
                rectFromDegrees(-90, -70, 25, 80));

            // GetCenter(), GetVertex(), Contains(S2LatLng), InteriorContains(S2LatLng).
            var eqM180 = S2LatLng.FromRadians(0, -S2.Pi);
            var northPole = S2LatLng.FromRadians(S2.PiOver2, 0);
            var r1 = new S2LatLngRect(eqM180, northPole);

            assertEquals(r1.Center, S2LatLng.FromRadians(S2.PiOver4, -S2.PiOver2));
            assertEquals(r1.GetVertex(0), S2LatLng.FromRadians(0, S2.Pi));
            assertEquals(r1.GetVertex(1), S2LatLng.FromRadians(0, 0));
            assertEquals(r1.GetVertex(2), S2LatLng.FromRadians(S2.PiOver2, 0));
            assertEquals(r1.GetVertex(3), S2LatLng.FromRadians(S2.PiOver2, S2.Pi));
            assertTrue(r1.Contains(S2LatLng.FromDegrees(30, -45)));
            assertTrue(!r1.Contains(S2LatLng.FromDegrees(30, 45)));
            assertTrue(!r1.InteriorContains(eqM180) && !r1.InteriorContains(northPole));
            assertTrue(r1.Contains(new S2Point(0.5, -0.3, 0.1)));
            assertTrue(!r1.Contains(new S2Point(0.5, 0.2, 0.1)));

            // Make sure that GetVertex() returns vertices in CCW order.
            for (var i = 0; i < 4; ++i)
            {
                var lat = S2.PiOver4*(i - 2);
                var lng = S2.PiOver2*(i - 2) + 0.2;
                var r = new S2LatLngRect(new R1Interval(lat, lat + S2.PiOver4), new S1Interval(
                                                                                   Math.IEEERemainder(lng, 2*S2.Pi), Math.IEEERemainder(lng + S2.PiOver2, 2*S2.Pi)));
                for (var k = 0; k < 4; ++k)
                {
                    assertTrue(
                        S2.SimpleCcw(r.GetVertex((k - 1) & 3).ToPoint(), r.GetVertex(k).ToPoint(),
                                     r.GetVertex((k + 1) & 3).ToPoint()));
                }
            }

            // Contains(S2LatLngRect), InteriorContains(S2LatLngRect),
            // Intersects(), InteriorIntersects(), Union(), Intersection().
            //
            // Much more testing of these methods is done in s1interval_unittest
            // and r1interval_unittest.

            var r1Mid = rectFromDegrees(45, -90, 45, -90);
            var reqM180 = new S2LatLngRect(eqM180, eqM180);
            var rNorthPole = new S2LatLngRect(northPole, northPole);

            testIntervalOps(r1, r1Mid, "TTTT", r1, r1Mid);
            testIntervalOps(r1, reqM180, "TFTF", r1, reqM180);
            testIntervalOps(r1, rNorthPole, "TFTF", r1, rNorthPole);

            assertTrue(r1.Equals(rectFromDegrees(0, -180, 90, 0)));
            testIntervalOps(r1, rectFromDegrees(-10, -1, 1, 20), "FFTT", rectFromDegrees(-10, -180, 90, 20),
                            rectFromDegrees(0, -1, 1, 0));
            testIntervalOps(r1, rectFromDegrees(-10, -1, 0, 20), "FFTF", rectFromDegrees(-10, -180, 90, 20),
                            rectFromDegrees(0, -1, 0, 0));
            testIntervalOps(r1, rectFromDegrees(-10, 0, 1, 20), "FFTF", rectFromDegrees(-10, -180, 90, 20),
                            rectFromDegrees(0, 0, 1, 0));

            testIntervalOps(rectFromDegrees(-15, -160, -15, -150), rectFromDegrees(20, 145, 25, 155),
                            "FFFF", rectFromDegrees(-15, 145, 25, -150), empty);
            testIntervalOps(rectFromDegrees(70, -10, 90, -140), rectFromDegrees(60, 175, 80, 5), "FFTT",
                            rectFromDegrees(60, -180, 90, 180), rectFromDegrees(70, 175, 80, 5));

            // assertTrue that the intersection of two rectangles that overlap in
            // latitude
            // but not longitude is valid, and vice versa.
            testIntervalOps(rectFromDegrees(12, 30, 60, 60), rectFromDegrees(0, 0, 30, 18), "FFFF",
                            rectFromDegrees(0, 0, 60, 60), empty);
            testIntervalOps(rectFromDegrees(0, 0, 18, 42), rectFromDegrees(30, 12, 42, 60), "FFFF",
                            rectFromDegrees(0, 0, 42, 60), empty);

            // AddPoint()
            var p = S2LatLngRect.Empty;
            p = p.AddPoint(S2LatLng.FromDegrees(0, 0));
            p = p.AddPoint(S2LatLng.FromRadians(0, -S2.PiOver2));
            p = p.AddPoint(S2LatLng.FromRadians(S2.PiOver4, -S2.Pi));
            p = p.AddPoint(new S2Point(0, 0, 1));
            assertTrue(p.Equals(r1));

            // Expanded()
            assertTrue(
                rectFromDegrees(70, 150, 80, 170).Expanded(S2LatLng.FromDegrees(20, 30)).ApproxEquals(
                    rectFromDegrees(50, 120, 90, -160)));
            assertTrue(S2LatLngRect.Empty.Expanded(S2LatLng.FromDegrees(20, 30)).IsEmpty);
            assertTrue(S2LatLngRect.Full.Expanded(S2LatLng.FromDegrees(20, 30)).IsFull);
            assertTrue(
                rectFromDegrees(-90, 170, 10, 20).Expanded(S2LatLng.FromDegrees(30, 80)).ApproxEquals(
                    rectFromDegrees(-90, -180, 40, 180)));

            // ConvolveWithCap()
            var llr1 =
                new S2LatLngRect(S2LatLng.FromDegrees(0, 170), S2LatLng.FromDegrees(0, -170))
                    .ConvolveWithCap(S1Angle.FromDegrees(15));
            var llr2 =
                new S2LatLngRect(S2LatLng.FromDegrees(-15, 155), S2LatLng.FromDegrees(15, -155));
            assertTrue(llr1.ApproxEquals(llr2));

            llr1 = new S2LatLngRect(S2LatLng.FromDegrees(60, 150), S2LatLng.FromDegrees(80, 10))
                .ConvolveWithCap(S1Angle.FromDegrees(15));
            llr2 = new S2LatLngRect(S2LatLng.FromDegrees(45, -180), S2LatLng.FromDegrees(90, 180));
            assertTrue(llr1.ApproxEquals(llr2));

            // GetCapBound(), bounding cap at center is smaller:
            assertTrue(new S2LatLngRect(S2LatLng.FromDegrees(-45, -45), S2LatLng.FromDegrees(45, 45)).CapBound.ApproxEquals(S2Cap.FromAxisHeight(new S2Point(1, 0, 0), 0.5)));
            // GetCapBound(), bounding cap at north pole is smaller:
            assertTrue(new S2LatLngRect(S2LatLng.FromDegrees(88, -80), S2LatLng.FromDegrees(89, 80)).CapBound.ApproxEquals(S2Cap.FromAxisAngle(new S2Point(0, 0, 1), S1Angle.FromDegrees(2))));
            // GetCapBound(), longitude span > 180 degrees:
            assertTrue(
                new S2LatLngRect(S2LatLng.FromDegrees(-30, -150), S2LatLng.FromDegrees(-10, 50)).CapBound
                    .ApproxEquals(S2Cap.FromAxisAngle(new S2Point(0, 0, -1), S1Angle.FromDegrees(80))));

            // Contains(S2Cell), MayIntersect(S2Cell), Intersects(S2Cell)

            // Special cases.
            testCellOps(empty, S2Cell.FromFacePosLevel(3, (byte)0, 0), 0);
            testCellOps(full, S2Cell.FromFacePosLevel(2, (byte)0, 0), 4);
            testCellOps(full, S2Cell.FromFacePosLevel(5, (byte)0, 25), 4);

            // This rectangle includes the first quadrant of face 0. It's expanded
            // slightly because cell bounding rectangles are slightly conservative.
            var r4 = rectFromDegrees(-45.1, -45.1, 0.1, 0.1);
            testCellOps(r4, S2Cell.FromFacePosLevel(0, (byte)0, 0), 3);
            testCellOps(r4, S2Cell.FromFacePosLevel(0, (byte)0, 1), 4);
            testCellOps(r4, S2Cell.FromFacePosLevel(1, (byte)0, 1), 0);

            // This rectangle intersects the first quadrant of face 0.
            var r5 = rectFromDegrees(-10, -45, 10, 0);
            testCellOps(r5, S2Cell.FromFacePosLevel(0, (byte)0, 0), 3);
            testCellOps(r5, S2Cell.FromFacePosLevel(0, (byte)0, 1), 3);
            testCellOps(r5, S2Cell.FromFacePosLevel(1, (byte)0, 1), 0);

            // Rectangle consisting of a single point.
            testCellOps(rectFromDegrees(4, 4, 4, 4), S2Cell.FromFacePosLevel(0, (byte)0, 0), 3);

            // Rectangles that intersect the bounding rectangle of a face
            // but not the face itself.
            testCellOps(rectFromDegrees(41, -87, 42, -79), S2Cell.FromFacePosLevel(2, (byte)0, 0), 1);
            testCellOps(rectFromDegrees(-41, 160, -40, -160), S2Cell.FromFacePosLevel(5, (byte)0, 0), 1);
            {
                // This is the leaf cell at the top right hand corner of face 0.
                // It has two angles of 60 degrees and two of 120 degrees.
                var cell0tr = new S2Cell(new S2Point(1 + 1e-12, 1, 1));
                var bound0tr = cell0tr.RectBound;
                var v0 = new S2LatLng(cell0tr.GetVertexRaw(0));
                testCellOps(
                    rectFromDegrees(v0.Lat.Degrees - 1e-8, v0.Lng.Degrees - 1e-8,
                                    v0.Lat.Degrees - 2e-10, v0.Lng.Degrees + 1e-10), cell0tr, 1);
            }

            // Rectangles that intersect a face but where no vertex of one region
            // is contained by the other region. The first one passes through
            // a corner of one of the face cells.
            testCellOps(rectFromDegrees(-37, -70, -36, -20), S2Cell.FromFacePosLevel(5, (byte)0, 0), 2);
            {
                // These two intersect like a diamond and a square.
                var cell202 = S2Cell.FromFacePosLevel(2, (byte)0, 2);
                var bound202 = cell202.RectBound;
                testCellOps(
                    rectFromDegrees(bound202.Lo.Lat.Degrees + 3, bound202.Lo.Lng.Degrees + 3,
                                    bound202.Hi.Lat.Degrees - 3, bound202.Hi.Lng.Degrees - 3), cell202, 2);
            }
        }
        /**
         * This method verifies a.getDistance(b), where b is a S2LatLng, by comparing
         * its result against a.getDistance(c), c being the point rectangle created
         * from b.
         */

        private static void verifyGetRectPointDistance(S2LatLngRect a, S2LatLng p)
        {
            var distance1 = bruteForceRectPointDistance(a, p.Normalized);
            var distance2 = a.GetDistance(p.Normalized);
            assertEquals(distance1.Radians, distance2.Radians, 1e-10);
        }
        /**
         * Returns the minimum distance from X to the latitude line segment defined by
         * the given latitude and longitude interval.
         */

        private static S1Angle getDistance(S2LatLng x, S1Angle lat, S1Interval interval)
        {
            assertTrue(x.IsValid);
            assertTrue(interval.IsValid);

            // Is X inside the longitude interval?
            if (interval.Contains(x.Lng.Radians))
                return S1Angle.FromRadians(Math.Abs(x.Lat.Radians - lat.Radians));

            // Return the distance to the closer endpoint.
            return S1Angle.Min(x.GetDistance(new S2LatLng(lat, S1Angle.FromRadians(interval.Lo))),
                               x.GetDistance(new S2LatLng(lat, S1Angle.FromRadians(interval.Hi))));
        }