/// <summary>
        /// Once the parameters have been configured the Execute command can be called, it returns true if successful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input1 = _inputParam[0].Value as IFeatureSet;
            if (input1 != null)
            {
                input1.FillAttributes();
            }

            ProjectionParam source = _inputParam[1] as ProjectionParam;
            ProjectionParam dest = _inputParam[2] as ProjectionParam;
            ProjectionInfo pSource = null;
            if (source != null)
            {
                pSource = source.Value;
            }

            if (dest == null)
            {
                return false;
            }

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(input1, pSource, dest.Value, output, cancelProgressHandler);
        }
Example #2
0
 /// <summary>
 /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
 /// </summary>
 public override bool Execute(ICancelProgressHandler cancelProgressHandler)
 {
     IRaster input1 = _inputParam[0].Value as IRaster;
     IRaster input2 = _inputParam[1].Value as IRaster;
     IRaster output = _outputParam[0].Value as IRaster;
     return Execute(input1, input2, output, cancelProgressHandler);
 }
Example #3
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet self = _inputParam[0].Value as IFeatureSet;
            if (self != null)
            {
                self.FillAttributes();
            }

            IFeatureSet other = _inputParam[1].Value as IFeatureSet;
            if (other != null)
            {
                other.FillAttributes();
            }

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            if (self == null)
            {
                return false;
            }

            if (other == null)
            {
                return false;
            }

            return self.Features.Count < other.Features.Count
                       ? Execute(self, other, output, cancelProgressHandler)
                       : Execute(other, self, output, cancelProgressHandler);
        }
Example #4
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet self = _inputParam[0].Value as IFeatureSet;
            IFeatureSet other = _inputParam[1].Value as IFeatureSet;

            if (self != null && other != null)
            {
                self.FillAttributes();
                other.FillAttributes();
            }

            IFeatureSet result = Overlay.EraseFeatures(self, other, cancelProgressHandler);
            if (cancelProgressHandler.Cancel)
            {
                _outputParam = null;
                return false;
            }
            else
            {
                result.Filename = ((IFeatureSet)_outputParam[0].Value).Filename;
                result.Save();
                _outputParam[0].Value = result;
                return true;
            }
        }
 /// <summary>
 /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
 /// </summary>
 public bool Execute(ICancelProgressHandler cancelProgressHandler)
 {
     IRaster input = _inputParam[0].Value as IRaster;
     Double threshold = Convert.ToDouble(_inputParam[1].Value);
     IRaster output = _outputParam[0].Value as IRaster;
     return Execute(input, threshold, output, cancelProgressHandler);
 }
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            MapWindow.Data.IRaster gridIn = _inputParam[0].Value as MapWindow.Data.IRaster;

            IFeatureSet polyOut = _outputParam[0].Value as IFeatureSet;

            return Execute(gridIn, polyOut, cancelProgressHandler);
        }
Example #7
0
 /// <summary>
 /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
 /// </summary>
 public override bool Execute(ICancelProgressHandler cancelProgressHandler)
 {
     IRaster input1 = _inputParam[0].Value as IRaster;
     double baseValue = (double)_inputParam[1].Value;
     double binSize = (double)_inputParam[2].Value;
     IRaster output = _outputParam[0].Value as IRaster;
     return Execute(input1, baseValue, binSize, output, cancelProgressHandler);
 }
Example #8
0
        /// <summary>
        /// Once the Parameters have been configured, the Execute command can be called, it returns true if succesful.
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet self = _inputParam[0].Value as IFeatureSet;

            // self.FillAttributes();
            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(self, output, cancelProgressHandler);
        }
Example #9
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster inputRaster = _inputParam[0].Value as IRaster;

            IRaster outputRaster = _outputParam[0].Value as IRaster;
            double maximumDistance = (double)_inputParam[1].Value;

            return Execute(inputRaster, outputRaster, maximumDistance, cancelProgressHandler);
        }
Example #10
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input = _inputParam[0].Value as IFeatureSet;
            DoubleParam dp = _inputParam[1] as DoubleParam;
            double bufferDistance = 1;
            if(dp != null)bufferDistance = dp.Value;
            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(input, bufferDistance, output, cancelProgressHandler);
        }
Example #11
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster input1 = _inputParam[0].Value as IRaster;
            double value1 = Convert.ToDouble(_inputParam[1].Value);

            double value2 = Convert.ToDouble(_inputParam[2].Value);

            IRaster output = _outputParam[0].Value as IRaster;
            return Execute(input1, value1, value2, output, cancelProgressHandler);
        }
Example #12
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster grid = _inputParam[0].Value as IRaster;
            double inZFactor = (double)_inputParam[1].Value;
            IFeatureSet poly = _inputParam[2].Value as IFeatureSet;

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(grid, inZFactor, poly, output, cancelProgressHandler);
        }
Example #13
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if successful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            string input1 = _inputParam[0].Value as string;
            Extent input2 = _inputParam[1].Value as Extent;
            int numRows = (int)_inputParam[2].Value;
            int numCols = (int)_inputParam[3].Value;
            IRaster output = _outputParam[0].Value as IRaster;

            return Execute(input1, input2, numRows, numCols, output, cancelProgressHandler);
        }
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            MapWindow.Data.IRaster input1 = _inputParam[0].Value as MapWindow.Data.IRaster;
            MapWindow.Data.IFeatureSet input2 = _inputParam[1].Value as MapWindow.Data.IFeatureSet;

            MapWindow.Data.IRaster output = _outputParam[0].Value as MapWindow.Data.IRaster;

            return Execute(input1, input2, output, cancelProgressHandler);

        }
        /// <summary>
        /// Once the parameters have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool  Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input1 = _inputParam[0].Value as IFeatureSet;
            if (input1 != null) input1.FillAttributes();
            var input2 = _inputParam[1].Value as IFeatureSet;
            if (input2 != null) input2.FillAttributes();
            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(input1, input2, output, cancelProgressHandler);
        }
Example #16
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster input1 = _inputParam[0].Value as IRaster;
            double inZFactor = (double)_inputParam[1].Value;

            bool slopeInPercent = (bool)_inputParam[2].Value;

            IRaster output = _outputParam[0].Value as IRaster;

            return Execute(input1, inZFactor, slopeInPercent, output, cancelProgressHandler);
        }
Example #17
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            MapWindow.Data.IRaster input1 = _inputParam[0].Value as MapWindow.Data.IRaster;
            double inZFactor = (double)_inputParam[1].Value;

            bool slopeInPercent =(bool) _inputParam[2].Value;

            MapWindow.Data.IRaster output = _outputParam[0].Value as MapWindow.Data.IRaster;

            return Execute(input1, inZFactor,slopeInPercent, output, cancelProgressHandler);
        }
 /// <summary>
 /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
 /// </summary>
 public bool Execute(ICancelProgressHandler cancelProgressHandler)
 {
     IFeatureSet poly = _inputParam[0].Value as IFeatureSet;
     double cellSize = (double)_inputParam[2].Value;
     if (poly == null) return false;
     int indx = (int)_inputParam[1].Value - 1;
     string field = indx < 0 ? "FID" : poly.DataTable.Columns[indx].ColumnName;
     
     IRaster output = _outputParam[0].Value as IRaster;
     return Execute(poly, cellSize, field, output, cancelProgressHandler);
     
 }
Example #19
0
        /// <summary>
        /// Once the parameters have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input1 = _inputParam[0].Value as IFeatureSet;
            if (input1 != null)
            {
                input1.FillAttributes();
            }

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(input1, output, cancelProgressHandler);
        }
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet poly = _inputParam[0].Value as IFeatureSet;
            int numRow = (int)_inputParam[1].Value;
            int numCol = (int)_inputParam[2].Value;
            int selectionIndex = (int)_inputParam[3].Value;
            
            MapWindow.Data.IRaster output = _outputParam[0].Value as MapWindow.Data.IRaster;


            return Execute(poly, numRow, numCol,selectionIndex, output, cancelProgressHandler);
        }
Example #21
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet self = _inputParam[0].Value as IFeatureSet;
            if (self != null) self.FillAttributes();
            IFeatureSet other = _inputParam[1].Value as IFeatureSet;
            if (other != null) other.FillAttributes();

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(self, other, output, cancelProgressHandler);
         
        }
Example #22
0
        public bool Execute(ICancelProgressHandler CancelProgressHandler)
        {
            string fileName = _outputParameters[0].Value.ToString();

            if (Execute(fileName, CancelProgressHandler) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// Once the parameters have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input1 = _inputParam[0].Value as IFeatureSet;
            if (input1 != null) input1.FillAttributes();

            IndexParam ip = _inputParam[1] as IndexParam;
            string input2 = "";
            if(ip != null) input2 = ip.Value;

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(input1, input2, output, cancelProgressHandler);
        }
Example #24
0
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet input = _inputParam[0].Value as IFeatureSet;
            if (input != null)
            {
                input.FillAttributes();
            }

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            Analysis.Voronoi.VoronoiPolygons(input, output, true);
            output.Save();
            return true;
        }
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster input1 = _inputParam[0].Value as IRaster;
            DoubleParam dp1 = _inputParam[1] as DoubleParam;
            DoubleParam dp2 = _inputParam[2] as DoubleParam;
            double value1 = 0;
            double value2 = 0;
            if(dp1 != null) value1 = dp1.Value;
            if (dp2 != null) value2 = dp2.Value;
           
            IRaster output = _outputParam[0].Value as IRaster;
            return Execute(input1, value1, value2, output, cancelProgressHandler);

        }
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster grid = _inputParam[0].Value as IRaster;
            double inZFactor = (double)_inputParam[1].Value;
            bool slopeInPercent = (bool)_inputParam[2].Value;
            IFeatureSet poly = _inputParam[3].Value as IFeatureSet;
            IFeatureSet outerShpFile = _inputParam[4].Value as IFeatureSet;
            int outerShpIndex = (int)_inputParam[5].Value;
            string fldInPolyToStoreSlope = (string)_inputParam[6].Value;

            IFeatureSet output = _outputParam[0].Value as IFeatureSet;

            return Execute(grid, inZFactor, slopeInPercent, poly, fldInPolyToStoreSlope, outerShpFile, outerShpIndex, output, cancelProgressHandler);
        }
        /// <summary>
        /// Once the Parameter have been configured the Execute command can be called, it returns true if succesful
        /// </summary>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            IRaster raster = _inputParam[0].Value as IRaster;
            IFeatureSet polygon = _inputParam[1].Value as IFeatureSet;

            IRaster output = _outputParam[0].Value as IRaster;

            // Validates the input and output data
            if (raster == null || polygon == null || output == null)
            {
                return false;
            }

            ClipRaster.ClipRasterWithPolygon(
                polygon.Features[0], raster, output.Filename, cancelProgressHandler);
            return true;
        }
Example #28
0
        /// <summary>
        /// Erase features from one feature set where they are intersected by another feature set. 
        /// </summary>
        /// <param name="TargetFeatures">Features which will be erased in part or whole.</param>
        /// <param name="SourceFeatures">Features which represent areas to erase.</param>
        /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param>
        /// <returns>A point feature set with the randomly created features.</returns>
        public static FeatureSet EraseFeatures(IFeatureSet TargetFeatures, IFeatureSet SourceFeatures, ICancelProgressHandler cancelProgressHandler = null)
        {
            if (TargetFeatures == null || SourceFeatures == null)
            {
                return null;
            }
            //Erase features from one feature set where they are intersected by another feature set
            //Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique.
            //The current version does not preserve any attribute info. 
            //Dan Ames 2/27/2013
            FeatureSet ResultFeatures = new FeatureSet();                   //the resulting featureset
            IFeature TF, SF;                                                //a single output feature
            ResultFeatures.CopyTableSchema(TargetFeatures);                 //set up the data table in the new feature set

            for (Int16 i = 0; i <= TargetFeatures.ShapeIndices.Count - 1; i++)
            {
                TF = TargetFeatures.GetFeature(i);                          //get the full undifferenced feature
                for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++)
                {
                    SF = SourceFeatures.GetFeature(j);
                    if (SF.Envelope.Intersects(TF.Envelope))
                    {
                        TF = TF.Difference(SF);                             //clip off any pieces of SF that overlap FR
                    }
                    if (TF == null)
                    {                                                       //sometimes difference leaves nothing left of a feature
                        break;
                    }
                }
                if (TF != null)
                {
                    ResultFeatures.AddFeature(TF).CopyAttributes(TargetFeatures.GetFeature(i));  //add the fully clipped feature to the results
                }
                if (cancelProgressHandler != null)
                {
                    if (cancelProgressHandler.Cancel) { return null; }
                    int progress = Convert.ToInt32(i * 100 / TargetFeatures.ShapeIndices.Count);
                    cancelProgressHandler.Progress(String.Empty, progress, String.Empty);
                }
            }
            return ResultFeatures;
        }
