public List <WebGridCellFeatureStatistics> GetGridFeatureStatistics(WebClientInformation clientInformation,
                                                                     WebFeatureStatisticsSpecification featureStatisticsSpecification,
                                                                     String featuresUrl,
                                                                     String featureCollectionJson,
                                                                     WebGridSpecification gridSpecification,
                                                                     WebCoordinateSystem coordinateSystem)
 {
     using (WebServiceContext context = GetWebServiceContext(clientInformation))
     {
         try
         {
             var featuresUri = string.IsNullOrEmpty(featuresUrl) ? null : new Uri(featuresUrl);
             return(AnalysisManager.GetGridCellFeatureStatistics(context,
                                                                 featuresUri,
                                                                 featureCollectionJson,
                                                                 gridSpecification,
                                                                 coordinateSystem));
         }
         catch (Exception exception)
         {
             WebServiceData.LogManager.LogError(context, exception);
             throw;
         }
     }
 }
        /// <summary>
        /// This method get species (Taxa of category species) and observations per grid cell that matches
        /// species observation search criteria, grid cell specifications and specified coordinate
        /// system to getting results in.
        /// </summary>
        /// <param name="clientInformation">Information about the client that makes this web service call.</param>
        /// <param name="searchCriteria">Species observation search criteria - defined in class WebSpeciesObservationSearchCriteria.</param>
        /// <param name="gridSpecification">Grid specifications i.e settings for result grid. These settings are defined in class
        /// WebGridSpecifications. Note! GridCellSize and GridCoordinateSystem classes are the
        /// only properties that is used in this method. If Bounding Box is set then WebSpeciesObservationSearchCriteria property
        /// BoundingBox is override with WebGridSpecifications property BoundingBox.</param>
        /// <param name="coordinateSystem">Coordinate systen whch is used for performing grid caluculations defined in
        /// WebCoordinateSystem</param>
        /// <returns> A list of grid cells is returned that matches. Grid cell results is presented in WebGridCellSpeciesCount class showing number of species, no of observations.</returns>
        public List <WebGridCellSpeciesCount> GetGridSpeciesCountsBySpeciesObservationSearchCriteria(
            WebClientInformation clientInformation,
            WebSpeciesObservationSearchCriteria searchCriteria,
            WebGridSpecification gridSpecification,
            WebCoordinateSystem coordinateSystem)
        {
            List <WebGridCellSpeciesCount> grid;

            using (WebServiceContext context = GetWebServiceContext(clientInformation))
            {
                try
                {
                    if (SpeciesObservationConfiguration.IsElasticsearchUsed)
                    {
                        grid = AnalysisManager.GetGridSpeciesCountsElasticsearch(context, searchCriteria, gridSpecification, coordinateSystem);
                    }
                    else
                    {
                        grid = AnalysisManager.GetGridSpeciesCounts(context, searchCriteria, gridSpecification, coordinateSystem);
                    }

                    LogSpeciesObservationCount(grid);
                    return(grid);
                }
                catch (Exception exception)
                {
                    WebServiceData.LogManager.LogError(context, exception);
                    throw;
                }
            }
        }
        public void GetGridCellSpeciesCountsTest()
        {
            WebCoordinateSystem coordinateSystem;

            coordinateSystem    = new WebCoordinateSystem();
            coordinateSystem.Id = CoordinateSystemId.GoogleMercator;

            WebSpeciesObservationSearchCriteria searchCriteria = new WebSpeciesObservationSearchCriteria();

            SetDefaultSearchCriteria(searchCriteria);
            searchCriteria.TaxonIds.Add(Convert.ToInt32(TaxonId.Grasshoppers));
            WebGridSpecification webGridSpecification = new WebGridSpecification();

            webGridSpecification.GridCoordinateSystem    = GridCoordinateSystem.Rt90_25_gon_v;
            webGridSpecification.GridCellSize            = 5000;
            webGridSpecification.IsGridCellSizeSpecified = true;
            webGridSpecification.GridCellGeometryType    = GridCellGeometryType.Polygon;

            IList <WebGridCellSpeciesCount> noOfGridCellObservations = WebServiceProxy.AnalysisService.GetGridSpeciesCounts(GetClientInformation(), searchCriteria, webGridSpecification, coordinateSystem);

            Assert.IsTrue(noOfGridCellObservations.Count > 0);
            Assert.IsTrue(noOfGridCellObservations[0].CentreCoordinate.X.IsNotNull());
            Assert.IsTrue(noOfGridCellObservations[0].CentreCoordinate.Y.IsNotNull());
            Assert.IsTrue(noOfGridCellObservations[0].Size == 5000);
            //Assert.IsTrue(noOfGridCellObservations[0].GridCoordinateSystem.ToString().Equals(GridCoordinateSystem.RT90.ToString()));
            Assert.IsTrue(noOfGridCellObservations[0].GridCoordinateSystem.ToString().Equals(GridCoordinateSystem.Rt90_25_gon_v.ToString()));
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[0].X.IsNotNull());
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[2].X.IsNotNull());
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[0].Y.IsNotNull());
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[2].Y.IsNotNull());
            Assert.IsTrue(noOfGridCellObservations[0].SpeciesObservationCount > 0);
            Assert.IsTrue(noOfGridCellObservations[0].SpeciesCount > 0);
            Assert.IsTrue(noOfGridCellObservations[0].SpeciesObservationCount >= noOfGridCellObservations[0].SpeciesCount);
        }
        public void GetGridCellSpeciesObservationCountsTest()
        {
            WebCoordinateSystem coordinateSystem;

            coordinateSystem    = new WebCoordinateSystem();
            coordinateSystem.Id = CoordinateSystemId.GoogleMercator;

            WebSpeciesObservationSearchCriteria searchCriteria = new WebSpeciesObservationSearchCriteria();

            SetDefaultSearchCriteria(searchCriteria);
            WebGridSpecification webGridSpecification = new WebGridSpecification();

            //IGridSpecification.GridCoordinateSystem = GridCoordinateSystem.RT90;
            webGridSpecification.GridCoordinateSystem    = GridCoordinateSystem.SWEREF99_TM;
            webGridSpecification.GridCellSize            = 5000;
            webGridSpecification.IsGridCellSizeSpecified = true;
            webGridSpecification.GridCellGeometryType    = GridCellGeometryType.Polygon;

            IList <WebGridCellSpeciesObservationCount> noOfGridCellObservations = WebServiceProxy.AnalysisService.GetGridSpeciesObservationCounts(GetClientInformation(), searchCriteria, webGridSpecification, coordinateSystem);

            Assert.IsTrue(noOfGridCellObservations.Count > 0);
            Assert.IsTrue(noOfGridCellObservations[0].CentreCoordinate.X > 0);
            Assert.IsTrue(noOfGridCellObservations[0].CentreCoordinate.Y > 0);
            Assert.IsTrue(noOfGridCellObservations[0].Size == 5000);
            //Assert.IsTrue(noOfGridCellObservations[0].GridCoordinateSystem.ToString().Equals(GridCoordinateSystem.RT90.ToString()));
            //Assert.IsTrue(noOfGridCellObservations[0].GridCoordinateSystem.ToString().Equals(GridCoordinateSystem.SWEREF99_TM.ToString()));
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[0].X > 0);
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[2].X > 0);
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[0].Y > 0);
            Assert.IsTrue(noOfGridCellObservations[0].BoundingBox.LinearRings[0].Points[2].Y > 0);
        }
        public List <DocumentUniqueValue> GetGridSpeciesCounts(string filter, WebGridSpecification gridSpecification)
        {
            string script;

            switch (gridSpecification.GridCoordinateSystem)
            {
            case GridCoordinateSystem.Rt90_25_gon_v:
                script = string.Format("(floor(doc['Location_{0}'].value / {1}) * {1} + {1} / 2).toString() + ':' + (floor(doc['Location_{2}'].value / {1}) * {1} + {1} / 2).toString()", Settings.Default.CoordinateXRt90FieldName, gridSpecification.GridCellSize, Settings.Default.CoordinateYRt90FieldName);
                break;

            case GridCoordinateSystem.SWEREF99_TM:
                script = string.Format("(floor(doc['Location_{0}'].value / {1}) * {1} + {1} / 2).toString() + ':' + (floor(doc['Location_{2}'].value / {1}) * {1} + {1} / 2).toString()", Settings.Default.CoordinateXSweref99FieldName, gridSpecification.GridCellSize, Settings.Default.CoordinateYSweref99FieldName);
                break;

            default:
                throw new NotImplementedException(string.Format("Coordinate system not supported in grid query [{0}]", gridSpecification.GridCoordinateSystem));
            }

            return(GroupByCountAndSum(SpeciesObservationType, new List <ElasticsearchTerm> {
                new ElasticsearchTerm(script)
                {
                    TermType = ElasticsearchTermType.Script
                }, new ElasticsearchTerm("Taxon_Species_TaxonId")
            }, null, filter).UniqueValues);
        }
        /// <summary>
        /// Load data into the WebGridCellSpeciesCount instance.
        /// </summary>
        /// <param name="gridCellObservationCount"> Information on species counts.</param>
        /// <param name="uniqueValue">A KeyValuePair with coordinate and count information</param>
        /// <param name="gridSpecification">The grid specification: bounding box, grid cell size, etc.</param>
        /// <param name="coordinateSystem"></param>
        public static void LoadData(this WebGridCellSpeciesCount gridCellObservationCount,
                                    KeyValuePair <string, long> uniqueValue,
                                    WebGridSpecification gridSpecification,
                                    WebCoordinateSystem coordinateSystem)
        {
            if (gridCellObservationCount != null)
            {
                // Returning int 32, no problem for gridcells.
                gridCellObservationCount.SpeciesObservationCount = uniqueValue.Value;
                gridCellObservationCount.GridCoordinateSystem    = gridSpecification.GridCoordinateSystem;
                gridCellObservationCount.CoordinateSystem        = coordinateSystem;
                gridCellObservationCount.Size = gridSpecification.GridCellSize;

                // Calculate grid points
                double centreCoordinateX = uniqueValue.Key.Split(':')[0].WebParseDouble();
                double centreCoordinateY = uniqueValue.Key.Split(':')[1].WebParseDouble();
                //TODO Create method:
                double halfGridSize = gridCellObservationCount.Size / 2.0;

                double upperCoordinateY = centreCoordinateY + halfGridSize;
                double upperCoordinateX = centreCoordinateX + halfGridSize;
                double lowerCoordinateY = centreCoordinateY - halfGridSize;
                double lowerCoordinateX = centreCoordinateX - halfGridSize;

                // Create Point and BoundingBox
                WebPoint centrePoint = new WebPoint(centreCoordinateX, centreCoordinateY);

                WebPoint pointMax = new WebPoint(upperCoordinateX, upperCoordinateY);
                WebPoint pointMin = new WebPoint(lowerCoordinateX, lowerCoordinateY);

                gridCellObservationCount.CentreCoordinate        = centrePoint;
                gridCellObservationCount.OrginalCentreCoordinate = centrePoint;
                //gridCellObservationCount.GridCellBoundingBox = new WebBoundingBox() { Max = pointMax, Min = pointMin };
                gridCellObservationCount.BoundingBox             = new WebPolygon();
                gridCellObservationCount.BoundingBox.LinearRings = new List <WebLinearRing>();
                gridCellObservationCount.BoundingBox.LinearRings.Add(new WebLinearRing());
                gridCellObservationCount.BoundingBox.LinearRings[0].Points = new List <WebPoint>();
                gridCellObservationCount.BoundingBox.LinearRings[0].Points.Add(new WebPoint());
                gridCellObservationCount.BoundingBox.LinearRings[0].Points.Add(new WebPoint());
                gridCellObservationCount.BoundingBox.LinearRings[0].Points.Add(new WebPoint());
                gridCellObservationCount.BoundingBox.LinearRings[0].Points.Add(new WebPoint());
                gridCellObservationCount.BoundingBox.LinearRings[0].Points.Add(new WebPoint());
                //Create the linear ring that is the "bounding polygon".
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[0].X = pointMin.X;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[0].Y = pointMin.Y;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[1].X = pointMin.X;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[1].Y = pointMax.Y;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[2].X = pointMax.X;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[2].Y = pointMax.Y;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[3].X = pointMax.X;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[3].Y = pointMin.Y;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[4].X = pointMin.X;
                gridCellObservationCount.BoundingBox.LinearRings[0].Points[4].Y = pointMin.Y;

                gridCellObservationCount.OrginalBoundingBox = new WebBoundingBox {
                    Max = pointMax, Min = pointMin
                };
            }
        }
 /// <summary>
 /// Check if grid specifications is correct.
 /// </summary>
 /// <param name="gridSpecification"> Information on grid specifications.</param>
 /// <param name="speciesObservationBoundingBox">Bounding box for species observation.</param>
 public static void CheckGridSpecifications(this WebGridSpecification gridSpecification, WebBoundingBox speciesObservationBoundingBox)
 {
     if (gridSpecification.IsNotNull() && gridSpecification.BoundingBox.IsNotNull())
     {
         if (speciesObservationBoundingBox.IsNotNull())
         {
             throw new ArgumentException("WebGridSpecifications: Properties WebGridSpecifications.BoundingBox and WebSpeciesObservatioSearchCriteria.BoundingBox have value set, only one BoundigBox can be set.");
         }
     }
 }
 /// <summary>
 /// Load data into the WebGridCellSpeciesCount instance.
 /// </summary>
 /// <param name="gridCellObservationCount"> Information on species counts.</param>
 /// <param name="uniqueValue">A DocumentUniqueValue with coordinate, count and sum information</param>
 /// <param name="gridSpecification">The grid specification: bounding box, grid cell size, etc.</param>
 /// <param name="coordinateSystem"></param>
 public static void LoadData(this WebGridCellSpeciesCount gridCellObservationCount,
                             DocumentUniqueValue uniqueValue,
                             WebGridSpecification gridSpecification,
                             WebCoordinateSystem coordinateSystem)
 {
     if (gridCellObservationCount != null)
     {
         gridCellObservationCount.SpeciesCount = Convert.ToInt32(uniqueValue.Count);
         LoadData(gridCellObservationCount, new KeyValuePair <string, long>(uniqueValue.Key, uniqueValue.DocumentCount), gridSpecification, coordinateSystem);
     }
 }
 /// <summary>
 /// Gets no of species observations
 /// that matches the search criteria and grid specifications.
 /// </summary>
 /// <param name="clientInformation">Information about the client that makes this web service call.</param>
 /// <param name="searchCriteria">The species observation search criteria, GridCellSize and GridCoordinateSystem are the
 /// only properties that is used in this method.</param>
 /// <param name="gridSpecification">Search properties for grid search.</param>
 /// <param name="coordinateSystem">Coordinate system used in search criteria.</param>
 /// <returns>Information about changed species observations.</returns>
 public List <WebGridCellSpeciesCount> GetGridSpeciesCounts(WebClientInformation clientInformation,
                                                            WebSpeciesObservationSearchCriteria searchCriteria,
                                                            WebGridSpecification gridSpecification,
                                                            WebCoordinateSystem coordinateSystem)
 {
     using (ClientProxy client = new ClientProxy(this, 10))
     {
         return(client.Client.GetGridSpeciesCountsBySpeciesObservationSearchCriteria(clientInformation,
                                                                                     searchCriteria,
                                                                                     gridSpecification,
                                                                                     coordinateSystem));
     }
 }
        public void GetGridCellFeatureStatisticsWithCompleteUrlTestAndTransformCoordinates()
        {
            // Test accuracy
            String featuresUrl;
            WebCoordinateSystem coordinateSystem;
            WebFeatureStatisticsSpecification featureStatisticsSpecification;
            WebGridSpecification gridSpecification;

            gridSpecification = new WebGridSpecification();
            coordinateSystem  = new WebCoordinateSystem();
            featureStatisticsSpecification = new WebFeatureStatisticsSpecification();

            gridSpecification.BoundingBox     = new WebBoundingBox();
            gridSpecification.BoundingBox.Max = new WebPoint();
            gridSpecification.BoundingBox.Min = new WebPoint();

            gridSpecification.GridCellSize            = 1000;
            gridSpecification.GridCoordinateSystem    = GridCoordinateSystem.SWEREF99_TM;
            gridSpecification.IsGridCellSizeSpecified = true;
            gridSpecification.GridCellGeometryType    = GridCellGeometryType.Polygon;

            //Set returning coordinate system to something different to test the transformations
            coordinateSystem.Id = CoordinateSystemId.GoogleMercator;

            featuresUrl =
                "http://slwgeo.artdata.slu.se:8080/geoserver/wfs?&service=wfs&request=GetFeature&version=1.1.0&typeName=SLW:MapOfSwedishCounties&srsName=EPSG:3006";
            //&srs=3006";

            //IList<WebGridCellFeatureStatistics> gridCellFeatureStatistics =
            //                 AnalysisManager.GetGridCellFeatureStatistics(Context, featureStatistics, featuresUrl, //typeName,
            //                                                          gridSpecification, coordinateSystem //,isCompleteUrl
            //                                                          );

            IList <WebGridCellFeatureStatistics> gridCellFeatureStatistics =
                WebServiceProxy.AnalysisService.GetGridCellFeatureStatistics(GetClientInformation(),
                                                                             featureStatisticsSpecification,
                                                                             featuresUrl,
                                                                             null,
                                                                             gridSpecification,
                                                                             coordinateSystem);

            double y1 = gridCellFeatureStatistics[0].BoundingBox.LinearRings[0].Points[0].Y;
            double y2 = gridCellFeatureStatistics[0].BoundingBox.LinearRings[0].Points[2].Y;
            double y3 = y1 + ((y2 - y1) / 2); //371
            double y4 = gridCellFeatureStatistics[1].CentreCoordinate.Y;

            Assert.IsTrue(gridCellFeatureStatistics.Count > 0);
            Assert.IsTrue(gridCellFeatureStatistics.Count.Equals(100));

            // Assert.IsTrue(y4.Equals(y3));
        }
 /// <summary>
 /// Gets the grid cell feature statistics combined with species observation counts.
 /// </summary>
 /// <param name="clientInformation">Client information.</param>
 /// <param name="gridSpecification">The grid specification: bounding box, grid cell size, etc.</param>
 /// <param name="searchCriteria">The species observation search criteria.</param>
 /// <param name="featureStatisticsSpecification">Information about requested information from a web feature service.</param>
 /// <param name="featuresUrl">Address to data in a web feature service.</param>
 /// <param name="featureCollectionJson">Feature collection json.</param>
 /// <param name="coordinateSystem">Coordinate system used in returned grid.</param>
 /// <returns>A list with combined result from GetGridSpeciesCounts() and GetGridCellFeatureStatistics().</returns>
 public List <WebGridCellCombinedStatistics> GetGridCellFeatureStatisticsCombinedWithSpeciesObservationCounts(
     WebClientInformation clientInformation,
     WebGridSpecification gridSpecification,
     WebSpeciesObservationSearchCriteria searchCriteria,
     WebFeatureStatisticsSpecification featureStatisticsSpecification,
     String featuresUrl,
     String featureCollectionJson,
     WebCoordinateSystem coordinateSystem)
 {
     using (ClientProxy client = new ClientProxy(this, 20))
     {
         return(client.Client.GetGridCellFeatureStatisticsCombinedWithSpeciesObservationCounts(
                    clientInformation, gridSpecification, searchCriteria, featureStatisticsSpecification, featuresUrl, featureCollectionJson, coordinateSystem));
     }
 }
        public void GetGridCellFeatureStatisticsWithCompleteUrlTest()
        {
            // Test accuracy
            String featuresUrl;
            WebCoordinateSystem coordinateSystem;

            WebFeatureStatisticsSpecification featureStatistics;
            WebGridSpecification gridSpecification;

            gridSpecification = new WebGridSpecification();
            coordinateSystem  = new WebCoordinateSystem();
            featureStatistics = new WebFeatureStatisticsSpecification();



            gridSpecification.BoundingBox     = new WebBoundingBox();
            gridSpecification.BoundingBox.Max = new WebPoint();
            gridSpecification.BoundingBox.Min = new WebPoint();

            //Defined in RT90, X=Northing, Y=Easting
            //This bounding box is parsed and extracted from the url?

            gridSpecification.BoundingBox.Max.Y = 1489104;
            gridSpecification.BoundingBox.Max.X = 6858363;
            gridSpecification.BoundingBox.Min.Y = 1400000;
            gridSpecification.BoundingBox.Min.X = 6800000;

            gridSpecification.GridCellSize            = 100000;
            gridSpecification.GridCoordinateSystem    = GridCoordinateSystem.Rt90_25_gon_v;
            gridSpecification.IsGridCellSizeSpecified = true;
            gridSpecification.GridCellGeometryType    = GridCellGeometryType.Polygon;
            coordinateSystem.Id = CoordinateSystemId.Rt90_25_gon_v;

            featuresUrl = "http://slwgeo.artdata.slu.se:8080/geoserver/wfs?&service=wfs&request=GetFeature&version=1.1.0&typeName=SLW:MapOfSwedishCounties&srsName=EPSG:3021";

            IList <WebGridCellFeatureStatistics> gridCellFeatureStatistics =
                WebServiceProxy.AnalysisService.GetGridCellFeatureStatistics(GetClientInformation(), featureStatistics, featuresUrl, null,                //typeName,
                                                                             gridSpecification, coordinateSystem);


            Assert.IsTrue(gridCellFeatureStatistics.Count > 0);
            Assert.IsTrue(gridCellFeatureStatistics.Count.Equals(4));
            Assert.IsTrue(gridCellFeatureStatistics[0].BoundingBox.LinearRings[0].Points[0].Y.Equals(1400000));
            Assert.IsTrue(gridCellFeatureStatistics[3].BoundingBox.LinearRings[0].Points[2].X.Equals(7000000));
        }
 /// <summary>
 /// Get information about spatial features in a grid representation inside a user supplied bounding box.
 /// </summary>
 /// /// <param name="clientInformation">Information about the client that makes this web service call.</param>
 /// <param name="featureStatisticsSpecification">Information about what statistics are requested from a web feature
 /// service and wich spatial feature type that is to be measured</param>
 /// <param name="featuresUrl">Resource address.</param>
 /// <param name="featureCollectionJson">Feature collection as json string.</param>
 /// <param name="gridSpecification">Specifications of requested grid cell size, requested coordinate system
 /// and user supplied bounding box.</param>
 /// <param name="coordinateSystem">Coordinate system used in geometry search criteria.</param>
 /// <returns>Statistical measurements on spatial features in grid format.</returns>
 public List <WebGridCellFeatureStatistics> GetGridCellFeatureStatistics(WebClientInformation clientInformation,
                                                                         WebFeatureStatisticsSpecification
                                                                         featureStatisticsSpecification,
                                                                         String featuresUrl,
                                                                         String featureCollectionJson,
                                                                         //WfsTypeName typeName,
                                                                         WebGridSpecification gridSpecification,
                                                                         WebCoordinateSystem coordinateSystem)
 {
     using (ClientProxy client = new ClientProxy(this, 20))
     {
         return(client.Client.GetGridFeatureStatistics(clientInformation, featureStatisticsSpecification,
                                                       featuresUrl,
                                                       featureCollectionJson,
                                                       gridSpecification,
                                                       coordinateSystem));
     }
 }
 /// <summary>
 /// Gets the grid cell feature statistics combined with species observation counts.
 /// </summary>
 /// <param name="clientInformation">Client information.</param>
 /// <param name="gridSpecification">The grid specification: bounding box, grid cell size, etc.</param>
 /// <param name="searchCriteria">The species observation search criteria.</param>
 /// <param name="featureStatisticsSpecification">Information about requested information from a web feature service.</param>
 /// <param name="featuresUrl">Address to data in a web feature service.</param>
 /// <param name="featureCollectionJson">Feature collecation as json.</param>
 /// <param name="coordinateSystem">Coordinate system used in returned grid.</param>
 /// <returns>A list with combined result from GetGridSpeciesCounts() and GetGridCellFeatureStatistics().</returns>
 public List <WebGridCellCombinedStatistics> GetGridCellFeatureStatisticsCombinedWithSpeciesObservationCounts(
     WebClientInformation clientInformation,
     WebGridSpecification gridSpecification,
     WebSpeciesObservationSearchCriteria searchCriteria,
     WebFeatureStatisticsSpecification featureStatisticsSpecification,
     String featuresUrl,
     String featureCollectionJson,
     WebCoordinateSystem coordinateSystem)
 {
     using (WebServiceContext context = GetWebServiceContext(clientInformation))
     {
         try
         {
             if (SpeciesObservationConfiguration.IsElasticsearchUsed)
             {
                 return(AnalysisManager.GetGridCellFeatureStatisticsCombinedWithSpeciesObservationCountsElasticsearch(context,
                                                                                                                      searchCriteria,
                                                                                                                      gridSpecification,
                                                                                                                      coordinateSystem,
                                                                                                                      featuresUrl,
                                                                                                                      featureCollectionJson));
             }
             else
             {
                 return(AnalysisManager.GetGridCellFeatureStatisticsCombinedWithSpeciesObservationCounts(context,
                                                                                                         searchCriteria,
                                                                                                         gridSpecification,
                                                                                                         coordinateSystem,
                                                                                                         featuresUrl,
                                                                                                         featureCollectionJson));
             }
         }
         catch (Exception exception)
         {
             WebServiceData.LogManager.LogError(context, exception);
             throw;
         }
     }
 }