Example #29
0
        /// <summary>
        /// A static function to compute the buffer and return the result to the Execute function.
        /// </summary>
        /// <param name="input">The feature set that will be buffered.</param>
        /// <param name="bufferDistance">The distance of the buffer.</param>
        /// <param name="outputFeatures">The resulting feature set that will show the buffer.</param>
        /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel if needed.</param>
        /// <returns></returns>
        public static bool AddBuffer(IFeatureSet inputFeatures, double bufferDistance, IFeatureSet outputFeatures, ICancelProgressHandler cancelProgressHandler = null)
        {
            int numFeatures = inputFeatures.Features.Count;
            for (int i = 0; i < numFeatures; i++)
            {
                inputFeatures.Features[i].Buffer(bufferDistance, outputFeatures);

                // Here we update the progress
                if (cancelProgressHandler != null)
                {
                    if (cancelProgressHandler.Cancel)
                    {
                        return false;
                    }
                    int progress = Convert.ToInt32(i * 100 / numFeatures);
                    cancelProgressHandler.Progress("buffer_tool", progress, "Buffering features.");
                }
            }
            return true;
        }
Example #30
0
 public bool Execute(string fileName, ICancelProgressHandler cancelProgressHandler)
 {
     string SeriesId = GetSeriesId();
     DataTable dataValues = GetDataValues(SeriesId);
     if (dataValues.Rows.Count > 1)
     {
         for (int j = 1; j < dataValues.Rows.Count; j++)
         {
             DataTable2CSV(dataValues, fileName, ",");
             cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(dataValues.Rows.Count)) * 100), dataValues.Rows[j][0].ToString());
             if (cancelProgressHandler.Cancel)
                 return false;
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Example #31
0
        /// <summary>
        /// Once the parameters have been configured the Execute command can be called, it returns true if succesful.
        /// </summary>
        /// <param name="cancelProgressHandler">The progresshandler used for showing the proress.</param>
        /// <returns>False on error, otherwise true if run successfully.</returns>
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (!(_inputParam[0].Value is IFeatureSet inputFs1) || !(_inputParam[1].Value is IFeatureSet inputFs2) || !(_outputParam[0].Value is IFeatureSet output) || inputFs1.FeatureType != FeatureType.Polygon || output.FeatureType != FeatureType.Polygon || inputFs2.FeatureType != FeatureType.Polygon)
            {
                return(false);
            }

            output.CopyTableSchema(inputFs1.DataTable);
            output.Projection = inputFs1.Projection;

            if (!output.DataTable.Columns.Contains("InterArea"))
            {
                output.DataTable.Columns.Add("InterArea");
            }

            int maxFeature = inputFs1.Features.Count;

            for (int i = 0; i < inputFs1.Features.Count; i++)
            {
                if (cancelProgressHandler.Cancel)
                {
                    return(false);
                }

                int current = Convert.ToInt32(Math.Round((i + 1) * 100d / maxFeature));

                IFeature        polygonFeat1         = inputFs1.Features[i];
                Extent          tolerant             = polygonFeat1.Geometry.EnvelopeInternal.ToExtent();
                List <IFeature> intersectingFeatures = inputFs2.Select(tolerant);

                if (intersectingFeatures?.Count > 0)
                {
                    foreach (IFeature polygonFeat2 in intersectingFeatures)
                    {
                        if (polygonFeat2.Geometry.Intersects(polygonFeat1.Geometry))
                        {
                            try
                            {
                                Geometry intersectedF = polygonFeat2.Geometry.Intersection(polygonFeat1.Geometry);
                                var      f            = output.AddFeature(intersectedF);
                                f.DataRow["InterArea"] = intersectedF.Area;
                                f.CopyAttributes(polygonFeat1);
                            }
                            catch (Exception e)
                            {
                                cancelProgressHandler.Progress(current, e.Message);
                                return(false);
                            }
                        }
                    }
                }

                if (current % 5 == 0)
                {
                    cancelProgressHandler.Progress(current, current + TextStrings.progresscompleted);
                }
            }

            output.Save();
            return(true);
        }
Example #32
0
        /// <summary>
        /// A static function to compute the buffer and return the result to the Execute function.
        /// </summary>
        /// <param name="inputFeatures">The feature set that will be buffered.</param>
        /// <param name="bufferDistance">The distance of the buffer.</param>
        /// <param name="outputFeatures">The resulting feature set that will show the buffer.</param>
        /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel if needed.</param>
        /// <returns></returns>
        public static bool AddBuffer(IFeatureSet inputFeatures, double bufferDistance, IFeatureSet outputFeatures, ICancelProgressHandler cancelProgressHandler = null)
        {
            int numFeatures = inputFeatures.Features.Count;

            for (int i = 0; i < numFeatures; i++)
            {
                inputFeatures.Features[i].Buffer(bufferDistance, outputFeatures);

                // Here we update the progress
                if (cancelProgressHandler != null)
                {
                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }
                    int progress = Convert.ToInt32(i * 100 / numFeatures);
                    cancelProgressHandler.Progress("buffer_tool", progress, "Buffering features.");
                }
            }
            return(true);
        }
Example #33
0
 public override void Save(ICancelProgressHandler progress)
 {
     throw new NotImplementedException();
 }
Example #34
0
        /// <summary>
        /// Executes the Erase Opaeration tool programaticaly
        /// Ping Yang deleted static for external testing 01/2010
        /// </summary>
        /// <param name="input">The input raster</param>
        /// <param name="oldValue">The original double value representing no-data</param>
        /// <param name="newValue">The new double value representing no-data</param>
        /// <param name="output">The output raster</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns></returns>
        public bool Execute(
            IRaster input,
            double oldValue,
            double newValue,
            IRaster output,
            ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input == null || newValue == 0 || output == null)
            {
                return(false);
            }

            Extent envelope = input.Bounds.Extent;

            int noOfCol  = input.NumColumns;
            int noOfRow  = input.NumRows;
            int previous = 0;

            // create output raster
            output = Raster.CreateRaster(
                output.Filename, string.Empty, noOfCol, noOfRow, 1, typeof(int), new[] { string.Empty });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope);

            output.Bounds = bound;

            output.NoDataValue = input.NoDataValue;

            // Loop throug every cell
            int max = output.Bounds.NumRows + 1;

            for (int i = 0; i < output.Bounds.NumRows; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    if (input.Value[i, j] == oldValue)
                    {
                        output.Value[i, j] = newValue;
                    }
                    else
                    {
                        output.Value[i, j] = input.Value[i, j];
                    }

                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }
                }

                int current = Convert.ToInt32(Math.Round(i * 100D / max));

                // only update when increment in persentage
                if (current > previous)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                }

                previous = current;
            }

            // output = Temp;
            output.Save();
            return(true);
        }
Example #35
0
        /// <summary>
        /// Executes the Area tool with programatic input
        /// Ping delete static for external testing
        /// </summary>
        /// <param name="input">The input raster</param>
        /// <param name="zField">The field name containing the values to interpolate</param>
        /// <param name="cellSize">The double geographic size of the raster cells to create</param>
        /// <param name="power">The double power representing the inverse</param>
        /// <param name="neighborType">Fixed distance of fixed number of neighbors</param>
        /// <param name="pointCount">The number of neighbors to include if the neighborhood type
        /// is Fixed</param>
        /// <param name="distance">Points further from the raster cell than this distance are not included
        /// in the calculation if the neighborhood type is Fixed Distance.</param>
        /// <param name="output">The output raster where values are stored.  The fileName is used, but the number
        /// of rows and columns will be computed from the cellSize and input featureset</param>
        /// <param name="cancelProgressHandler">A progress handler for receiving progress messages</param>
        /// <returns>A boolean, true if the IDW process worked correctly</returns>
        public bool Execute(IFeatureSet input, string zField, double cellSize, double power, NeighborhoodType neighborType, int pointCount, double distance, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input == null || output == null)
            {
                return(false);
            }

            // If the cellSize is 0 we calculate a cell size based on the input extents
            if (cellSize == 0)
            {
                cellSize = input.Extent.Width / 255;
            }

            // Defines the dimensions and position of the raster
            int numColumns = Convert.ToInt32(Math.Round(input.Extent.Width / cellSize));
            int numRows    = Convert.ToInt32(Math.Round(input.Extent.Height / cellSize));

            output = Raster.CreateRaster(output.Filename, string.Empty, numColumns, numRows, 1, typeof(double), new[] { string.Empty });

            output.CellHeight = cellSize;
            output.CellWidth  = cellSize;
            output.Xllcenter  = input.Extent.MinX + (cellSize / 2);
            output.Yllcenter  = input.Extent.MinY + (cellSize / 2);

            // Used to calculate progress
            int lastUpdate = 0;

            // Populates the KD tree
            var        kd         = new KdTreeEx <IFeature>();
            List <int> randomList = new List <int>();

            for (int i = 0; i < input.Features.Count; i++)
            {
                randomList.Add(i);
            }

            Random     rnd       = new Random();
            List <int> completed = new List <int>();

            while (randomList.Count > 0)
            {
                int        index = rnd.Next(0, randomList.Count - 1);
                Coordinate coord = input.Features[randomList[index]].Geometry.Coordinates[0];
                while (kd.Search(coord) != null)
                {
                    coord.X = coord.X * 1.000000000000001D;
                }

                kd.Insert(coord, input.Features[randomList[index]]);
                completed.Add(randomList[index]);
                randomList.RemoveAt(index);
            }

            if (neighborType == NeighborhoodType.FixedCount)
            {
                // we add all the old features to output
                for (int x = 0; x < numColumns; x++)
                {
                    for (int y = 0; y < numRows; y++)
                    {
                        // Gets the pointCount number of cells closest to the current cell
                        Coordinate cellCenter = output.CellToProj(y, x);
                        var        coord      = output.CellToProj(y, x);
                        var        result     = kd.NearestNeighbor(coord);
                        var        featurePt  = result?.Data;
                        if (featurePt != null)
                        {
                            // Sets up the IDW numerator and denominator
                            double top    = 0;
                            double bottom = 0;

                            double distanceToCell = cellCenter.Distance(featurePt.Geometry.Coordinates[0]);
                            if (distanceToCell <= distance || distance == 0)
                            {
                                // If we can't convert the value to a double throw it out
                                try
                                {
                                    Convert.ToDouble(featurePt.DataRow[zField]);
                                }
                                catch
                                {
                                    continue;
                                }

                                if (power == 2)
                                {
                                    top    += (1 / (distanceToCell * distanceToCell)) * Convert.ToDouble(featurePt.DataRow[zField]);
                                    bottom += 1 / (distanceToCell * distanceToCell);
                                }
                                else
                                {
                                    top    += (1 / Math.Pow(distanceToCell, power)) * Convert.ToDouble(featurePt.DataRow[zField]);
                                    bottom += 1 / Math.Pow(distanceToCell, power);
                                }
                            }

                            output.Value[y, x] = top / bottom;
                        }
                    }

                    // Checks if we need to update the status bar
                    if (Convert.ToInt32(Convert.ToDouble(x * numRows) / Convert.ToDouble(numColumns * numRows) * 100) > lastUpdate)
                    {
                        lastUpdate = Convert.ToInt32(Convert.ToDouble(x * numRows) / Convert.ToDouble(numColumns * numRows) * 100);
                        cancelProgressHandler.Progress(lastUpdate, "Cell: " + (x * numRows) + " of " + (numColumns * numRows));
                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }
            }

            output.Save();
            return(true);
        }
Example #36
0
        /// <summary>
        /// Gets the count of members that match the expression
        /// </summary>
        /// <param name="expressions">The string expression to test</param>
        /// <param name="progressHandler">THe progress handler that can also cancel the counting</param>
        /// <param name="maxSampleSize">The integer maximum sample size from which to draw counts.  If this is negative, it will not be used.</param>
        /// <returns>The integer count of the members that match the expression.</returns>
        public override int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize)
        {
            if (AttributesPopulated)
            {
                return(base.GetCounts(expressions, progressHandler, maxSampleSize));
            }

            int[] counts = new int[expressions.Length];

            // The most common case would be no filter expression, in which case the count is simply the number of shapes.
            bool requiresRun = false;

            for (int iex = 0; iex < expressions.Length; iex++)
            {
                if (!string.IsNullOrEmpty(expressions[iex]))
                {
                    requiresRun = true;
                }
                else
                {
                    counts[iex] = NumRows();
                }
            }
            if (!requiresRun)
            {
                return(counts);
            }

            AttributePager ap = new AttributePager(this, 5000);
            ProgressMeter  pm = new ProgressMeter(progressHandler, "Calculating Counts", ap.NumPages());

            // Don't bother to use a sampling approach if the number of rows is on the same order of magnitude as the number of samples.
            if (maxSampleSize > 0 && maxSampleSize < NumRows() / 2)
            {
                DataTable sample = new DataTable();
                sample.Columns.AddRange(GetColumns());
                Dictionary <int, int> usedRows = new Dictionary <int, int>();
                int    samplesPerPage          = maxSampleSize / ap.NumPages();
                Random rnd = new Random(DateTime.Now.Millisecond);
                for (int page = 0; page < ap.NumPages(); page++)
                {
                    for (int i = 0; i < samplesPerPage; i++)
                    {
                        int row;
                        do
                        {
                            row = rnd.Next(ap.StartIndex, ap.StartIndex + ap.PageSize);
                        } while (usedRows.ContainsKey(row));
                        usedRows.Add(row, row);
                        sample.Rows.Add(ap.Row(row).ItemArray);
                    }
                    ap.MoveNext();

                    pm.CurrentValue = page;
                    if (progressHandler.Cancel)
                    {
                        break;
                    }
                    //Application.DoEvents();
                }
                for (int i = 0; i < expressions.Length; i++)
                {
                    try
                    {
                        DataRow[] dr = sample.Select(expressions[i]);
                        counts[i] += dr.Length;
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }
                }
                pm.Reset();
                return(counts);
            }
            for (int page = 0; page < ap.NumPages(); page++)
            {
                for (int i = 0; i < expressions.Length; i++)
                {
                    DataRow[] dr = ap[page].Select(expressions[i]);
                    counts[i] += dr.Length;
                }
                pm.CurrentValue = page;
                if (progressHandler.Cancel)
                {
                    break;
                }
                //Application.DoEvents();
            }
            pm.Reset();
            return(counts);
        }
Example #37
0
        public override bool Load(ICancelProgressHandler progresshandler)
        {
            if (File.Exists(FileName))
            {
                var mf     = Owner as Modflow;
                var grid   = (Owner.Grid as MFGrid);
                int nlayer = grid.ActualLayerCount;

                mf.LayerGroupManager.Clear();
                StreamReader sr = new StreamReader(FileName);
                //Data Set 1: # ILPFCB, HDRY, NPLPF
                string  newline = ReadComment(sr);
                float[] fv      = TypeConverterEx.Split <float>(newline, 3);
                int     ncell   = grid.ActiveCellCount;
                ILPFCB = (int)fv[0];
                HDRY   = fv[1];
                NPLPF  = (int)fv[2];

                //Data Set 2: #
                newline = sr.ReadLine();
                LAYTYP  = TypeConverterEx.Split <int>(newline, nlayer);

                //Data Set 3: #
                newline = sr.ReadLine();
                LAYAVG  = TypeConverterEx.Split <int>(newline, nlayer);

                //Data Set 4: #
                newline = sr.ReadLine();
                CHANI   = TypeConverterEx.Split <float>(newline, nlayer);

                //Data Set 5: #
                newline = sr.ReadLine();
                LAYVKA  = TypeConverterEx.Split <int>(newline, nlayer);

                //Data Set 6: #
                newline = sr.ReadLine();
                LAYWET  = TypeConverterEx.Split <int>(newline, nlayer);

                if (LAYWET.Sum() != 0)
                {
                    //Data Set 7: #
                    newline = sr.ReadLine();
                    fv      = TypeConverterEx.Split <float>(newline, 3);
                    WETFCT  = fv[0];
                    IWETIT  = (int)fv[1];
                    IHDWET  = (int)fv[2];
                }

                mf.LayerGroupManager.LayerGroups.CollectionChanged -= this.LayerGroups_CollectionChanged;
                mf.LayerGroupManager.Initialize(grid.ActualLayerCount);
                mf.LayerGroupManager.ConvertFrom(LAYTYP, "LAYTYP");
                mf.LayerGroupManager.ConvertFrom(LAYAVG, "LAYAVG");
                mf.LayerGroupManager.ConvertFrom(CHANI, "CHANI");
                mf.LayerGroupManager.ConvertFrom(LAYVKA, "LAYVKA");
                mf.LayerGroupManager.ConvertFrom(LAYWET, "LAYWET");
                mf.LayerGroupManager.LayerGroups.CollectionChanged += this.LayerGroups_CollectionChanged;

                HK = new DataCube <float>(nlayer, 1, grid.ActiveCellCount)
                {
                    AllowTableEdit = true,
                    TimeBrowsable  = false,
                    Name           = "HK"
                };

                HANI = new DataCube <float>(nlayer, 1, grid.ActiveCellCount)
                {
                    AllowTableEdit = true,
                    TimeBrowsable  = false,
                    Name           = "HANI"
                };
                VKA = new DataCube <float>(nlayer, 1, grid.ActiveCellCount)
                {
                    AllowTableEdit = true,
                    TimeBrowsable  = false,
                    Name           = "VKA"
                };
                SS = new DataCube <float>(nlayer, 1, grid.ActiveCellCount)
                {
                    AllowTableEdit = true,
                    TimeBrowsable  = false,
                    Name           = "SS"
                };
                SY = new DataCube <float>(nlayer, 1, grid.ActiveCellCount)
                {
                    AllowTableEdit = true,
                    TimeBrowsable  = false,
                    Name           = "SY"
                };
                WETDRY = new DataCube <float>(nlayer, 1, grid.ActiveCellCount)
                {
                    AllowTableEdit = true,
                    TimeBrowsable  = false,
                    Name           = "WETDRY"
                };

                HK.Topology     = grid.Topology;
                HANI.Topology   = grid.Topology;
                VKA.Topology    = grid.Topology;
                SS.Topology     = grid.Topology;
                SY.Topology     = grid.Topology;
                WETDRY.Topology = grid.Topology;

                for (int l = 0; l < grid.ActualLayerCount; l++)
                {
                    ReadSerialArray(sr, HK, l, 0);
                    ReadSerialArray(sr, HANI, l, 0);
                    ReadSerialArray(sr, VKA, l, 0);
                    ReadSerialArray(sr, SS, l, 0);

                    if (LAYTYP[l] != 0)
                    {
                        ReadSerialArray(sr, SY, l, 0);
                    }

                    if (LAYTYP[l] != 0 && LAYWET[l] != 0)
                    {
                        ReadSerialArray(sr, WETDRY, l, 0);
                    }

                    HK.Variables[l]     = "HK Layer" + (l + 1);
                    HANI.Variables[l]   = "HANI Layer" + (l + 1);
                    VKA.Variables[l]    = "VKA Layer" + (l + 1);
                    SS.Variables[l]     = "SS Layer" + (l + 1);
                    SY.Variables[l]     = "SY Layer" + (l + 1);
                    WETDRY.Variables[l] = "WETDRY Layer" + (l + 1);
                }
                sr.Close();
                OnLoaded(progresshandler);
                return(true);
            }
            else
            {
                OnLoadFailed("Failed to load " + this.Name, progresshandler);
                return(false);
            }
        }
Example #38
0
        /// <summary>
        /// Executes the Erase Opaeration tool programaticaly
        /// Ping Yang deleted static for external testing 01/2010.
        /// </summary>
        /// <param name="input1">The original input raster.</param>
        /// <param name="input2">The second input raster.</param>
        /// <param name="output">The output raster</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>Boolean, true if the method was successful.</returns>
        public bool Execute(IRaster input1, IRaster input2, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            RasterMagic magic = new RasterMagic(Operation);

            return(magic.RasterMath(input1, input2, output, cancelProgressHandler));
        }
Example #39
0
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="ras">The input altitude raster.</param>
        /// <param name="inZFactor">A multiplicative scaling factor to be applied to the elevation values before calculating the slope.</param>
        /// <param name="slopeInPercent">If this is true, the resulting slopes are returned as percentages.</param>
        /// <param name="output">The output slope raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>True if the method worked.</returns>
        public bool Execute(
            IRaster ras,
            double inZFactor,
            bool slopeInPercent,
            IRaster output,
            ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || output == null)
            {
                return(false);
            }

            try
            {
                int noOfCol = ras.NumColumns;
                int noOfRow = ras.NumRows;
                output = Raster.CreateRaster(
                    output.Filename, string.Empty, noOfCol, noOfRow, 1, typeof(double), new[] { string.Empty });
                output.NoDataValue = ras.NoDataValue;

                // output.Bounds = ras.Bounds.Copy();
                output.Bounds = ras.Bounds;

                int previous = 0;
                for (int i = 0; i < output.NumRows; i++)
                {
                    int current = Convert.ToInt32(Math.Round(i * 100D / output.NumRows));

                    // only update when increment in percentage
                    if (current > previous)
                    {
                        cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                    }

                    previous = current;

                    for (int j = 0; j < output.NumColumns; j++)
                    {
                        if (i > 0 && i < output.NumRows - 1 && j > 0 && j < output.NumColumns - 1)
                        {
                            double z1 = ras.Value[i - 1, j - 1];
                            double z2 = ras.Value[i - 1, j];
                            double z3 = ras.Value[i - 1, j + 1];
                            double z4 = ras.Value[i, j - 1];
                            double z5 = ras.Value[i, j + 1];
                            double z6 = ras.Value[i + 1, j - 1];
                            double z7 = ras.Value[i + 1, j];
                            double z8 = ras.Value[i + 1, j + 1];

                            // 3rd Order Finite Difference slope algorithm
                            double dZdX = inZFactor * ((z3 - z1) + 2 * (z5 - z4) + (z8 - z6)) / (8 * ras.CellWidth);
                            double dZdY = inZFactor * ((z1 - z6) + 2 * (z2 - z7) + (z3 - z8)) / (8 * ras.CellHeight);

                            double slope = Math.Atan(Math.Sqrt((dZdX * dZdX) + (dZdY * dZdY))) * (180 / Math.PI);

                            // change to radious and in persentage
                            if (slopeInPercent)
                            {
                                slope = Math.Tan(slope * Math.PI / 180) * 100;
                            }

                            output.Value[i, j] = slope;

                            if (cancelProgressHandler.Cancel)
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            output.Value[i, j] = output.NoDataValue;
                        }

                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }

                // output = Temp;
                if (output.IsFullyWindowed())
                {
                    output.Save();
                    return(true);
                }

                return(false);
            }
            catch (Exception ex)
            {
                // throw new SystemException("Error in Slope: ", ex);
                throw new SystemException(ex.ToString());
            }
        }
Example #40
0
        /// <inheritdoc />
        public int[] GetCounts(string[] expressions, ICancelProgressHandler progressHandler, int maxSampleSize)
        {
            int numSelected = Count;

            int[] counts      = new int[expressions.Length];
            bool  requiresRun = false;

            for (int ie = 0; ie < expressions.Length; ie++)
            {
                if (string.IsNullOrEmpty(expressions[ie]))
                {
                    counts[ie] = numSelected;
                }
                else
                {
                    requiresRun = true;
                }
            }

            if (!requiresRun)
            {
                return(counts);
            }

            AttributePager ap         = new AttributePager(_layer.DataSet, 100000);
            int            numinTable = 0;
            DataTable      result     = new DataTable();

            result.Columns.AddRange(_layer.DataSet.GetColumns());
            FastDrawnState[] drawnStates = _layer.DrawnStates;
            for (int shp = 0; shp < drawnStates.Length; shp++)
            {
                if (drawnStates[shp].Selected)
                {
                    result.Rows.Add(ap.Row(shp).ItemArray);
                    numinTable++;
                    if (numinTable > 100000)
                    {
                        for (int ie = 0; ie < expressions.Length; ie++)
                        {
                            if (string.IsNullOrEmpty(expressions[ie]))
                            {
                                continue;
                            }

                            counts[ie] += result.Select(expressions[ie]).Length;
                        }

                        result.Clear();
                    }
                }
            }

            for (int ie = 0; ie < expressions.Length; ie++)
            {
                if (string.IsNullOrEmpty(expressions[ie]))
                {
                    continue;
                }

                counts[ie] += result.Select(expressions[ie]).Length;
            }

            result.Clear();
            return(counts);
        }