コード例 #15
0
        /// <summary>
        /// Creates a SQL geometry grid based on a grid specification.
        /// </summary>
        /// <param name="gridSpecification">The grid specification.</param>
        /// <param name="srid">The srid that is used.</param>
        /// <param name="centrePointList">The centre point list.</param>
        public static List <SqlGeometry> CreateSqlGeometryGrid(WebGridSpecification gridSpecification, int srid, out List <WebPoint> centrePointList)
        {
            SqlGeometry        newCell;
            WebPoint           centrePoint;
            SqlGeometryBuilder geomBuilder;
            List <SqlGeometry> gridCellList = null;
            Double             xMin, yMin, xMax, yMax;
            Int32 cellSize;

            centrePointList = new List <WebPoint>();
            if (gridSpecification.IsNotNull() && centrePointList.IsNotNull() && gridSpecification.GridCellSize.IsNotNull())
            {
                cellSize = gridSpecification.GridCellSize;

                // Adjust grid into even integer intervals.
                // this means that the first grid cells may exceed the boundary box.
                xMin = Math.Floor(gridSpecification.BoundingBox.Min.X / cellSize) * cellSize;
                xMax = Math.Ceiling(gridSpecification.BoundingBox.Max.X / cellSize) * cellSize;
                yMin = Math.Floor(gridSpecification.BoundingBox.Min.Y / cellSize) * cellSize;
                yMax = Math.Ceiling(gridSpecification.BoundingBox.Max.Y / cellSize) * cellSize;

                //Todo: This should be done in earlier checkdata
                if (xMin >= xMax)
                {
                    throw new Exception(string.Format("The bounding box is defect. xMin={0}, xMax={1}", xMin, xMax));
                }
                if (yMin >= yMax)
                {
                    throw new Exception(string.Format("The bounding box is defect.yMin={0}, yMax={1}", yMin, yMax));
                }
                double count = ((xMax - xMin) / cellSize) * ((yMax - yMin) / cellSize);
                if (count > 200000)
                {
                    throw new Exception("Too many grid cells. Use larger cell size or smaller bounding box.");
                }

                //Create a gridcell polygon list and a corresponding centre point list
                gridCellList = new List <SqlGeometry>();
                while (xMin < xMax)     //The last grid cell may exceed the boundary box
                {
                    while (yMin < yMax) //The last grid cell may exceed the boundary box
                    {
                        //Build new list of cells
                        geomBuilder = new SqlGeometryBuilder();
                        geomBuilder.SetSrid(srid);
                        geomBuilder.BeginGeometry(OpenGisGeometryType.Polygon);
                        geomBuilder.BeginFigure(xMin, yMin);
                        geomBuilder.AddLine(xMin + cellSize, yMin);
                        geomBuilder.AddLine(xMin + cellSize, yMin + cellSize);
                        geomBuilder.AddLine(xMin, yMin + cellSize);
                        geomBuilder.AddLine(xMin, yMin);
                        geomBuilder.EndFigure();
                        geomBuilder.EndGeometry();
                        newCell = geomBuilder.ConstructedGeometry;
                        gridCellList.Add(newCell);

                        //Create a list of centre points
                        centrePoint   = new WebPoint();
                        centrePoint.X = Math.Floor(xMin / cellSize) * cellSize + cellSize * 0.5;
                        centrePoint.Y = Math.Floor(yMin / cellSize) * cellSize + cellSize * 0.5;
                        if (centrePointList.IsNotNull())
                        {
                            centrePointList.Add(centrePoint);
                        }

                        yMin = yMin + cellSize;
                    }
                    xMin = xMin + cellSize;
                    yMin = Math.Floor(gridSpecification.BoundingBox.Min.Y / cellSize) * cellSize;
                }
            }

            return(gridCellList);
        }