Example #41
0
        public override bool Execute(ICancelProgressHandler cancelProgressHandler)
        {
            var     shell    = MyAppManager.Instance.CompositionContainer.GetExportedValue <IShellService>();
            var     prj      = MyAppManager.Instance.CompositionContainer.GetExportedValue <IProjectService>();
            var     model    = prj.Project.Model;
            int     progress = 0;
            int     count    = 1;
            Modflow mf       = null;

            if (model is HeiflowModel)
            {
                mf = (model as HeiflowModel).ModflowModel;
            }
            else if (model is Modflow)
            {
                mf = model as Modflow;
            }
            if (mf != null)
            {
                if (!mf.Packages.ContainsKey(FHBPackage.PackageName))
                {
                    var fhb = mf.Select(FHBPackage.PackageName);
                    mf.Add(fhb);
                }
                var pck = mf.GetPackage(FHBPackage.PackageName) as FHBPackage;
                pck.NBDTIM = 2;
                pck.NHED   = 0;
                pck.IFHBSS = 1;
                pck.BDTIM  = new int[] { 0, prj.Project.Model.TimeService.NumTimeStep };
                List <FlowBound> list = new List <FlowBound>();
                int npt = _sourcefs.Features.Count;
                for (int i = 0; i < npt; i++)
                {
                    var   pt    = _sourcefs.Features[i].Geometry.Coordinate;
                    int   layer = 1;
                    float rate  = 0;
                    if (!string.IsNullOrEmpty(LayerField))
                    {
                        int.TryParse(_sourcefs.DataTable.Rows[i][LayerField].ToString(), out layer);
                    }
                    if (!string.IsNullOrEmpty(FluxRateField))
                    {
                        float.TryParse(_sourcefs.DataTable.Rows[i][FluxRateField].ToString(), out rate);
                    }
                    for (int j = 0; j < _grid_layer.Features.Count; j++)
                    {
                        var cell = _grid_layer.Features[j].Geometry.Coordinates;
                        if (SpatialRelationship.PointInPolygon(cell, pt))
                        {
                            FlowBound bound = new FlowBound()
                            {
                                Layer    = layer,
                                FlowRate = rate,
                                Row      = int.Parse(_grid_layer.DataTable.Rows[j]["ROW"].ToString()),
                                Col      = int.Parse(_grid_layer.DataTable.Rows[j]["COLUMN"].ToString()),
                            };
                            list.Add(bound);
                            break;
                        }
                    }
                    progress = i * 100 / npt;
                    if (progress > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing point: " + i);
                        count++;
                    }
                }
                if (list.Count > 0)
                {
                    pck.NFLW = list.Count;
                    var FlowRate = new DataCube <float>(4 + pck.NBDTIM, 1, pck.NFLW)
                    {
                        Name           = "FHB_FlowRate",
                        TimeBrowsable  = false,
                        AllowTableEdit = true
                    };
                    FlowRate.Variables[0] = "Layer";//Layer Row Column IAUX  FLWRAT(NBDTIM)
                    FlowRate.Variables[1] = "Row";
                    FlowRate.Variables[2] = "Column";
                    FlowRate.Variables[3] = "IAUX";
                    for (int i = 0; i < pck.NBDTIM; i++)
                    {
                        FlowRate.Variables[4 + i] = "FLWRAT " + (i + 1);
                    }
                    for (int i = 0; i < pck.NFLW; i++)
                    {
                        var bound = list[i];
                        FlowRate[0, 0, i] = bound.Layer;
                        FlowRate[1, 0, i] = bound.Row;
                        FlowRate[2, 0, i] = bound.Col;
                        FlowRate[3, 0, i] = 0;
                        for (int j = 0; j < pck.NBDTIM; j++)
                        {
                            FlowRate[4 + j, 0, i] = bound.FlowRate;
                        }
                    }
                    FlowRate.TimeBrowsable = false;
                    pck.FlowRate           = FlowRate;
                    pck.CreateFeature(shell.MapAppManager.Map.Projection, prj.Project.GeoSpatialDirectory);
                    pck.BuildTopology();
                    pck.IsDirty = true;
                    pck.Save(null);
                    pck.ChangeState(Models.Generic.ModelObjectState.Ready);
                }
                else
                {
                    pck.ChangeState(Models.Generic.ModelObjectState.Standby);
                    cancelProgressHandler.Progress("Package_Tool", 100, "Warning: no points located in the modeling domain.");
                }
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Error message: Modflow is used by this tool.");
                return(false);
            }
        }
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="ras">The input altitude raster.</param>
        /// <param name="inZFactor">A multiplicative scaling factor to be applied to the elevation values before calculating the slope.</param>
        /// <param name="slopeInPercent">If this is true, the slope is returned as a percentage.</param>
        /// <param name="result">The output slope raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        private static void Slope(IRaster ras, double inZFactor, bool slopeInPercent, IRaster result, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || result == null)
            {
                return;
            }

            try
            {
                int noOfCol = ras.NumColumns;
                int noOfRow = ras.NumRows;

                // Create the new raster with the appropriate dimensions
                IRaster temp = Raster.CreateRaster("SlopeRaster.bgd", string.Empty, noOfCol, noOfRow, 1, typeof(double), new[] { string.Empty });
                temp.NoDataValue = ras.NoDataValue;
                temp.Bounds      = ras.Bounds;

                for (int i = 0; i < temp.NumRows; i++)
                {
                    for (int j = 0; j < temp.NumColumns; j++)
                    {
                        if (i > 0 && i < temp.NumRows - 1 && j > 0 && j < temp.NumColumns - 1)
                        {
                            double z1 = ras.Value[i - 1, j - 1];
                            double z2 = ras.Value[i - 1, j];
                            double z3 = ras.Value[i - 1, j + 1];
                            double z4 = ras.Value[i, j - 1];
                            double z5 = ras.Value[i, j + 1];
                            double z6 = ras.Value[i + 1, j - 1];
                            double z7 = ras.Value[i + 1, j];
                            double z8 = ras.Value[i + 1, j + 1];

                            // 3rd Order Finite Difference slope algorithm
                            double dZdX = inZFactor * ((z3 - z1) + 2 * (z5 - z4) + (z8 - z6)) / (8 * ras.CellWidth);
                            double dZdY = inZFactor * ((z1 - z6) + 2 * (z2 - z7) + (z3 - z8)) / (8 * ras.CellHeight);

                            double slope = Math.Atan(Math.Sqrt((dZdX * dZdX) + (dZdY * dZdY))) * (180 / Math.PI);

                            // change to radious and in persentage
                            if (slopeInPercent)
                            {
                                slope = Math.Tan(slope * Math.PI / 180) * 100;
                            }

                            temp.Value[i, j] = slope;

                            if (cancelProgressHandler.Cancel)
                            {
                                return;
                            }
                        }
                        else
                        {
                            temp.Value[i, j] = temp.NoDataValue;
                        }

                        if (cancelProgressHandler.Cancel)
                        {
                            return;
                        }
                    }
                }

                result = temp;
                if (result.IsFullyWindowed())
                {
                    result.Save();
                }
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.ToString());
            }
        }
Example #43
0
        public bool Execute(
            IFeatureSet input, double tolerance, IFeatureSet output,
            ICancelProgressHandler cancelProgressHandler)
        {
            if (input == null || output == null)
            {
                return(false);
            }

            // 复制表
            foreach (DataColumn inputColumn in input.DataTable.Columns)
            {
                output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType));
            }

            int numTotalOldPoints = 0;
            int numTotalNewPoints = 0;

            for (int j = 0; j < input.Features.Count; j++)
            {
                int numOldPoints = 0;
                int numNewPoints = 0;

                Geometry geom = input.Features[j].BasicGeometry as Geometry;
                if (geom != null)
                {
                    numOldPoints = geom.NumPoints;
                }

                numTotalOldPoints += numOldPoints;
                if (geom != null)
                {
                    for (int part = 0; part < geom.NumGeometries; part++)
                    {
                        Geometry geomPart = (Geometry)geom.GetGeometryN(part);

                        // 简化
                        IList <Coordinate> oldCoords = geomPart.Coordinates;
                        IList <Coordinate> newCoords = DouglasPeuckerLineSimplifier.Simplify(
                            oldCoords, tolerance);

                        // coordinates -> geometry
                        Geometry newGeom = new LineString(newCoords);
                        numNewPoints      += newGeom.NumPoints;
                        numTotalNewPoints += numNewPoints;
                        Feature newFeature = new Feature(newGeom, output);
                        foreach (DataColumn colSource in input.DataTable.Columns)
                        {
                            newFeature.DataRow[colSource.ColumnName] = input.Features[j].DataRow[colSource.ColumnName];
                        }
                    }
                }

                cancelProgressHandler.Progress(
                    string.Empty,
                    Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(input.Features.Count)) * 100),
                    numOldPoints + "-->" + numNewPoints);
                if (cancelProgressHandler.Cancel)
                {
                    return(false);
                }
            }

            cancelProgressHandler.Progress(
                string.Empty,
                100,
                "Old / Processed number of points:" + numTotalOldPoints + "/"
                + numTotalNewPoints);

            output.Save();
            return(true);
        }
Example #44
0
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="source">The input altitude raster.</param>
        /// <param name="baseValue">The double precision base value.</param>
        /// <param name="binSize">The double size of the output bin.</param>
        /// <param name="result">The output slope raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>True if the method worked.</returns>
        public bool Execute(IRaster source, double baseValue, double binSize, IRaster result, ICancelProgressHandler cancelProgressHandler)
        {
            RasterBin rasterBin = new RasterBin
            {
                BaseValue = baseValue,
                BinSize   = binSize
            };

            try
            {
                return(rasterBin.BinRaster(source, result.Filename, cancelProgressHandler));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("The Execute method failed for RasterBin tool: " + ex.Message);
                MessageBox.Show(TextStrings.RasterBinTool_Execute_FailedToCompleteSuccessfully);
                return(false);
            }
        }
Example #45
0
        private void CreateUniqueCategories(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler)
        {
            Breaks = GetUniqueValues(fieldName, source, progressHandler);

            string fieldExpression = "[" + fieldName.ToUpper() + "]";

            ClearCategories();

            bool isStringField = CheckFieldType(fieldName, source);

            ProgressMeter pm = new ProgressMeter(progressHandler, "Building Feature Categories", Breaks.Count);

            List <double> sizeRamp  = GetSizeSet(Breaks.Count);
            List <Color>  colorRamp = GetColorSet(Breaks.Count);

            for (int colorIndex = 0; colorIndex < Breaks.Count; colorIndex++)
            {
                Break brk = Breaks[colorIndex];
                //get the color for the category
                Color            randomColor = colorRamp[colorIndex];
                double           size        = sizeRamp[colorIndex];
                IFeatureCategory cat         = CreateNewCategory(randomColor, size) as IFeatureCategory;
                if (cat != null)
                {
                    //cat.SelectionSymbolizer = _selectionSymbolizer.Copy();
                    cat.LegendText = brk.Name;
                    if (isStringField)
                    {
                        cat.FilterExpression = fieldExpression + "= '" + brk.Name.Replace("'", "''") + "'";
                    }
                    else
                    {
                        cat.FilterExpression = fieldExpression + "=" + brk.Name;
                    }

                    AddCategory(cat);
                }

                colorIndex++;
                pm.CurrentValue = colorIndex;
            }
            pm.Reset();
        }
Example #46
0
 /// <summary>
 /// Clips a raster with a polygon feature.
 /// </summary>
 /// <param name="inputFileName">The input raster file.</param>
 /// <param name="polygon">The clipping polygon feature.</param>
 /// <param name="outputFileName">The output raster file.</param>
 /// <param name="cancelProgressHandler">Progress handler for reporting progress status and cancelling the operation.</param>
 /// <returns>The output clipped raster object.</returns>
 public static IRaster ClipRasterWithPolygon(string inputFileName, IFeature polygon, string outputFileName, ICancelProgressHandler cancelProgressHandler = null)
 {
     return(ClipRasterWithPolygon(polygon, Raster.Open(inputFileName), outputFileName, cancelProgressHandler));
 }