コード例 #16
0
        public static List <WebGridCellFeatureStatistics> GetFeaturesBasedOnGridCells(List <SqlGeometry> featureList, WebGridSpecification gridSpecification, int srid)
        {
            List <WebGridCellFeatureStatistics> webGridCellFeatureStatisticsList;
            List <SqlGeometry> gridCellList;
            List <WebPoint>    centrePointList;
            SqlGeometry        newFeature;

            if (featureList.IsNotNull() && featureList.Count.Equals(0))
            {
                throw new Exception("There are no features in the featureList.");
            }

            webGridCellFeatureStatisticsList = new List <WebGridCellFeatureStatistics>();
            if (gridSpecification.IsNull())
            {
                return(webGridCellFeatureStatisticsList);
            }


            WebBoundingBox gridBoundingBox     = gridSpecification.BoundingBox;
            WebBoundingBox featuresBoundingBox = GetBoundingBoxFromSqlGeometryList(featureList);

            var mergedBoundingBox = GetFeatureStatisticsMergedBoundingBox(featuresBoundingBox, gridBoundingBox);

            if (mergedBoundingBox != null)
            {
                gridSpecification.BoundingBox = mergedBoundingBox; // change bounding box
            }
            gridCellList = CreateSqlGeometryGrid(gridSpecification, srid, out centrePointList);
            gridSpecification.BoundingBox = gridBoundingBox; // reset bounding box
            WebCoordinateSystem gridCoordinateSystem = gridSpecification.GridCoordinateSystem.ToWebCoordinateSystem();
            int maxGridCellArea = gridSpecification.GridCellSize * gridSpecification.GridCellSize;

            // Pick one grid cell at a time and step through all the features.
            // If they overlap, add the grid cell and the data to the resulting list.
            for (int i = 0; i < gridCellList.Count; i++)
            {
                SqlGeometry gridCell = gridCellList[i];
                WebGridCellFeatureStatistics webGridCellFeatureStatistics = null;

                foreach (SqlGeometry feature in featureList)
                {
                    if (feature == null)
                    {
                        continue;
                    }



                    // *     ____                --------                            ____
                    //  ____/     |             |       |                         __/    |
                    // < ___      |             |       |           =>(intersect) |_     |
                    //      |_   _|   feature   |_______| gridcell                  |____|
                    //        |_|
                    newFeature = feature.STIntersection(gridCell).MakeValid(); //Create a new feature from overlay with the geometry feature and the gridcell
                    if (!(newFeature.STNumGeometries() == 0))                  //If there is intersection
                    {
                        if (webGridCellFeatureStatistics == null)
                        {
                            webGridCellFeatureStatistics = new WebGridCellFeatureStatistics();

                            webGridCellFeatureStatistics.CoordinateSystem        = gridCoordinateSystem;
                            webGridCellFeatureStatistics.BoundingBox             = CreateGridCellBoundingPolygonFromSqlGeometry(gridCell);
                            webGridCellFeatureStatistics.CentreCoordinate        = centrePointList[i];
                            webGridCellFeatureStatistics.Size                    = gridSpecification.GridCellSize;
                            webGridCellFeatureStatistics.GridCoordinateSystem    = gridSpecification.GridCoordinateSystem;
                            webGridCellFeatureStatistics.OrginalBoundingBox      = CreateGridCellBoundingBoxFromSqlGeometry(gridCell);
                            webGridCellFeatureStatistics.OrginalCentreCoordinate = CreateCentreCoordinateFromBoundingBox(webGridCellFeatureStatistics.OrginalBoundingBox);
                            if (feature.GetGeometryType().ToString().Equals("MultiPolygon"))
                            {
                                webGridCellFeatureStatistics.FeatureType = FeatureType.Multipolygon;
                            }
                            if (feature.GetGeometryType().ToString().Equals("Polygon"))
                            {
                                webGridCellFeatureStatistics.FeatureType = FeatureType.Polygon;
                            }
                            if (feature.GetGeometryType().ToString().Equals("MultiLineString"))
                            {
                                webGridCellFeatureStatistics.FeatureType = FeatureType.Multiline;
                            }
                            if (feature.GetGeometryType().ToString().Equals("LineString"))
                            {
                                webGridCellFeatureStatistics.FeatureType = FeatureType.Line;
                            }
                            if (feature.GetGeometryType().ToString().Equals("MultiPoint"))
                            {
                                webGridCellFeatureStatistics.FeatureType = FeatureType.Point;
                            }
                            if (feature.GetGeometryType().ToString().Equals("Point"))
                            {
                                webGridCellFeatureStatistics.FeatureType = FeatureType.Point;
                            }

                            webGridCellFeatureStatisticsList.Add(webGridCellFeatureStatistics);

                            // Create line for lines and Polygones
                            if (feature.GetGeometryType().ToString().Equals("MultiPolygon") || feature.GetGeometryType().ToString().Equals("Polygon") ||
                                feature.GetGeometryType().ToString().Equals("MultiLineString") || feature.GetGeometryType().ToString().Equals("LineString"))
                            {
                                // Old incorrect value
                                // webGridCellFeatureStatistics.FeatureLength += newFeature.STLength().Value;
                                // For debug only
                                // double test = newFeature.STLength().Value;

                                // Here we get the length of the newFeaure without intersection length.
                                // First we get boundaries for feature, newFeature and gridcell
                                SqlGeometry featureBoundary    = feature.STBoundary();
                                SqlGeometry newfeatureBoundary = newFeature.STBoundary();
                                // SqlGeometry gridBoundary = gridCell.STBoundary();

                                // *     ____                       ____
                                //    __/    |                 ___/     |
                                //    |_     |                <___      |            => (difference)   |
                                //      |____|   newfeature       |_   _| feature                          __
                                //                                   |_|
                                // Get the difference between newfeature and feature ie intersection with the gridcell
                                SqlGeometry intersectionObjectsWithGridCell = newfeatureBoundary.STDifference(featureBoundary);

                                // *           ____                                                               ____
                                //          __/    |                                                           __/    |
                                //          |_     |                    |               => (difference)         _     |
                                //            |____| newfeature            __                                    |_  _|
                                //
                                // Then we remove intersectionObjects from newFeature and we get the resulting objects.
                                SqlGeometry newFeatueWithoutIntersection = newfeatureBoundary.STDifference(intersectionObjectsWithGridCell);

                                // And now we have the correct lenght of newFeature.
                                double newFeatueWithoutIntersectionLine = newFeatueWithoutIntersection.STLength().Value;
                                webGridCellFeatureStatistics.FeatureLength += newFeatueWithoutIntersectionLine;
                            }
                        }
                        else
                        {
                            // Create add line length to existing line used for lines and polygones
                            if (feature.GetGeometryType().ToString().Equals("MultiPolygon") || feature.GetGeometryType().ToString().Equals("Polygon") ||
                                feature.GetGeometryType().ToString().Equals("MultiLineString") || feature.GetGeometryType().ToString().Equals("LineString"))
                            {
                                webGridCellFeatureStatistics.FeatureLength += newFeature.STLength().Value;
                            }
                        }
                        // Calculate area only for polygons
                        if (feature.GetGeometryType().ToString().Equals("MultiPolygon") || feature.GetGeometryType().ToString().Equals("Polygon"))
                        {
                            webGridCellFeatureStatistics.FeatureArea += newFeature.STArea().Value;
                            if (webGridCellFeatureStatistics.FeatureArea > maxGridCellArea)
                            {
                                webGridCellFeatureStatistics.FeatureArea = maxGridCellArea;
                            }
                        }

                        if (feature.GetGeometryType().ToString().Equals("MultiPoint") || feature.GetGeometryType().ToString().Equals("Point"))
                        {
                            webGridCellFeatureStatistics.FeatureCount += (int)newFeature.STNumGeometries();
                        }
                        else
                        {
                            webGridCellFeatureStatistics.FeatureCount += 1;
                        }

                        // webGridCellFeatureStatistics.FeatureCount += newFeature.STNumGeometries().Value;
                    }
                }
            }
            return(webGridCellFeatureStatisticsList);
        }