Example #47
0
        /// <summary>
        /// Gets a list of all unique values of the attribute field.
        /// </summary>
        private List <Break> GetUniqueValues(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler)
        {
            ArrayList lst;
            bool      hugeCountOk = false;

            if (_cachedUniqueValues.ContainsKey(fieldName))
            {
                lst = _cachedUniqueValues[fieldName];
            }
            else
            {
                lst = new ArrayList();
                AttributePager ap = new AttributePager(source, 5000);
                ProgressMeter  pm = new ProgressMeter(progressHandler, "Discovering Unique Values", source.NumRows());
                for (int row = 0; row < source.NumRows(); row++)
                {
                    object val = ap.Row(row)[fieldName] ?? "[NULL]";
                    if (val.ToString() == string.Empty)
                    {
                        val = "[NULL]";
                    }
                    if (lst.Contains(val))
                    {
                        continue;
                    }
                    lst.Add(val);
                    if (lst.Count > 1000 && !hugeCountOk)
                    {
                        CancelEventArgs args = new CancelEventArgs(true);
                        if (TooManyCategories != null)
                        {
                            TooManyCategories(this, args);
                        }
                        if (args.Cancel)
                        {
                            break;
                        }
                        hugeCountOk = true;
                    }
                    pm.CurrentValue = row;
                    if (progressHandler.Cancel)
                    {
                        break;
                    }
                }
                lst.Sort();
                if (lst.Count < EditorSettings.MaxSampleCount)
                {
                    _cachedUniqueValues[fieldName] = lst;
                }
            }

            List <Break> result = new List <Break>();

            if (lst != null)
            {
                foreach (object item in lst)
                {
                    result.Add(new Break(item.ToString()));
                }
            }
            return(result);
        }
Example #48
0
        /// <summary>
        /// Clips a raster with a polygon feature.
        /// </summary>
        /// <param name="polygon">The clipping polygon feature.</param>
        /// <param name="input">The input raster object.</param>
        /// <param name="outputFileName">the output raster file name.</param>
        /// <param name="cancelProgressHandler">Progress handler for reporting progress status and cancelling the operation.</param>
        /// <remarks>We assume there is only one part in the polygon.
        /// Traverses the raster with a vertical scan line from left to right, bottom to top.</remarks>
        /// <returns>The raster resulting from the clip operation.</returns>
        public static IRaster ClipRasterWithPolygon(IFeature polygon, IRaster input, string outputFileName, ICancelProgressHandler cancelProgressHandler = null)
        {
            // if the polygon is completely outside the raster
            if (!input.ContainsFeature(polygon))
            {
                return(input);
            }

            cancelProgressHandler?.Progress(16, "Retrieving the borders.");

            List <Border> borders = GetBorders(polygon);

            cancelProgressHandler?.Progress(33, "Copying raster.");

            // create output raster
            IRaster output = Raster.CreateRaster(outputFileName, input.DriverCode, input.NumColumns, input.NumRows, 1, input.DataType, new[] { string.Empty });

            output.Bounds      = input.Bounds.Copy();
            output.NoDataValue = input.NoDataValue;
            if (input.CanReproject)
            {
                output.Projection = input.Projection;
            }

            // set all initial values of Output to NoData
            for (int i = 0; i < output.NumRows; i++)
            {
                for (int j = 0; j < output.NumColumns; j++)
                {
                    output.Value[i, j] = output.NoDataValue;
                }
            }

            double xStart      = GetXStart(polygon, output);
            int    columnStart = GetStartColumn(polygon, output); // get the index of first column

            ProgressMeter pm = new ProgressMeter(cancelProgressHandler, "Clipping Raster", output.NumColumns)
            {
                StepPercent = 5, StartValue = 33
            };

            int col = 0;

            for (int columnCurrent = columnStart; columnCurrent < output.NumColumns; columnCurrent++)
            {
                var xCurrent = xStart + (col * output.CellWidth);

                var intersections = GetYIntersections(borders, xCurrent);
                intersections.Sort();
                ParseIntersections(intersections, xCurrent, columnCurrent, output, input);

                // update progess meter
                pm.CurrentValue = xCurrent;

                // update counter
                col++;

                // cancel if requested
                if (cancelProgressHandler != null && cancelProgressHandler.Cancel)
                {
                    return(null);
                }
            }

            output.Save();

            return(output);
        }
Example #49
0
        /// <summary>
        /// Gets the values from a file based data source rather than an in memory object.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="progressHandler"></param>
        public void GetValues(IAttributeSource source, ICancelProgressHandler progressHandler)
        {
            int pageSize = 100000;

            Values = new List <double>();
            string normField = EditorSettings.NormField;
            string fieldName = EditorSettings.FieldName;

            if (source.NumRows() < EditorSettings.MaxSampleCount)
            {
                int numPages = (int)Math.Ceiling((double)source.NumRows() / pageSize);
                for (int ipage = 0; ipage < numPages; ipage++)
                {
                    int       numRows = (ipage == numPages - 1) ? source.NumRows() % pageSize : pageSize;
                    DataTable table   = source.GetAttributes(ipage * pageSize, numRows);
                    if (!string.IsNullOrEmpty(EditorSettings.ExcludeExpression))
                    {
                        DataRow[] rows = table.Select("NOT (" + EditorSettings.ExcludeExpression + ")");
                        foreach (DataRow row in rows)
                        {
                            double val;
                            if (!double.TryParse(row[fieldName].ToString(), out val))
                            {
                                continue;
                            }
                            if (double.IsNaN(val))
                            {
                                continue;
                            }

                            if (normField != null)
                            {
                                double norm;
                                if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val))
                                {
                                    continue;
                                }
                                Values.Add(val / norm);
                                continue;
                            }
                            Values.Add(val);
                        }
                    }
                    else
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            double val;
                            if (!double.TryParse(row[fieldName].ToString(), out val))
                            {
                                continue;
                            }
                            if (double.IsNaN(val))
                            {
                                continue;
                            }

                            if (normField != null)
                            {
                                double norm;
                                if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val))
                                {
                                    continue;
                                }
                                Values.Add(val / norm);
                                continue;
                            }
                            Values.Add(val);
                        }
                    }
                }
            }
            else
            {
                Dictionary <int, double> randomValues = new Dictionary <int, double>();
                pageSize = 10000;
                int count = EditorSettings.MaxSampleCount;

                Random         rnd          = new Random();
                AttributePager ap           = new AttributePager(source, pageSize);
                int            countPerPage = count / ap.NumPages();
                ProgressMeter  pm           = new ProgressMeter(progressHandler, "Sampling " + count + " random values", count);
                for (int iPage = 0; iPage < ap.NumPages(); iPage++)
                {
                    for (int i = 0; i < countPerPage; i++)
                    {
                        double val;
                        double norm = 1;
                        int    index;
                        bool   failed = false;
                        do
                        {
                            index = rnd.Next(ap.StartIndex, ap.StartIndex + pageSize);
                            DataRow dr = ap.Row(index);
                            if (!double.TryParse(dr[fieldName].ToString(), out val))
                            {
                                failed = true;
                            }
                            if (normField == null)
                            {
                                continue;
                            }
                            if (!double.TryParse(dr[normField].ToString(), out norm))
                            {
                                failed = true;
                            }
                        } while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed);
                        if (normField != null)
                        {
                            Values.Add(val / norm);
                        }
                        else
                        {
                            Values.Add(val);
                        }
                        randomValues.Add(index, val);
                        pm.CurrentValue = i + iPage * countPerPage;
                    }
                    //Application.DoEvents();
                    if (progressHandler != null && progressHandler.Cancel)
                    {
                        break;
                    }
                }
            }
            Values.Sort();
            Statistics.Calculate(Values);
        }
        /// <summary>
        /// Finds the average slope in the given polygons with more user preferences.
        /// </summary>
        /// <param name="ras">The dem Raster(Grid file).</param>
        /// <param name="inZFactor">The scaler factor</param>
        /// <param name="slopeInPercent">The slope in percentage.</param>
        /// <param name="poly">The flow poly shapefile path.</param>
        /// <param name="fldInPolyToStoreSlope">The field name to store average slope in the attribute.</param>
        /// <param name="outerShpFile">The Featureset where we have the area of interest</param>
        /// <param name="outerShpIndex">The index of featureset which give paticular area of interest.</param>
        /// <param name="output">The path to save created slope Feature set.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns></returns>
        public bool Execute(
            IRaster ras,
            double inZFactor,
            bool slopeInPercent,
            IFeatureSet poly,
            string fldInPolyToStoreSlope,
            IFeatureSet outerShpFile,
            int outerShpIndex,
            IFeatureSet output,
            ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || poly == null || outerShpFile == null || output == null)
            {
                return(false);
            }

            if (poly.FeatureType != FeatureType.Polygon || outerShpFile.FeatureType != FeatureType.Polygon)
            {
                return(false);
            }

            int     previous  = 0;
            IRaster slopegrid = new Raster();

            int[]    areaCount = new int[poly.Features.Count];
            double[] areaTotal = new double[poly.Features.Count];
            double[] areaAve   = new double[poly.Features.Count];

            Slope(ras, inZFactor, slopeInPercent, slopegrid, cancelProgressHandler);
            if (slopegrid == null)
            {
                throw new SystemException(TextStrings.Slopegridfileisnull);
            }

            foreach (IFeature f in poly.Features)
            {
                output.Features.Add(f);
            }

            for (int i = 0; i < slopegrid.NumRows; i++)
            {
                int current = Convert.ToInt32(Math.Round(i * 100D / slopegrid.NumRows));

                // only update when increment in percentage
                if (current > previous + 5)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                    previous = current;
                }

                for (int j = 0; j < slopegrid.NumColumns; j++)
                {
                    Coordinate coordin = slopegrid.CellToProj(i, j);
                    IPoint     pt      = new Point(coordin);
                    IFeature   point   = new Feature(pt);
                    if (!outerShpFile.Features[outerShpIndex].Covers(point))
                    {
                        continue; // not found the point inside.
                    }

                    for (int c = 0; c < poly.Features.Count; c++)
                    {
                        if (output.Features[c].Covers(point))
                        {
                            areaCount[c]++;
                            areaTotal[c] += slopegrid.Value[i, j] / 100;
                        }

                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }
            }

            // Add the column
            output.DataTable.Columns.Add("FID", typeof(int));
            output.DataTable.Columns.Add(fldInPolyToStoreSlope, typeof(Double));
            for (int c = 0; c < output.Features.Count; c++)
            {
                if (areaCount[c] == 0)
                {
                    areaAve[c] = 0.0;
                }
                else
                {
                    areaAve[c] = areaTotal[c] / areaCount[c];
                }

                // Add the field values
                output.Features[c].DataRow["FID"] = c;
                output.Features[c].DataRow[fldInPolyToStoreSlope] = areaAve[c];
            }

            output.SaveAs(output.Filename, true);
            slopegrid.Close();
            ras.Close();
            return(true);
        }
Example #51
0
        /// <summary>
        /// Executes the ClipPolygonWithPolygon tool with programatic input
        /// </summary>
        /// <param name="input">The input feature set to clip</param>
        /// <param name="input2">The input polygon feature set to clip with</param>
        /// <param name="output">The output feature set</param>
        /// <param name="cancelProgressHandler">The progress handler for progress message updates</param>
        /// <returns></returns>
        /// Ping delete "static" for external testing
        public bool Execute(IFeatureSet input, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input == null || input2 == null || output == null)
            {
                cancelProgressHandler.Progress(string.Empty, 100, TextStrings.Oneparameterinnull);
                return(false);
            }

            if (input2.FeatureType != FeatureType.Polygon)
            {
                cancelProgressHandler.Progress(string.Empty, 100, TextStrings.secondinputlayer);
                return(false);
            }

            output.FeatureType = input.FeatureType;

            // we add all the old features to output
            IFeatureSet tempoutput = input.Intersection(input2, FieldJoinType.LocalOnly, cancelProgressHandler);

            // We add all the fields
            foreach (DataColumn inputColumn in tempoutput.DataTable.Columns)
            {
                output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType));
            }

            foreach (var fe in tempoutput.Features)
            {
                output.Features.Add(fe);
            }

            // Setting the AttributesPopulated to true here means the output shapefile will get attribute columns copied from
            // the source file. This problem occurs when using the ClipPolygonWithPolygon tool due to how the input/output files
            // are loaded. https://github.com/DotSpatial/DotSpatial/issues/892
            output.AttributesPopulated = true;

            output.SaveAs(output.Filename, true);
            return(true);
        }
        /// <summary>
        /// Executes the DP line simplefy tool programaticaly
        /// </summary>
        /// <param name="input">The input polygon feature set</param>
        /// <param name="tolerance">The tolerance to use when simplefiying</param>
        /// <param name="output">The output polygon feature set</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns></returns>
        public bool Execute(
            IFeatureSet input, double tolerance, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input == null || output == null)
            {
                return(false);
            }

            // We copy all the fields
            foreach (DataColumn inputColumn in input.DataTable.Columns)
            {
                output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType));
            }

            int numTotalOldPoints = 0;
            int numTotalNewPoints = 0;

            for (int j = 0; j < input.Features.Count; j++)
            {
                int numOldPoints = 0;
                int numNewPoints = 0;

                Geometry geom = input.Features[j].BasicGeometry as Geometry;
                if (geom != null)
                {
                    numOldPoints = geom.NumPoints;
                }

                numTotalOldPoints += numOldPoints;
                if (geom != null)
                {
                    for (int part = 0; part < geom.NumGeometries; part++)
                    {
                        Geometry geomPart = (Geometry)geom.GetGeometryN(part);

                        // do the simplification
                        IList <Coordinate> oldCoords = geomPart.Coordinates;
                        IList <Coordinate> newCoords = DouglasPeuckerLineSimplifier.Simplify(
                            oldCoords, tolerance);

                        // convert the coordinates back to a geometry
                        Geometry newGeom = new LineString(newCoords);
                        numNewPoints      += newGeom.NumPoints;
                        numTotalNewPoints += numNewPoints;
                        Feature newFeature = new Feature(newGeom, output);
                        foreach (DataColumn colSource in input.DataTable.Columns)
                        {
                            newFeature.DataRow[colSource.ColumnName] = input.Features[j].DataRow[colSource.ColumnName];
                        }
                    }
                }

                // Status updates is done here, shows number of old / new points
                cancelProgressHandler.Progress(
                    string.Empty,
                    Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(input.Features.Count)) * 100),
                    numOldPoints + "-->" + numNewPoints);
                if (cancelProgressHandler.Cancel)
                {
                    return(false);
                }
            }

            cancelProgressHandler.Progress(
                string.Empty,
                100,
                TextStrings.Originalnumberofpoints + numTotalOldPoints + " " + TextStrings.Newnumberofpoints
                + numTotalNewPoints);

            output.Save();
            return(true);
        }
Example #53
0
        /// <summary>
        /// Generates a new raster given the specified featureset.  Values will be given to
        /// each cell that coincide with the values in the specified field of the attribute
        /// table.  If the cellSize is 0, then it will be automatically calculated so that
        /// the smaller dimension (between width and height) is 256 cells.
        /// Ping Yang delete static for external testing 01/2010
        /// </summary>
        /// <param name="source">The featureset to convert into a vector format</param>
        /// <param name="cellSize">A double giving the geographic cell size.</param>
        /// <param name="fieldName">The string fieldName to use</param>
        /// <param name="output">The raster that will be created</param>
        /// <param name="cancelProgressHandler">A progress handler for handling progress messages</param>
        /// <returns></returns>
        public bool Execute(IFeatureSet source, double cellSize, string fieldName, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (source == null || output == null)
            {
                return(false);
            }

            output = VectorToRaster.ToRaster(source, cellSize, fieldName, output.Filename, string.Empty, new string[] { }, cancelProgressHandler);
            output.Save();
            return(true);
        }
Example #54
0
        public bool RasterMath(IRaster input1, IRaster input2, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input1 == null || input2 == null || output == null)
            {
                return(false);
            }

            // Figures out which raster has smaller cells
            var smallestCellRaster = input1.CellWidth < input2.CellWidth ? input1 : input2;
            var envelope           = UnionEnvelope(input1, input2);

            envelope.MinX = envelope.MinX + smallestCellRaster.CellWidth / 2;
            envelope.MinY = envelope.MinY - smallestCellRaster.CellHeight / 2;
            envelope.MaxX = envelope.MaxX + smallestCellRaster.CellWidth / 2;
            envelope.MaxY = envelope.MaxY - smallestCellRaster.CellHeight / 2;

            // Given the envelope of the two rasters we calculate the number of columns / rows
            int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / smallestCellRaster.CellWidth));
            int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / smallestCellRaster.CellHeight));

            // create output raster
            output = Raster.CreateRaster(
                output.Filename, string.Empty, noOfCol, noOfRow, 1, typeof(int), new[] { string.Empty });
            var bound = new RasterBounds(noOfRow, noOfCol, envelope);

            output.Bounds      = bound;
            output.NoDataValue = input1.NoDataValue;

            int previous = 0;
            int max      = output.Bounds.NumRows + 1;

            for (int i = 0; i < output.Bounds.NumRows; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    Coordinate cellCenter = output.CellToProj(i, j);
                    var        v1         = input1.ProjToCell(cellCenter);
                    double     val1;
                    if (v1.Row <= input1.EndRow && v1.Column <= input1.EndColumn && v1.Row > -1 && v1.Column > -1)
                    {
                        val1 = input1.Value[v1.Row, v1.Column];
                    }
                    else
                    {
                        val1 = input1.NoDataValue;
                    }

                    var    v2 = input2.ProjToCell(cellCenter);
                    double val2;
                    if (v2.Row <= input2.EndRow && v2.Column <= input2.EndColumn && v2.Row > -1 && v2.Column > -1)
                    {
                        val2 = input2.Value[v2.Row, v2.Column];
                    }
                    else
                    {
                        val2 = input2.NoDataValue;
                    }

                    if (val1 == input1.NoDataValue || val2 == input2.NoDataValue)
                    {
                        output.Value[i, j] = output.NoDataValue;
                    }
                    else
                    {
                        output.Value[i, j] = Operation(val1, val2);
                    }

                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }
                }

                int current = Convert.ToInt32(Math.Round(i * 100D / max));

                // only update when increment in persentage
                if (current > previous)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                }

                previous = current;
            }

            // output = Temp;
            output.Save();
            return(true);
        }
Example #55
0
        /// <summary>
        /// Erase features from one feature set where they are intersected by another feature set.
        /// </summary>
        /// <param name="targetFeatures">Features which will be erased in part or whole.</param>
        /// <param name="sourceFeatures">Features which represent areas to erase.</param>
        /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param>
        /// <returns>A point feature set with the randomly created features.</returns>
        public static FeatureSet EraseFeatures(IFeatureSet targetFeatures, IFeatureSet sourceFeatures, ICancelProgressHandler cancelProgressHandler = null)
        {
            if (targetFeatures == null || sourceFeatures == null)
            {
                return(null);
            }

            // Erase features from one feature set where they are intersected by another feature set
            // Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique.
            // The current version does not preserve any attribute info.
            // Dan Ames 2/27/2013
            FeatureSet resultFeatures = new FeatureSet();   // the resulting featureset

            resultFeatures.CopyTableSchema(targetFeatures); // set up the data table in the new feature set

            for (short i = 0; i <= targetFeatures.ShapeIndices.Count - 1; i++)
            {
                var tf = targetFeatures.GetFeature(i); // get the full undifferenced feature
                for (short j = 0; j <= sourceFeatures.ShapeIndices.Count - 1; j++)
                {
                    var sf = sourceFeatures.GetFeature(j);
                    if (sf.Geometry.Envelope.Intersects(tf.Geometry.Envelope))
                    {
                        tf = tf.Difference(sf.Geometry); // clip off any pieces of SF that overlap FR
                    }

                    if (tf == null)
                    {
                        // sometimes difference leaves nothing left of a feature
                        break;
                    }
                }

                if (tf != null)
                {
                    resultFeatures.AddFeature(tf.Geometry).CopyAttributes(targetFeatures.GetFeature(i)); // add the fully clipped feature to the results
                }

                if (cancelProgressHandler != null)
                {
                    if (cancelProgressHandler.Cancel)
                    {
                        return(null);
                    }

                    int progress = Convert.ToInt32(i * 100 / targetFeatures.ShapeIndices.Count);
                    cancelProgressHandler.Progress(progress, string.Empty);
                }
            }

            return(resultFeatures);
        }
Example #56
0
 /// <summary>
 /// Create polygons from raster.
 /// </summary>
 /// <param name="input">The Polygon Raster(Grid file).</param>
 /// <param name="output">The Polygon shapefile path.</param>
 /// <param name="cancelProgressHandler">The progress handler.</param>
 public bool Execute(IRaster input, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
 {
     return(Execute(input, null, output, cancelProgressHandler));
 }
Example #57
0
        /// <summary>
        /// Executes the Union Opaeration tool programaticaly
        /// </summary>
        /// <param name="self">The input are feature set</param>
        /// <param name="other">The second input feature set</param>
        /// <param name="output">The output feature set</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns></returns>
        public bool Execute(
            IFeatureSet self, IFeatureSet other, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (self == null || other == null || output == null)
            {
                return(false);
            }

            IFeatureSet tempOutput     = self.Intersection(other, FieldJoinType.All, null);
            IFeatureSet tempFeatureSet = self.CombinedFields(other);

            int previous = 0;
            int max      = self.Features.Count;

            // Take (Self-Intersect Featureset)
            List <IFeature> intersectList;

            for (int i = 0; i < self.Features.Count; i++)
            {
                intersectList = other.Select(self.Features[i].Envelope.ToExtent());
                foreach (IFeature feat in intersectList)
                {
                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }

                    self.Features[i].Difference(feat, tempFeatureSet, FieldJoinType.LocalOnly);
                }

                if (Math.Round(i * 40D / max) <= previous)
                {
                    continue;
                }

                previous = Convert.ToInt32(Math.Round(i * 40D / max));
                cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted);
            }

            max = other.Features.Count;

            // Take (Other-Intersect Featureset)
            for (int i = 0; i < other.Features.Count; i++)
            {
                intersectList = self.Select(other.Features[i].Envelope.ToExtent());
                foreach (IFeature feat in intersectList)
                {
                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }

                    other.Features[i].Difference(feat, tempFeatureSet, FieldJoinType.LocalOnly);
                }

                if (Math.Round((i * 40D / max) + 40D) <= previous)
                {
                    continue;
                }

                previous = Convert.ToInt32(Math.Round((i * 40D / max) + 40D));
                cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted);
            }

            max = tempFeatureSet.Features.Count;
            output.CopyTableSchema(tempFeatureSet);

            // Add the individual feature to output
            for (int i = 0; i < tempFeatureSet.Features.Count; i++)
            {
                output.Features.Add(tempFeatureSet.Features[i]);
                if (Math.Round((i * 10D / max) + 80D) <= previous)
                {
                    continue;
                }

                previous = Convert.ToInt32(Math.Round((i * 10D / max) + 80D));
                if (cancelProgressHandler.Cancel)
                {
                    return(false);
                }

                cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted);
            }

            max = tempOutput.Features.Count;

            // Add the Intersect feature to output
            for (int i = 0; i < tempOutput.Features.Count; i++)
            {
                output.Features.Add(tempOutput.Features[i]);
                if (cancelProgressHandler.Cancel)
                {
                    return(false);
                }

                if (Math.Round((i * 10D / max) + 90D) <= previous)
                {
                    continue;
                }

                previous = Convert.ToInt32(Math.Round((i * 10D / max) + 90D));
                cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted);
            }

            output.SaveAs(output.Filename, true);
            return(true);
        }
Example #58
0
        /// <summary>
        /// Create polygons from raster.
        /// </summary>
        /// <param name="input">The Polygon Raster(Grid file).</param>
        /// <param name="connectionGrid">Connection Grid.</param>
        /// <param name="output">The Polygon shapefile path.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        public bool Execute(IRaster input, IRaster connectionGrid, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
        {
            if (input == null || output == null)
            {
                return(false);
            }

            output.DataTable.Columns.Add("Value", typeof(double));

            var featureHash = new Dictionary <double, LineSegmentList>();
            var previous    = 0.0;

            var height = input.CellHeight;
            var width  = input.CellWidth;

            var xMin = input.Xllcenter - width / 2.0;
            var yMin = input.Yllcenter - height / 2.0;
            var xMax = xMin + width * input.NumColumns;
            var yMax = yMin + height * input.NumRows;

            var numRows    = input.NumRows;
            var numColumns = input.NumColumns;

            Func <int, int, double, bool> same = (y, x, value) => y >= 0 && y < numRows &&
                                                 x >= 0 && x < numColumns &&
                                                 input.Value[y, x] == value;
            Func <int, int, double> get = (y, x) => y >= 0 && y < numRows && x >= 0 && x < numColumns
                                                       ? input.Value[y, x]
                                                       : input.NoDataValue;
            Func <int, int, int, int, bool> eqValues = (y1, x1, y2, x2) => get(y1, x1) == get(y2, x2);

            var enableCon = connectionGrid != null;
            Func <int, int, int> connection = (y, x) => enableCon ? (int)connectionGrid.Value[y, x] : 0;

            for (int y = 0; y < numRows; y++)
            {
                int current = Convert.ToInt32((y * 100.0) / input.NumRows);
                if (current > previous)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                    previous = current;
                }

                Debug.WriteLine("Row : " + y + " done.");
                for (int x = 0; x < numColumns; x++)
                {
                    var value = input.Value[y, x];
                    if (value == input.NoDataValue)
                    {
                        continue;
                    }

                    LineSegmentList lineList;
                    if (!featureHash.TryGetValue(value, out lineList))
                    {
                        lineList = new LineSegmentList();
                        featureHash.Add(value, lineList);
                    }

                    var curCon = connection(y, x);

                    /*
                     * 6 7 8
                     * 5 0 1
                     * 4 3 2
                     * current cell (x,y)=0
                     */

                    var con_7 = same(y + 1, x, value);
                    var con_5 = same(y, x - 1, value);
                    var con_3 = same(y - 1, x, value);
                    var con_1 = same(y, x + 1, value);

                    var con_8l = enableCon &&
                                 same(y + 1, x + 1, value) && !con_7 &&
                                 (curCon == 8 || connection(y + 1, x + 1) == 4);
                    var con_8r = enableCon &&
                                 same(y + 1, x + 1, value) && !con_1 &&
                                 (curCon == 8 || connection(y + 1, x + 1) == 4);

                    var con_6l = enableCon &&
                                 same(y + 1, x - 1, value) && !con_5 &&
                                 (curCon == 6 || connection(y + 1, x - 1) == 2);
                    var con_6r = enableCon &&
                                 same(y + 1, x - 1, value) && !con_7 &&
                                 (curCon == 6 || connection(y + 1, x - 1) == 2);

                    var con_4l = enableCon &&
                                 same(y - 1, x - 1, value) && !con_5 &&
                                 (curCon == 4 || connection(y - 1, x - 1) == 8);
                    var con_4r = enableCon &&
                                 same(y - 1, x - 1, value) && !con_3 &&
                                 (curCon == 4 || connection(y - 1, x - 1) == 8);

                    var con_2l = enableCon &&
                                 same(y - 1, x + 1, value) && !con_3 &&
                                 (curCon == 2 || connection(y - 1, x + 1) == 6);
                    var con_2r = enableCon &&
                                 same(y - 1, x + 1, value) && !con_1 &&
                                 (curCon == 2 || connection(y - 1, x + 1) == 6);

                    /* Cell points:
                     * tl tc tr
                     * cl    cr
                     * bl bc br
                     */
                    var tl = new Coordinate(xMin + x * width, yMax - (y + 1) * height);
                    var tc = new Coordinate(xMin + (x + 0.5) * width, yMax - (y + 1) * height);
                    var tr = new Coordinate(xMin + (x + 1) * width, yMax - (y + 1) * height);
                    var cl = new Coordinate(xMin + x * width, yMax - (y + 0.5) * height);
                    var cr = new Coordinate(xMin + (x + 1) * width, yMax - (y + 0.5) * height);
                    var bl = new Coordinate(xMin + x * width, yMax - y * height);
                    var bc = new Coordinate(xMin + (x + 0.5) * width, yMax - y * height);
                    var br = new Coordinate(xMin + (x + 1) * width, yMax - y * height);

                    /*
                     * Cell edges:
                     * e_tl   e_tr
                     * ----|----
                     * e_lt  |       | e_rt
                     * -       -
                     * e_lb  |       | e_rb
                     * ----|----
                     * e_bl   e_br
                     */

                    bool e_tr = false,
                         e_tl = false,
                         e_lt = false,
                         e_lb = false,
                         e_rt = false,
                         e_rb = false,
                         e_br = false,
                         e_bl = false;

                    if (!con_7)
                    {
                        #region Check Cell 7

                        // top: right half
                        if (!con_8l)
                        {
                            var a1 = con_6r && con_1;
                            var a2 = !con_8r && !con_6l && con_4l && !con_2r;
                            e_tr = a1 || a2;
                        }

                        // top: left half
                        if (!con_6r)
                        {
                            var a1 = con_8l && con_5;
                            var a2 = !con_8r && !con_6l && !con_4l && con_2r;
                            e_tl = a1 || a2;
                        }

                        // top: full
                        if (!con_8l && !con_6r && !con_4l && !con_2r)
                        {
                            e_tr = e_tl = true;
                        }

                        #endregion
                    }

                    if (!con_3)
                    {
                        #region Check Cell 3

                        // bottom: left half
                        if (!con_4r)
                        {
                            var a1 = con_2l && con_5;
                            var a2 = !con_2r && !con_4l && !con_6l && con_8r;
                            e_bl = a1 || a2;
                        }

                        // bottom: right half
                        if (!con_2l)
                        {
                            var a1 = con_4r && con_1;
                            var a2 = !con_2r && !con_4l && !con_8r && con_6l;
                            e_br = a1 || a2;
                        }

                        // bottom: full
                        if (!con_4r && !con_2l && !con_8r && !con_6l)
                        {
                            e_bl = e_br = true;
                        }

                        #endregion
                    }

                    if (!con_1)
                    {
                        #region Check Cell 1

                        // right: bottom half
                        if (!con_2r)
                        {
                            var a1 = con_8r && con_3;
                            var a2 = !con_2l && !con_8l && !con_4r && con_6r;
                            e_rb = a1 || a2;
                        }

                        // right: top half
                        if (!con_8r)
                        {
                            var a1 = con_2r && con_7;
                            var a2 = !con_2l && !con_8l && !con_6r && con_4r;
                            e_rt = a1 || a2;
                        }

                        // right: full
                        if (!con_2r && !con_8r && !con_4r && !con_6r)
                        {
                            e_rb = e_rt = true;
                        }

                        #endregion
                    }

                    if (!con_5)
                    {
                        #region Check Cell 5

                        // left: bottom half
                        if (!con_4l)
                        {
                            var a1 = con_3 && con_6l;
                            var a2 = !con_6r && !con_4r && con_8l && !con_2l;
                            e_lb = a1 || a2;
                        }

                        // left: top half
                        if (!con_6l)
                        {
                            var a1 = con_4l && con_7;
                            var a2 = !con_6r && !con_4r && !con_8l && con_2l;
                            e_lt = a1 || a2;
                        }

                        // left: full
                        if (!con_4l && !con_6l && !con_8l && !con_2l)
                        {
                            e_lb = e_lt = true;
                        }

                        #endregion
                    }

                    // Smooth boundaries regarding to outer cells
                    // Right top corner
                    if (e_tr && e_rt)
                    {
                        if (eqValues(y + 1, x, y, x + 1))
                        {
                            var a1 = connection(y + 1, x);
                            var a2 = connection(y, x + 1);
                            if ((a1 == 6 || a1 == 2 || a2 == 6 || a2 == 2) && !(a1 == 6 && a2 == 2))
                            {
                                lineList.AddSegment(tc, cr);
                                e_tr = e_rt = false;
                            }
                        }
                    }

                    // Left top corner
                    if (e_tl && e_lt)
                    {
                        if (eqValues(y, x - 1, y + 1, x))
                        {
                            var a1 = connection(y, x - 1);
                            var a2 = connection(y + 1, x);
                            if ((a1 == 8 || a1 == 4 || a2 == 8 || a2 == 4) && !(a1 == 8 && a2 == 4))
                            {
                                lineList.AddSegment(tc, cl);
                                e_tl = e_lt = false;
                            }
                        }
                    }

                    // Left bottom corner
                    if (e_bl && e_lb)
                    {
                        if (eqValues(y - 1, x, y, x - 1))
                        {
                            var a1 = connection(y - 1, x);
                            var a2 = connection(y, x - 1);
                            if ((a1 == 6 || a1 == 2 || a2 == 6 || a2 == 2) && !(a1 == 6 && a2 == 2))
                            {
                                lineList.AddSegment(cl, bc);
                                e_bl = e_lb = false;
                            }
                        }
                    }

                    // Right bottom corner
                    if (e_br && e_rb)
                    {
                        if (eqValues(y, x + 1, y - 1, x))
                        {
                            var a1 = connection(y, x + 1);
                            var a2 = connection(y - 1, x);
                            if ((a1 == 8 || a1 == 4 || a2 == 8 || a2 == 4) && !(a1 == 8 && a2 == 4))
                            {
                                lineList.AddSegment(bc, cr);
                                e_br = e_rb = false;
                            }
                        }
                    }

                    // Smooth boundaries regarding direction of current cell
                    switch (curCon)
                    {
                    case 2:
                    case 6:
                        if (e_tr && e_rt)
                        {
                            lineList.AddSegment(tc, cr);
                            e_tr = e_rt = false;
                        }
                        if (e_bl && e_lb)
                        {
                            lineList.AddSegment(bc, cl);
                            e_bl = e_lb = false;
                        }
                        break;

                    case 4:
                    case 8:
                        if (e_tl && e_lt)
                        {
                            lineList.AddSegment(cl, tc);
                            e_tl = e_lt = false;
                        }
                        if (e_br && e_rb)
                        {
                            lineList.AddSegment(cr, bc);
                            e_br = e_rb = false;
                        }
                        break;
                    }

                    // Add remaining edges
                    // Top
                    if (e_tl && e_tr)
                    {
                        lineList.AddSegment(tl, tr);
                    }
                    else if (e_tl)
                    {
                        lineList.AddSegment(tl, tc);
                    }
                    else if (e_tr)
                    {
                        lineList.AddSegment(tc, tr);
                    }

                    //Left
                    if (e_lt && e_lb)
                    {
                        lineList.AddSegment(tl, bl);
                    }
                    else if (e_lt)
                    {
                        lineList.AddSegment(tl, cl);
                    }
                    else if (e_lb)
                    {
                        lineList.AddSegment(cl, bl);
                    }

                    // Bottom
                    if (e_bl && e_br)
                    {
                        lineList.AddSegment(bl, br);
                    }
                    else if (e_bl)
                    {
                        lineList.AddSegment(bl, bc);
                    }
                    else if (e_br)
                    {
                        lineList.AddSegment(bc, br);
                    }

                    // Right
                    if (e_rt && e_rb)
                    {
                        lineList.AddSegment(tr, br);
                    }
                    else if (e_rt)
                    {
                        lineList.AddSegment(tr, cr);
                    }
                    else if (e_rb)
                    {
                        lineList.AddSegment(cr, br);
                    }

                    // Right top out diagonals
                    if (con_8l)
                    {
                        lineList.AddSegment(tc, new Coordinate(xMin + (x + 1) * width, yMax - (y + 1 + 0.5) * height));
                    }
                    if (con_8r)
                    {
                        lineList.AddSegment(cr, new Coordinate(xMin + (x + 1 + 0.5) * width, yMax - (y + 1) * height));
                    }

                    // Right in diagonals
                    if (con_4l || con_8l)
                    {
                        if (!con_6r && !con_6l && !con_7 && !con_5)
                        {
                            lineList.AddSegment(tc, cl);
                        }
                    }
                    if (con_4r || con_8r)
                    {
                        if (!con_2r && !con_2l && !con_1 && !con_3)
                        {
                            lineList.AddSegment(cr, bc);
                        }
                    }

                    // Left Top out diagonals
                    if (con_6r)
                    {
                        lineList.AddSegment(tc, new Coordinate(xMin + x * width, yMax - (y + 1 + 0.5) * height));
                    }
                    if (con_6l)
                    {
                        lineList.AddSegment(cl, new Coordinate(xMin + (x - 0.5) * width, yMax - (y + 1) * height));
                    }

                    // Left In diagonals
                    if (con_6r || con_2r)
                    {
                        if (!con_8r && !con_8l && !con_7 && !con_1)
                        {
                            lineList.AddSegment(tc, cr);
                        }
                    }
                    if (con_6l || con_2l)
                    {
                        if (!con_4r && !con_4l && !con_5 && !con_3)
                        {
                            lineList.AddSegment(cl, bc);
                        }
                    }

                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }
                }
            }

            foreach (var pair in featureHash)
            {
#if DEBUG
                var sw = new Stopwatch();
                sw.Start();
#endif
                var key         = pair.Key;
                var lineSegList = pair.Value.List;

                var polyList = new List <Polygon>();
                var ind      = 0;
                while (ind != lineSegList.Count)
                {
                    var polyShell = new List <Coordinate>();

                    var start = lineSegList[ind++];
                    polyShell.Add(start.P0);
                    polyShell.Add(start.P1);

                    while (!polyShell[0].Equals2D(polyShell[polyShell.Count - 1]))
                    {
                        var         last    = polyShell[polyShell.Count - 1];
                        LineSegment segment = null;
                        for (int i = ind; i < lineSegList.Count; i++)
                        {
                            var cur = lineSegList[i];
                            if (cur.P0.Equals2D(last) || cur.P1.Equals2D(last))
                            {
                                segment = cur;
                                if (ind != i)
                                {
                                    var swap = lineSegList[ind];
                                    lineSegList[ind] = cur;
                                    lineSegList[i]   = swap;
                                }

                                ind++;
                                break;
                            }
                        }
                        Debug.Assert(segment != null);
                        polyShell.Add(segment.P0.Equals2D(last) ? segment.P1 : segment.P0);
                    }

                    polyList.Add(new Polygon(polyShell));
                }

                var geometry = polyList.Count == 1
                                   ? (IBasicGeometry)polyList[0]
                                   : new MultiPolygon(polyList.ToArray());
                var f = output.AddFeature(geometry);
                f.DataRow["Value"] = key;

#if DEBUG
                sw.Stop();
                Debug.WriteLine(sw.ElapsedMilliseconds);
#endif
            }

            output.AttributesPopulated = true;
            output.Save();
            return(true);
        }
Example #59
0
        /// <summary>
        /// Finds the average slope in the given polygons.
        /// </summary>
        /// <param name="ras">The dem Raster(Grid file).</param>
        /// <param name="zFactor">The scaler factor.</param>
        /// <param name="poly">The flow poly shapefile path.</param>
        /// <param name="output">The resulting DEM of slopes.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>True, if executed successfully.</returns>
        public bool Execute(IRaster ras, double zFactor, IFeatureSet poly, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || poly == null || output == null)
            {
                return(false);
            }

            output.FeatureType = poly.FeatureType;
            foreach (IFeature f in poly.Features)
            {
                output.Features.Add(f);
            }

            output.DataTable.Columns.Add("FID", typeof(int));
            output.DataTable.Columns.Add(TextStrings.AveSlope, typeof(double));

            IRaster slopeGrid = new Raster
            {
                DataType = ras.DataType,
                Bounds   = ras.Bounds
            };

            // FeatureSet polyShape = new FeatureSet();
            int previous = 0;

            if (Slope(ref ras, zFactor, false, ref slopeGrid, cancelProgressHandler) == false)
            {
                return(false);
            }

            int shapeCount = output.Features.Count;

            int[]    areaCount = new int[shapeCount];
            double[] areaTotal = new double[shapeCount];
            double[] areaAve   = new double[shapeCount];
            double   dxHalf    = slopeGrid.CellWidth / 2;
            double   dyHalf    = slopeGrid.CellHeight / 2;

            // check whether those two envelope are intersect
            if (ras.Extent.Intersects(output.Extent) == false)
            {
                return(false);
            }

            RcIndex start = slopeGrid.ProjToCell(output.Extent.MinX, output.Extent.MaxY);
            RcIndex stop  = slopeGrid.ProjToCell(output.Extent.MaxX, output.Extent.MinY);

            int rowStart = start.Row;
            int colStart = start.Column;
            int rowStop  = stop.Row;
            int colStop  = stop.Column;

            for (int row = rowStart - 1; row < rowStop + 1; row++)
            {
                int current = Convert.ToInt32((row - rowStart + 1) * 100.0 / (rowStop + 1 - rowStart + 1));

                // only update when increment in percentage
                if (current > previous + 5)
                {
                    cancelProgressHandler.Progress(current, current + TextStrings.progresscompleted);
                    previous = current;
                }

                for (int col = colStart - 1; col < colStop + 1; col++)
                {
                    Coordinate cent  = slopeGrid.CellToProj(row, col);
                    double     xCent = cent.X;
                    double     yCent = cent.Y;
                    for (int shpindx = 0; shpindx < output.Features.Count; shpindx++)
                    {
                        IFeature tempFeat = output.Features[shpindx];
                        NtsPoint pt1      = new(xCent, yCent);
                        NtsPoint pt2      = new(xCent - dxHalf, yCent - dyHalf);
                        NtsPoint pt3      = new(xCent + dxHalf, yCent - dyHalf);
                        NtsPoint pt4      = new(xCent + dxHalf, yCent + dyHalf);
                        NtsPoint pt5      = new(xCent - dxHalf, yCent + dyHalf);
                        if ((((!tempFeat.Geometry.Covers(pt1) && !tempFeat.Geometry.Covers(pt2)) && !tempFeat.Geometry.Covers(pt3)) && !tempFeat.Geometry.Covers(pt4)) && !tempFeat.Geometry.Covers(pt5))
                        {
                            continue;
                        }

                        areaCount[shpindx]++;
                        areaTotal[shpindx] += slopeGrid.Value[row, col] / 100;

                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }
            }

            for (int shpindx = 0; shpindx < output.Features.Count; shpindx++)
            {
                if (areaCount[shpindx] == 0)
                {
                    areaAve[shpindx] = 0;
                }
                else
                {
                    areaAve[shpindx] = areaTotal[shpindx] / areaCount[shpindx];
                }

                output.Features[shpindx].DataRow["FID"] = shpindx;
                output.Features[shpindx].DataRow[TextStrings.AveSlope] = areaAve[shpindx];
            }

            poly.Close();
            slopeGrid.Close();
            output.SaveAs(output.Filename, true);
            return(true);
        }
Example #60
0
        /// <summary>
        /// Finds the average slope in the given polygons.
        /// Ping delete static for external testing
        /// </summary>
        /// <param name="input">The Polygon Raster(Grid file).</param>
        /// <param name="output">The Polygon shapefile path.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        public bool Execute(IRaster input, IFeatureSet output, ICancelProgressHandler cancelProgressHandler)
        {
            if ((input == null) || (output == null))
            {
                return(false);
            }

            output.DataTable.Columns.Add("Value", typeof(double));

            Hashtable featureHash = new Hashtable();
            double    previous    = 0.0;
            double    height      = input.CellHeight;
            double    width       = input.CellWidth;
            int       numRows     = input.NumRows;
            int       numColumns  = input.NumColumns;
            double    xMin        = input.Xllcenter - (input.CellWidth / 2.0);
            double    yMin        = input.Yllcenter - (input.CellHeight / 2.0);
            double    xMax        = xMin + (height * input.NumColumns);
            double    yMax        = yMin + (width * input.NumRows);

            for (int y = 0; y < numRows; y++)
            {
                int current = Convert.ToInt32((y * 100.0) / input.NumRows);
                if (current > previous)
                {
                    cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted);
                    previous = current;
                }

                Debug.WriteLine("Row : " + y + " done.");
                for (int x = 0; x < numColumns; x++)
                {
                    double             value    = input.Value[y, x];
                    List <LineSegment> lineList = new List <LineSegment>();
                    if (!featureHash.Contains(value))
                    {
                        featureHash.Add(value, lineList);
                    }
                    else
                    {
                        lineList = featureHash[value] as List <LineSegment>;
                    }

                    if (y == 0)
                    {
                        if (lineList != null)
                        {
                            lineList.Add(
                                new LineSegment(
                                    new Coordinate((x * width) + xMin, yMax),
                                    new Coordinate(((x + 1) * width) + xMin, yMax)));
                            if (input.Value[y + 1, x] != value)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate((x * width) + xMin, yMax - height),
                                        new Coordinate(((x + 1) * width) + xMin, yMax - height)));
                            }
                        }
                    }
                    else if (y == (numRows - 1))
                    {
                        if (lineList != null)
                        {
                            lineList.Add(
                                new LineSegment(
                                    new Coordinate((x * width) + xMin, yMin),
                                    new Coordinate(((x + 1) * width) + xMin, yMin)));
                            if (input.Value[y - 1, x] != value)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate((x * width) + xMin, yMin + height),
                                        new Coordinate(((x + 1) * width) + xMin, yMin + height)));
                            }
                        }
                    }
                    else
                    {
                        if (input.Value[y + 1, x] != value)
                        {
                            if (lineList != null)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate((x * width) + xMin, yMax - ((y + 1) * height)),
                                        new Coordinate(((x + 1) * width) + xMin, yMax - ((y + 1) * height))));
                            }
                        }

                        if (input.Value[y - 1, x] != value)
                        {
                            if (lineList != null)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate((x * width) + xMin, yMax - (y * height)),
                                        new Coordinate(((x + 1) * width) + xMin, yMax - (y * height))));
                            }
                        }
                    }

                    if (x == 0)
                    {
                        if (lineList != null)
                        {
                            lineList.Add(
                                new LineSegment(
                                    new Coordinate(xMin, yMax - (y * height)),
                                    new Coordinate(xMin, yMax - ((y + 1) * height))));
                            if (input.Value[y, x + 1] != value)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate(xMin + width, yMax - (y * height)),
                                        new Coordinate(xMin + width, yMax - ((y + 1) * height))));
                            }
                        }
                    }
                    else if (x == (numColumns - 1))
                    {
                        if (lineList != null)
                        {
                            lineList.Add(
                                new LineSegment(
                                    new Coordinate(xMax, yMax - (y * height)),
                                    new Coordinate(xMax, yMax - ((y + 1) * height))));
                            if (input.Value[y, x - 1] != value)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate(xMax - width, yMax - (y * height)),
                                        new Coordinate(xMax - width, yMax - ((y + 1) * height))));
                            }
                        }
                    }
                    else
                    {
                        if (input.Value[y, x + 1] != value)
                        {
                            if (lineList != null)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate(xMin + ((x + 1) * width), yMax - (y * height)),
                                        new Coordinate(xMin + ((x + 1) * width), yMax - ((y + 1) * height))));
                            }
                        }

                        if (input.Value[y, x - 1] != value)
                        {
                            if (lineList != null)
                            {
                                lineList.Add(
                                    new LineSegment(
                                        new Coordinate(xMin + (x * width), yMax - (y * height)),
                                        new Coordinate(xMin + (x * width), yMax - ((y + 1) * height))));
                            }
                        }
                    }

                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }
                }
            }

            Stopwatch sw = new Stopwatch();

            foreach (double key in featureHash.Keys)
            {
                sw.Reset();
                sw.Start();
                List <LineSegment> lineSegList = featureHash[key] as List <LineSegment>;
                if (lineSegList == null)
                {
                    break;
                }

                List <Polygon> polyList = new List <Polygon>();
                while (lineSegList.Count != 0)
                {
                    List <Coordinate> polyShell = new List <Coordinate>();
                    LineSegment       start     = lineSegList[0];
                    polyShell.Add(start.P0);
                    polyShell.Add(start.P1);
                    lineSegList.Remove(start);
                    while (!polyShell[0].Equals2D(polyShell[polyShell.Count - 1]))
                    {
                        LineSegment segment =
                            lineSegList.Find(
                                o =>
                                o.P0.Equals2D(polyShell[polyShell.Count - 1]) ||
                                o.P1.Equals2D(polyShell[polyShell.Count - 1]));
                        polyShell.Add(segment.P0.Equals2D(polyShell[polyShell.Count - 1]) ? segment.P1 : segment.P0);
                        lineSegList.Remove(segment);
                    }

                    polyList.Add(new Polygon(polyShell));
                }

                if (polyList.Count == 1)
                {
                    Feature feat = new Feature(polyList[0], output);
                    feat.DataRow["Value"] = key;
                }

                sw.Stop();
                Debug.WriteLine(sw.ElapsedMilliseconds);
            }

            output.Save();
            return(true);
        }