示例#1
0
        public IRaster Surface(IRaster raster)
        {
            int nr = raster.NumRows;
            int nc = raster.NumColumns;

            for (int row = 0; row < nr; row++)
            {
                for (int col = 0; col < nc; col++)
                {

                    raster.Value[row, col] = data[col, row];
                }
            }
            raster.Save();
            raster.Close();
            return raster;
        }
示例#2
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;
            }

            Extent envelope = UnionEnvelope(input1, input2);

            // Figures out which raster has smaller cells
            IRaster smallestCellRaster = input1.CellWidth < input2.CellWidth ? input1 : input2;

            // 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 });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope);
            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

            RcIndex v1;
            RcIndex v2;

            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);
                    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;
                    }

                    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 if (val1 != input1.NoDataValue && val2 == input2.NoDataValue)
                    {
                        output.Value[i, j] = output.NoDataValue;
                    }
                    else 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;
        }
        /// <summary>
        /// Executes the ReSample Opaeration tool programaticaly
        /// Ping deleted the static property for external testing
        /// </summary>
        /// <param name="input1">The input raster</param>
        /// <param name="oldCellSize">The size of the cells Hight</param>
        /// <param name="newCellSize">The size of the cells Width</param>
        /// <param name="output">The output raster</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns></returns>
        public bool Execute(IRaster input1, double newCellHeight, double newCellWidth, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (input1 == null || newCellWidth == 0 || output == null)
            {
                return false;
            }
            IEnvelope envelope = input1.Bounds.Envelope;

            //Calculate new number of columns and rows
            int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / newCellWidth));
            int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / newCellHeight));

            int previous = 0;

            //************OLD Method
            ////Create the new raster with the appropriate dimensions
            //Raster Temp = new Raster();
            ////Temp.CreateNew(output.Filename, noOfRow, noOfCol, input1.DataType);
            //Temp.CreateNew(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new string[] { "" });
            //Temp.CellWidth = newCellSize;
            //Temp.CellHeight = oldCellSize;
            //Temp.Xllcenter = input1.Bounds.Envelope.Minimum.X + (Temp.CellWidth / 2);
            //Temp.Yllcenter = input1.Bounds.Envelope.Minimum.Y + (Temp.CellHeight / 2);
            //***************

            //create output raster
            output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new[] { "" });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope);
            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

            RcIndex index1;

            //Loop throug every cell for new value
            int max = (output.Bounds.NumRows + 1);
            for (int i = 0; i < output.Bounds.NumRows; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    //Projet the cell position to Map
                    Coordinate cellCenter = output.CellToProj(i, j);
                    index1=input1.ProjToCell(cellCenter);

                    double val;
                    if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1)
                    {
                        if (input1.Value[index1.Row, index1.Column] == input1.NoDataValue)
                            val = output.NoDataValue;
                        else
                            val = input1.Value[index1.Row, index1.Column];
                    }
                    else
                        val = output.NoDataValue;

                    output.Value[i, j] = val;
                    
                    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("", current, current + TextStrings.progresscompleted);
                previous = current;
            }

            //output = Temp;
            output.Save();
            return true;
        }
示例#4
0
        /// <summary>
        /// This will resample the cells.
        /// If the cell size is zero, this will default to the shorter of the width or height
        /// divided by 256.
        /// </summary>
        /// <param name="input1">the input raster.</param>
        /// <param name="cellHeight">The new cell height or null.</param>
        /// <param name="cellWidth">The new cell width or null.</param>
        /// <param name="outputFileName">The string name of the output raster.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>The resampled raster.</returns>
        public static IRaster Resample(IRaster input1, double cellHeight, double cellWidth, string outputFileName,
                                       IProgressHandler progressHandler)
        {
            if (input1 == null)
            {
                return(null);
            }

            Extent envelope = input1.Bounds.Extent;

            if (cellHeight == 0)
            {
                cellHeight = envelope.Height / 256;
            }
            if (cellWidth == 0)
            {
                cellWidth = envelope.Width / 256;
            }

            //Calculate new number of columns and rows
            int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / cellWidth));
            int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / cellHeight));

            IRaster output = Raster.CreateRaster(outputFileName, string.Empty, noOfCol, noOfRow, 1, input1.DataType,
                                                 new[] { string.Empty });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope);

            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

            RcIndex       index1;
            int           max = (output.Bounds.NumRows);
            ProgressMeter pm  = new ProgressMeter(progressHandler, "ReSize Cells", max);

            //Loop through every cell for new value
            for (int i = 0; i < max; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    //Project the cell position to Map
                    Coordinate cellCenter = output.CellToProj(i, j);
                    index1 = input1.ProjToCell(cellCenter);

                    double val;
                    if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 &&
                        index1.Column > -1)
                    {
                        val = input1.Value[index1.Row, index1.Column] == input1.NoDataValue
                                  ? output.NoDataValue
                                  : input1.Value[index1.Row, index1.Column];
                    }
                    else
                    {
                        val = output.NoDataValue;
                    }
                    output.Value[i, j] = val;
                }
                pm.CurrentValue = i;
            }
            output.Save();
            pm.Reset();
            return(output);
        }
示例#5
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);
        }
示例#6
0
        /// <summary>
        /// Executes the RasterFromLAS tool.
        /// </summary>
        /// <param name="filenameLAS">The string filename of the LAS file to convert.</param>
        /// <param name="outputExtent">The extent of the output raster.</param>
        /// <param name="numRows">The integer number of rows of the output raster.</param>
        /// <param name="numColumns">The integer number of columns.</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(
            string filenameLAS,
            Extent outputExtent,
            int numRows,
            int numColumns,
            IRaster output,
            ICancelProgressHandler cancelProgressHandler)
        {
            // create output raster
            output = Raster.CreateRaster(
                output.Filename, string.Empty, numColumns, numRows, 1, typeof(int), new[] { string.Empty });
            RasterBounds bound = new RasterBounds(numRows, numColumns, outputExtent);
            output.Bounds = bound;

            output.NoDataValue = int.MinValue;

            ProgressMeter pm = new ProgressMeter(
                cancelProgressHandler,
                TextStrings.ConvertingLAS + filenameLAS + TextStrings.Progresstoraster + "...",
                numRows);

            for (int row = 0; row < numRows; row++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    // TO DO: PING CAN ADD LAS READING AND CELL ASSIGNMENT HERE
                    if (cancelProgressHandler.Cancel)
                    {
                        return false;
                    }
                }

                pm.CurrentValue = row;
            }

            // output = Temp;
            output.Save();
            return true;
        }
        /// <summary>
        /// Finds the average slope in the given polygons.
        /// </summary>
        /// <param name="poly">The Polygon.</param>
        /// <param name="output">The Raster.</param>
        /// <param name="progress">The progress handler.</param>
        public bool Execute(IFeatureSet poly, int noOfRow, int noOfCol, int selectionIndex, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (poly == null || output == null)
            {
                return false;
            }
            if (poly.FeatureType != FeatureTypes.Polygon)
                return false;

            //double CellSize = poly.Envelope.Width / 255;
            //int noOfRow = Convert.ToInt32(poly.Envelope.Height / CellSize);
            //int noOfCol = Convert.ToInt32(poly.Envelope.Width / CellSize);
            output=Raster.Create(output.Filename,"",noOfCol,noOfRow,1,typeof(int),new string[] { "" });

            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, poly.Envelope);

            output.Bounds=bound;

            output.NoDataValue = -1;
            int current, previous = 0;
            double area = 0.0, previousArea = 0.0;
            double hCellWidth = output.CellWidth / 2;
            double hCellHeight = output.CellHeight / 2;
            ICoordinate[] coordinateCell=new Coordinate[4];
            int polyIndex = -1;
            bool cover = false;
            //IEnvelope env=null;
            for (int i = 0; i < output.NumRows; i++)
            {
                current = Convert.ToInt32(i*100 / output.NumRows);
                //only update when increment in percentage
                if (current > previous+5)
                {
                    cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed");
                    previous = current;
                }

                for (int j = 0; j < output.NumColumns; j++)
                {
                    polyIndex = -1;
                    area = 0.0;
                    previousArea = 0.0;
                    cover=false;
                    ICoordinate cordinate=null;
                    cordinate = output.CellToProj(i, j);
                    //make the center of cell as point geometry
                    IPoint pt=new Point(cordinate);

                    for(int f=0;f<poly.Features.Count;f++)
                    {
                        if (selectionIndex == 0)
                        {
                            if (poly.Features[f].Covers(pt))
                            {
                                output.Value[i, j] = f;
                                cover = true;
                                break;
                            }
                            if (cancelProgressHandler.Cancel == true)
                                return false;
                        }
                        else //process area based selection
                        {
                            ICoordinate tempCo = new Coordinate(cordinate.X - hCellWidth, cordinate.Y - hCellHeight);
                            coordinateCell[0] = tempCo;
                            tempCo = new Coordinate(cordinate.X + hCellWidth, cordinate.Y - hCellHeight);
                            coordinateCell[1] = tempCo;
                            tempCo = new Coordinate(cordinate.X + hCellWidth, cordinate.Y + hCellHeight);
                            coordinateCell[2] = tempCo;
                            tempCo = new Coordinate(cordinate.X - hCellWidth, cordinate.Y + hCellHeight);
                            coordinateCell[3] = tempCo;

                            List<ICoordinate> ListCellCordinate = new List<ICoordinate>();
                            ListCellCordinate = coordinateCell.ToList<ICoordinate>();
                            IFeature cell = new Feature(FeatureTypes.Polygon, ListCellCordinate);
                            IFeature commonFeature=poly.Features[f].Intersection(cell);
                            if (commonFeature == null)
                                continue;
                            area=commonFeature.Area();
                            if (area > previousArea)
                            {
                                polyIndex = f;
                                cover = true;
                                previousArea = area;
                            }

                            if (cancelProgressHandler.Cancel == true)
                                return false;
                        }

                        
                    }
                    if (cover == true)
                    {
                        if (selectionIndex == 1)
                            output.Value[i, j] = polyIndex;
                    }
                    else
                        output.Value[i, j] = output.NoDataValue;
                }

            }
            //output.SaveAs(output.Filename);
            output.Save();
            //output.SaveAs(output.Filename);
            return true;
        }
示例#8
0
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="raster">The input altitude raster.</param>
        /// <param name="inZFactor">The double precision multiplicative scaling factor for elevation values.</param>
        /// <param name="slopeInPercent">A boolean parameter that clarifies the nature of the slope values.  If this is true, the values represent percent slope.</param>
        /// <param name="result">The output slope raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>A boolean value, true if the process was successful.</returns>
        public static bool GetSlope(IRaster raster, double inZFactor, bool slopeInPercent, ref IRaster result,
                                    ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (raster == null || result == null)
            {
                return false;
            }
            int noOfCol = raster.NumColumns;
            int noOfRow = raster.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 = raster.NoDataValue;
            temp.Bounds = raster.Bounds;
            temp.Projection = raster.Projection;

            ProgressMeter progMeter = null;
            try
            {
                if (cancelProgressHandler != null)
                    progMeter = new ProgressMeter(cancelProgressHandler, "Calculating Slope", temp.NumRows);

                for (int i = 0; i < temp.NumRows; i++)
                {

                    if (cancelProgressHandler != null)
                    {
                        progMeter.Next();
                        if ((i % 100) == 0)
                        {
                            progMeter.SendProgress();

                            // HACK: DoEvents messes up the normal flow of your application. 
                            System.Windows.Forms.Application.DoEvents();
                        }

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

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

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

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

                            temp.Value[i, j] = slope;

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

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

                result = temp;
                if (result.IsFullyWindowed())
                {
                    result.Save();
                    return true;
                }
                return false;
            }
            finally
            {
                if (progMeter != null)
                {
                    progMeter.Reset();
                    System.Windows.Forms.Application.DoEvents();
                }
            }
        }
示例#9
0
        /// <summary>
        /// Executes the Raster distance calculation
        /// Ping Yang deleted static for external testing 10/2010
        /// </summary>
        /// <param name="input">The input raster</param>
        /// <param name="output">The output raster</param>
        /// <param name="maxDistance">The maximum distance value. Cells with a larger distance to nearest
        /// target cell than maxDistance will be assigned 'no data' value.</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns>true if execution successful, false otherwise</returns>
        public bool Execute(IRaster input, IRaster output, double maxDistance, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input == null || output == null)
            {
                return false;
            }

            // Creates the output raster with the same bounds as the input
            RasterBounds bounds = (RasterBounds)input.Bounds.Copy();

            output = Raster.CreateRaster(
                output.Filename, string.Empty, bounds.NumColumns, bounds.NumRows, 1, typeof(int), new[] { string.Empty });

            // output.CreateNew(output.Filename, "", bounds.NumColumns, bounds.NumRows, 1, typeof(int), new string[] { "" });

            // output = Raster.CreateNewRaster(output.Filename, bounds.NumRows, bounds.NumColumns, RasterDataTypes.INTEGER);
            output.Bounds = bounds;

            // internally we reference output as an integer type raster.
            Raster<int> outRaster = output as Raster<int>;

            if (outRaster != null)
            {
                int numColumns = outRaster.NumColumns;
                int numRows = outRaster.NumRows;
                int lastUpdate = 0;

                // declare two jagged arrays for storing the (Rx, Ry) vectors.
                // rX is distance from current cell to nearest target cell measured in the x-direction
                // rY is distance from current cell to nearest target cell measured in the y-direction
                // the actual distance can be calculated as sqrt(rX^2 + rY^2).
                // in the resulting distance raster we store the squared distance as well as the rX, rY relative coordinates
                // to improve computation speed
                int[][] aRx = new int[numRows][];
                int[][] aRy = new int[numRows][];
                int[][] aSqDist = new int[numRows][];

                const int infD = int.MaxValue;
                const int targetVal = 0;

                // initialize the arrays
                for (int i = 0; i < numRows; i++)
                {
                    aRx[i] = new int[numColumns];
                    aRy[i] = new int[numColumns];
                    aSqDist[i] = new int[numColumns];
                    ReadInputRow(input, i, aSqDist[i], targetVal, infD);
                }

                // *******************************************************************
                // raster distance calculation pass one - top to bottom, left to right
                // *******************************************************************
                // int[] row1 = new int[numColumns];
                // int[] row2 = new int[numColumns];
                int[] aNcels = new int[4]; // the values of four neighbouring cells (W, NW, N, NE)
                int[] aDiff = new int[4]; // the | y coordinate distances to nearest target cell

                for (int row = 1; row < numRows; row++)
                {
                    ////read the row from input raster
                    // ReadInputRow(input, rowIndex, row2, targetVal, infD);

                    for (int col = 1; col < numColumns - 1; col++)
                    {
                        int val = aSqDist[row][col];

                        // Continue processing only if the current cell is not a target
                        if (val == targetVal)
                        {
                            continue;
                        }

                        // read the values of the cell's neighbours
                        aNcels[0] = aSqDist[row][col - 1]; // W
                        aNcels[1] = aSqDist[row - 1][col - 1]; // NW
                        aNcels[2] = aSqDist[row - 1][col]; // N
                        aNcels[3] = aSqDist[row - 1][col + 1]; // NE

                        // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell
                        aDiff[0] = (aNcels[0] < infD) ? aNcels[0] + 2 * aRx[row][col - 1] + 1 : infD;
                        aDiff[1] = (aNcels[1] < infD)
                                       ? aNcels[1] + 2 * (aRx[row - 1][col - 1] + aRy[row - 1][col - 1] + 1)
                                       : infD;
                        aDiff[2] = (aNcels[2] < infD) ? aNcels[2] + 2 * aRy[row - 1][col] + 1 : infD;
                        aDiff[3] = (aNcels[3] < infD)
                                       ? aNcels[3] + 2 * (aRx[row - 1][col + 1] + aRy[row - 1][col + 1] + 1)
                                       : infD;

                        // find neighbouring cell with minimum distance difference
                        int minDiff = aDiff[0];
                        int minDiffCell = 0;
                        for (int i = 1; i < 4; i++)
                        {
                            if (aDiff[i] < minDiff)
                            {
                                minDiff = aDiff[i];
                                minDiffCell = i;
                            }
                        }

                        // if a neighbouring cell with known distance was found:
                        if (minDiff < infD)
                        {
                            // assign the minimum euclidean distance
                            aSqDist[row][col] = minDiff;

                            // update the (rX, rY) cell-to-nearest-target vector
                            switch (minDiffCell)
                            {
                                case 0: // W
                                    aRx[row][col] = aRx[row][col - 1] + 1;
                                    aRy[row][col] = aRy[row][col - 1];
                                    break;
                                case 1: // NW
                                    aRx[row][col] = aRx[row - 1][col - 1] + 1;
                                    aRy[row][col] = aRy[row - 1][col - 1] + 1;
                                    break;
                                case 2: // N
                                    aRx[row][col] = aRx[row - 1][col];
                                    aRy[row][col] = aRy[row - 1][col] + 1;
                                    break;
                                case 3: // NE
                                    aRx[row][col] = aRx[row - 1][col + 1] + 1;
                                    aRy[row][col] = aRy[row - 1][col + 1] + 1;
                                    break;
                            }
                        }

                        // end of update (rX, rY) cell-to-nearest-target vector
                    }

                    // end or current row processing - report progress
                    int percent = (int)(row / (double)numRows * 100f);
                    if (percent > lastUpdate)
                    {
                        lastUpdate += 1;
                        cancelProgressHandler.Progress(
                            string.Empty, lastUpdate, TextStrings.Pass1 + lastUpdate + TextStrings.progresscompleted);
                        if (cancelProgressHandler.Cancel)
                        {
                            return false;
                        }
                    }
                }

                // *******************************************************************
                // end of first pass for loop
                // *******************************************************************

                // *******************************************************************
                // raster distance calculation PASS TWO - bottom to top, right to left
                // *******************************************************************
                lastUpdate = 0;
                for (int row = numRows - 2; row > 0; row--)
                {
                    for (int col = numColumns - 2; col > 0; col--)
                    {
                        int val = aSqDist[row][col];

                        // Continue processing only if the current cell is not a target
                        if (val == targetVal)
                        {
                            continue;
                        }

                        // read the values of the cell's neighbours
                        aNcels[0] = aSqDist[row][col + 1]; // E
                        aNcels[1] = aSqDist[row + 1][col + 1]; // SE
                        aNcels[2] = aSqDist[row + 1][col]; // S
                        aNcels[3] = aSqDist[row + 1][col - 1]; // SW

                        // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell
                        aDiff[0] = (aNcels[0] < infD) ? aNcels[0] + 2 * aRx[row][col + 1] + 1 : infD;
                        aDiff[1] = (aNcels[1] < infD)
                                       ? aNcels[1] + 2 * (aRx[row + 1][col + 1] + aRy[row + 1][col + 1] + 1)
                                       : infD;
                        aDiff[2] = (aNcels[2] < infD) ? aNcels[2] + 2 * aRy[row + 1][col] + 1 : infD;
                        aDiff[3] = (aNcels[3] < infD)
                                       ? aNcels[3] + 2 * (aRx[row + 1][col - 1] + aRy[row + 1][col - 1] + 1)
                                       : infD;

                        // find neighbouring cell with minimum distance difference
                        int minDiff = aDiff[0];
                        int minDiffCell = 0;
                        for (int i = 1; i < 4; i++)
                        {
                            if (aDiff[i] < minDiff)
                            {
                                minDiff = aDiff[i];
                                minDiffCell = i;
                            }
                        }

                        // if a neighbouring cell with known distance smaller than current known distance was found:
                        if (minDiff < val)
                        {
                            // assign the minimum euclidean distance
                            aSqDist[row][col] = minDiff;

                            // update the (rX, rY) cell-to-nearest-target vector
                            switch (minDiffCell)
                            {
                                case 0: // E
                                    aRx[row][col] = aRx[row][col + 1] + 1;
                                    aRy[row][col] = aRy[row][col + 1];
                                    break;
                                case 1: // SE
                                    aRx[row][col] = aRx[row + 1][col + 1] + 1;
                                    aRy[row][col] = aRy[row + 1][col + 1] + 1;
                                    break;
                                case 2: // S
                                    aRx[row][col] = aRx[row + 1][col];
                                    aRy[row][col] = aRy[row + 1][col] + 1;
                                    break;
                                case 3: // SW
                                    aRx[row][col] = aRx[row + 1][col - 1] + 1;
                                    aRy[row][col] = aRy[row + 1][col - 1] + 1;
                                    break;
                            }
                        }

                        // end of update (rX, rY) cell-to-nearest-target vector
                    }

                    // Write row to output raster
                    WriteOutputRow(outRaster, row, aSqDist[row]);

                    // Report progress
                    int percent = (int)(row / (double)numRows * 100f);
                    if (percent > lastUpdate)
                    {
                        lastUpdate += 1;
                        cancelProgressHandler.Progress(
                            string.Empty, lastUpdate, TextStrings.Pass2 + lastUpdate + TextStrings.progresscompleted);
                        if (cancelProgressHandler.Cancel)
                        {
                            return false;
                        }
                    }
                }
            }

            // *******************************************************************
            // end of second pass proximity calculation loop
            // *******************************************************************

            // save output raster
            output.Save();

            return true;
        }
        public bool Execute(IFeatureSet input, string zField, double cellSize, double power, int neighborType, int pointCount, double distance, IRaster output)
        {
            if (input == null || output == null)
            {
                return(false);
            }
            if (cellSize == 0)
            {
                cellSize = input.Extent.Width / 255;
            }
            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 });//error
            output.CellHeight = cellSize;
            output.CellWidth  = cellSize;
            output.Xllcenter  = input.Extent.MinX + (cellSize / 2);
            output.Yllcenter  = input.Extent.MinY + (cellSize / 2);
            progress.Maximum  = numColumns * numRows;
            progress.Value    = 0;
            #region 构建KD树
            List <KD_Point> lists = new List <KD_Point>();//构建KD-Tree的点集列表
            foreach (var p in input.Features)
            {
                KD_Point kd = new KD_Point(p.BasicGeometry.Coordinates[0].X, p.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(p.DataRow[zField]));
                lists.Add(kd);
            }
            KDTree kDTree = new KDTree();
            kDTree.CreateByPointList(lists);

            /*
             * double gdistance = input.Features[0].BasicGeometry.Coordinates[0].Distance(input.Features[1].BasicGeometry.Coordinates[0]);
             * double tdistance = Math.Sqrt(Math.Pow(input.Features[0].BasicGeometry.Coordinates[0].X- input.Features[1].BasicGeometry.Coordinates[0].X, 2) + Math.Pow(input.Features[0].BasicGeometry.Coordinates[0].Y- input.Features[1].BasicGeometry.Coordinates[0].Y, 2));
             * Console.WriteLine("gdistance: " + gdistance + " , tdistance: " + tdistance);
             */
            #endregion
            if (neighborType == 0)//固定数目
            {
                for (int x = 0; x < numColumns; x++)
                {
                    for (int y = 0; y < numRows; y++)
                    {
                        //IDW算法的分子和分母
                        double top    = 0;
                        double bottom = 0;
                        if (pointCount > 0)
                        {
                            Coordinate      coord    = output.CellToProj(y, x);
                            KD_Point        kD_Point = new KD_Point(coord.X, coord.Y);
                            List <KD_Point> points   = kDTree.K_Nearest(kD_Point, pointCount);
                            //Console.WriteLine("KDTree points count: " + points.Count);
                            for (int i = 0; i < points.Count; i++)
                            {
                                if (points[i] != null)
                                {
                                    Coordinate kd             = new Coordinate(points[i].X, points[i].Y);
                                    double     distanceToCell = kd.Distance(coord);
                                    if (distanceToCell <= distance || distance == 0)
                                    {
                                        //Console.WriteLine(points[i].Z);
                                        if (power == 2)
                                        {
                                            top    += (1 / (distanceToCell * distanceToCell)) * points[i].Z;
                                            bottom += 1 / (distanceToCell * distanceToCell);
                                        }
                                        else
                                        {
                                            top    += (1 / Math.Pow(distanceToCell, power)) * points[i].Z;
                                            bottom += 1 / Math.Pow(distanceToCell, power);
                                        }
                                    }
                                }
                            }
                        }

                        else
                        {
                            for (int i = 0; i < input.Features.Count; i++)
                            {
                                Coordinate cellCenter = output.CellToProj(y, x);
                                //Coordinate coord = output.CellToProj(y, x);
                                var featurePt = input.Features[i];
                                if (featurePt != null)
                                {
                                    double distanceToCell = cellCenter.Distance(featurePt.BasicGeometry.Coordinates[0]);
                                    if (distanceToCell <= distance || distance == 0)
                                    {
                                        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);
                                        }
                                    }
                                }
                            }
                        }
                        //Console.WriteLine("top: " + top + " , bottom: " +bottom);
                        output.Value[y, x] = top / bottom;
                        //Console.WriteLine(y + " , " + x + " : " + output.Value[y, x]);
                        //richText.Text += output.Value[y, x] + "\n";
                        progress.Value++;
                    }
                }
            }
            output.Save();
            return(true);
        }
示例#11
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);
        }
示例#12
0
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="ras">The input altitude raster.</param>
        /// <param name="output">The output slope raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns></returns>
        public bool Execute(IRaster ras,double inZFactor, bool slopeInPercent,IRaster output, MapWindow.Tools.ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (ras == null || output == null)
            {
                return false;
            }
            double z1, z2, z3, z4, z5, z6, z7, z8, dZ_dx, dZ_dy, slope;
            int current, previous;
            try
            {
                int noOfCol = ras.NumColumns;
                int noOfRow = ras.NumRows;
                IEnvelope envelope1 = new Envelope() as IEnvelope;
                envelope1 = ras.Bounds.Envelope;


                output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, typeof(double), new string[] { "" });
                output.NoDataValue = ras.NoDataValue;

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

                previous = 0;
                for (int i = 0; i < output.NumRows; i++)
                {
                    current = Convert.ToInt32(Math.Round(i * 100D / output.NumRows));
                    //only update when increment in percentage
                    if (current > previous)
                        cancelProgressHandler.Progress("", current, current.ToString() + 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)
                        {
                            z1 = ras.Value[i - 1, j - 1];
                            z2 = ras.Value[i - 1, j];
                            z3 = ras.Value[i - 1, j + 1];
                            z4 = ras.Value[i, j - 1];
                            z5 = ras.Value[i, j + 1];
                            z6 = ras.Value[i + 1, j - 1];
                            z7 = ras.Value[i + 1, j];
                            z8 = ras.Value[i + 1, j + 1];

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

                            slope = Math.Atan(Math.Sqrt((dZ_dx * dZ_dx) + (dZ_dy * dZ_dy))) * (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 == true)
                                return false;
                        }
                        else
                            output.Value[i, j] = output.NoDataValue;

                        if (cancelProgressHandler.Cancel == true)
                            return false;
                    }

                }

                //output = Temp;
                if (output.IsFullyWindowed())
                {
                    output.Save();
                    return true;
                }
                else
                    return false;
                
            }
            catch (Exception ex)
            {
                //throw new SystemException("Error in Slope: ", ex);
                throw new SystemException(ex.ToString());
            }
            
        }
        public bool ExecuteByParam(IFeatureSet input, string zField, double cellSize, string model, int neighborType, int pointCount, double distance, IRaster output, double c, double r)
        {
            if (input == null || output == null)
            {
                return(false);
            }
            if (cellSize == 0)
            {
                cellSize = input.Extent.Width / 255;
            }
            int numColumns = Convert.ToInt32(Math.Round(input.Extent.Width / cellSize));
            int numRows    = Convert.ToInt32(Math.Round(input.Extent.Height / cellSize));

            progress.Maximum  = numColumns * numRows;
            progress.Value    = 0;
            output            = Raster.CreateRaster(output.Filename, string.Empty, numColumns, numRows, 1, typeof(double), new[] { string.Empty });//error
            output.CellHeight = cellSize;
            output.CellWidth  = cellSize;
            output.Xllcenter  = input.Extent.MinX + (cellSize / 2);
            output.Yllcenter  = input.Extent.MinY + (cellSize / 2);
            List <AltitudePoint> points = new List <AltitudePoint>();

            if (neighborType == 0)
            {
                #region 构建KD树
                List <KD_Point> lists = new List <KD_Point>();//构建KD-Tree的点集列表
                foreach (var p in input.Features)
                {
                    KD_Point kd = new KD_Point(p.BasicGeometry.Coordinates[0].X, p.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(p.DataRow[zField]));
                    lists.Add(kd);
                }
                KDTree kDTree = new KDTree();
                kDTree.CreateByPointList(lists);
                #endregion
                if (pointCount > 0)
                {
                    for (int i = 0; i < input.Features.Count; i++)
                    {
                        var featurePt = input.Features[i];
                        points.Add(new AltitudePoint(featurePt.BasicGeometry.Coordinates[0].X, featurePt.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(featurePt.DataRow[zField])));
                    }
                    ForRasterData forRasterData = new ForRasterData(points, model);
                    for (int x = 0; x < numColumns; x++)
                    {
                        for (int y = 0; y < numRows; y++)
                        {
                            points.Clear();
                            Coordinate      coord    = output.CellToProj(y, x);
                            KD_Point        kD_Point = new KD_Point(coord.X, coord.Y);
                            List <KD_Point> kdpoints = kDTree.K_Nearest(kD_Point, pointCount);
                            foreach (var p in kdpoints)
                            {
                                points.Add(new AltitudePoint(p.X, p.Y, p.Z));
                            }
                            forRasterData.ReSetPointList(points);
                            if (!forRasterData.IsPointsOK())
                            {
                                return(false);
                            }
                            output.Value[y, x] = forRasterData.GetValue(coord.X, coord.Y);
                            progress.Value++;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < input.Features.Count; i++)
                    {
                        var featurePt = input.Features[i];
                        points.Add(new AltitudePoint(featurePt.BasicGeometry.Coordinates[0].X, featurePt.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(featurePt.DataRow[zField])));
                    }
                    ForRasterData forRasterData = new ForRasterData(points, model, c, r);
                    if (!forRasterData.IsPointsOK())
                    {
                        return(false);
                    }
                    for (int x = 0; x < numColumns; x++)
                    {
                        for (int y = 0; y < numRows; y++)
                        {
                            Coordinate coordinate = output.CellToProj(y, x);
                            output.Value[y, x] = forRasterData.GetValue(coordinate.X, coordinate.Y);
                            progress.Value++;
                        }
                    }
                }
            }
            output.Save();
            return(true);
        }
        /// <summary>
        /// Executes the threshold operation
        /// </summary>
        /// <param name="input1">The input raster</param>
        /// <param name="threshold">The threshold value</param>
        /// <param name="output">The output raster</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns></returns>
        public bool Execute(IRaster input, double threshold, IRaster output, MapWindow.Tools.ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (input == null || output == null)
            {
                return false;
            }

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

            //Create the new raster with the appropriate dimensions
            output = Raster.Create(output.Filename, "", noOfCol, noOfRow,1 , typeof(int), new string[] { "" });
            output.CellWidth = input.CellWidth;
            output.CellHeight = input.CellHeight;
            output.Xllcenter = input.Xllcenter;
            output.Yllcenter = input.Yllcenter;
            output.NoDataValue = -1;

            //Loop throug every cell
            int max = (output.Bounds.NumRows + 1);
            for (int i = 0; i < output.NumRows; i++)
            {
                for (int j = 0; j < output.NumColumns; j++)
                {
                    if (input.Value[i, j] == input.NoDataValue)
                        output.Value[i,j] = -1;
                    else if (input.Value[i, j] >= threshold)
                        output.Value[i,j] = 1;
                    else
                        output.Value[i,j] = 0;
                    
                    if (cancelProgressHandler.Cancel == true)
                        return false;
                }

                //only update when increment in persentage
                current = Convert.ToInt32(Math.Round(i * 100D / max));
                if (current > previous)
                    cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed");
                previous = current;
            }

            output.Save();
            return true;
        }
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int progress = 0;
            int count    = 1;
            int ndays    = 174;

            if (senseor == 5)
            {
                ndays = 174;
            }
            else
            {
                ndays = 56;
            }
            //string lake_centroid = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\mask_centroid.shp";
            string    lake_centroid    = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\mask_centroid_selected.shp";
            var       lake_centroid_fs = FeatureSet.Open(lake_centroid);
            DataTable centroid_dt      = lake_centroid_fs.DataTable;
            //var lake_list = (from DataRow dr in centroid_dt.Rows where dr["Flag"].ToString() == "1" select int.Parse(dr["Id"].ToString())).ToList();
            // var lake_list = new int[] { 1,18,19,28,30,35,41,49,50,55,57,58,59,60,63,89,91,97,99,100,112,113,118,133,135,136,160,169,181,183};
            var lake_list = new int[] { 59 };
            int nlakes    = lake_list.Length;

            double [,] water_area     = new double[ndays, nlakes];
            double[,] water_bond_area = new double[ndays, nlakes];

            for (int K = 0; K < nlakes; K++)
            {
                int lake_id = lake_list[K];
                var dr_lake = (from DataRow dr in centroid_dt.Rows where dr["Id"].ToString() == lake_id.ToString() select dr).First();

                string       img_dir      = Path.Combine(FileDirectory, lake_id.ToString());
                StreamReader sr_date_list = new StreamReader(Path.Combine(img_dir, "date_list.txt"));
                int          nfile        = 0;
                while (!sr_date_list.EndOfStream)
                {
                    sr_date_list.ReadLine();
                    nfile++;
                }
                sr_date_list.Close();
                sr_date_list = new StreamReader(Path.Combine(img_dir, "date_list.txt"));
                string[] dirs = new string[nfile];
                for (int i = 0; i < nfile; i++)
                {
                    var str = sr_date_list.ReadLine();
                    dirs[i] = Path.Combine(img_dir, str + "_cmb.tif");
                }

                string       class_file_list = Path.Combine(img_dir, @"class\class_list.txt");
                StreamWriter sw_area         = new StreamWriter(Path.Combine(img_dir, "class\\area.csv"));
                FileStream   fs_class        = new FileStream(class_file_list, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sr_class_file   = new StreamReader(fs_class);
                var          center_pt       = new Coordinate(double.Parse(dr_lake["X"].ToString()), double.Parse(dr_lake["Y"].ToString()));
                int          cell_area       = 5 * 5;
                int          date_index      = 0;
                try
                {
                    foreach (var file in dirs)
                    {
                        int     water_cell_count       = 0;
                        int     water_bound_cell_count = 0;
                        var     temp       = Path.GetFileNameWithoutExtension(file);
                        var     daystr     = temp.Remove(10);
                        var     water_file = file.Replace("_cmb", "_water");
                        IRaster raster2    = Raster.OpenFile(file);
                        raster2.SaveAs(water_file);
                        IRaster raster_water = Raster.OpenFile(water_file);

                        var class_file = sr_class_file.ReadLine();
                        var class_mat  = ReadClassFile(class_file, raster2.NumRows, raster2.NumColumns);

                        for (int i = 0; i < raster2.NumRows; i++)
                        {
                            for (int j = 0; j < raster2.NumColumns; j++)
                            {
                                if (raster2.Value[i, j] != raster2.NoDataValue)
                                {
                                    raster_water.Value[i, j] = class_mat[i][j];
                                }
                                else
                                {
                                    raster_water.Value[i, j] = raster2.NoDataValue;
                                }
                            }
                        }
                        var cell               = raster2.ProjToCell(center_pt);
                        var center_class       = raster_water.Value[cell.Row, cell.Column];
                        var center_bound_class = center_class;
                        for (int i = cell.Row + 1; i < raster2.NumRows; i++)
                        {
                            if (raster_water.Value[i, cell.Column] != center_class)
                            {
                                center_bound_class = raster_water.Value[i, cell.Column];
                                break;
                            }
                        }

                        if (center_bound_class == center_class)
                        {
                            for (int i = cell.Column + 1; i < raster2.NumColumns; i++)
                            {
                                if (raster_water.Value[cell.Row, i] != center_class)
                                {
                                    center_bound_class = raster_water.Value[cell.Row, i];
                                    break;
                                }
                            }
                        }

                        for (int i = 0; i < raster2.NumRows; i++)
                        {
                            for (int j = 0; j < raster2.NumColumns; j++)
                            {
                                if (raster2.Value[i, j] != raster2.NoDataValue)
                                {
                                    if (raster_water.Value[i, j] == center_class)
                                    {
                                        water_cell_count++;
                                    }
                                    if (raster_water.Value[i, j] == center_bound_class)
                                    {
                                        water_bound_cell_count++;
                                    }
                                }
                            }
                        }
                        water_area[date_index, K]      = water_cell_count * cell_area;
                        water_bond_area[date_index, K] = water_bound_cell_count * cell_area;
                        sw_area.WriteLine(string.Format("{0},{1},{2},{3}", daystr, water_area[date_index, K], water_bond_area[date_index, K],
                                                        water_area[date_index, K] + water_bond_area[date_index, K]));

                        raster_water.Save();
                        raster_water.Close();

                        date_index++;
                    }
                }
                catch (Exception ex)
                {
                    cancelProgressHandler.Progress("Package_Tool", 100, "Error: " + ex.Message);
                }
                finally
                {
                    sw_area.Close();
                    sr_class_file.Close();
                    sr_date_list.Close();
                }
                progress = K * 100 / nlakes;
                //if (progress > count)
                //{
                cancelProgressHandler.Progress("Package_Tool", progress, "Processing lake " + lake_id);
                count++;
                // }
            }
            string       lake_area_file      = Path.Combine(FileDirectory, "water_area.csv");
            string       lake_area_bond_file = Path.Combine(FileDirectory, "waterbond_area.csv");
            StreamWriter csv_water           = new StreamWriter(lake_area_file);
            StreamWriter csv_bond            = new StreamWriter(lake_area_bond_file);
            var          line = string.Join(",", lake_list.ToArray());

            csv_water.WriteLine(line);
            csv_bond.WriteLine(line);
            for (int t = 0; t < ndays; t++)
            {
                line = "";
                for (int j = 0; j < nlakes; j++)
                {
                    line += water_area[t, j] + ",";
                }
                line = line.TrimEnd(new char[] { ',' });
                csv_water.WriteLine(line);

                line = "";
                for (int j = 0; j < nlakes; j++)
                {
                    line += water_bond_area[t, j] + ",";
                }
                line = line.TrimEnd(new char[] { ',' });
                csv_bond.WriteLine(line);
            }

            csv_water.Close();
            csv_bond.Close();
            lake_centroid_fs.Close();
            return(true);
        }
示例#16
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();

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

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

            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 *= 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);
        }
示例#17
0
        /// <summary>
        /// Executes the ReSample Opaeration tool programmatically
        /// Ping deleted the static property for external testing.
        /// </summary>
        /// <param name="input1">The input raster.</param>
        /// <param name="newCellHeight">The size of the cell's hight.</param>
        /// <param name="newCellWidth">The size of the cell's width.</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, double newCellHeight, double newCellWidth, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input1 == null || newCellWidth == 0 || output == null)
            {
                return(false);
            }

            Extent envelope = input1.Bounds.Extent;

            // Calculate new number of columns and rows
            int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / newCellWidth));
            int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / newCellHeight));

            int previous = 0;

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

            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

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

            for (int i = 0; i < output.Bounds.NumRows; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    // Projet the cell position to Map
                    Coordinate cellCenter = output.CellToProj(i, j);
                    var        index1     = input1.ProjToCell(cellCenter);

                    double val;
                    if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1)
                    {
                        val = input1.Value[index1.Row, index1.Column] == input1.NoDataValue ? output.NoDataValue : input1.Value[index1.Row, index1.Column];
                    }
                    else
                    {
                        val = output.NoDataValue;
                    }

                    output.Value[i, j] = val;

                    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(current, current + TextStrings.progresscompleted);
                }

                previous = current;
            }

            output.Save();
            return(true);
        }
示例#18
0
        /// <summary>
        /// Executes the Raster distance calculation
        /// Ping Yang deleted static for external testing 10/2010.
        /// </summary>
        /// <param name="input">The input raster.</param>
        /// <param name="output">The output raster.</param>
        /// <param name="maxDistance">The maximum distance value. Cells with a larger distance to nearest
        /// target cell than maxDistance will be assigned 'no data' value.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>true if execution was successful, false otherwise.</returns>
        public bool Execute(IRaster input, IRaster output, double maxDistance, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input == null || output == null)
            {
                return(false);
            }

            // Creates the output raster with the same bounds as the input
            RasterBounds bounds = (RasterBounds)input.Bounds.Copy();

            output        = Raster.CreateRaster(output.Filename, string.Empty, bounds.NumColumns, bounds.NumRows, 1, typeof(int), new[] { string.Empty });
            output.Bounds = bounds;

            // internally we reference output as an integer type raster.
            if (output is Raster <int> outRaster)
            {
                int numColumns = outRaster.NumColumns;
                int numRows    = outRaster.NumRows;
                int lastUpdate = 0;

                // declare two jagged arrays for storing the (Rx, Ry) vectors.
                // rX is distance from current cell to nearest target cell measured in the x-direction
                // rY is distance from current cell to nearest target cell measured in the y-direction
                // the actual distance can be calculated as sqrt(rX^2 + rY^2).
                // in the resulting distance raster we store the squared distance as well as the rX, rY relative coordinates
                // to improve computation speed
                int[][] aRx     = new int[numRows][];
                int[][] aRy     = new int[numRows][];
                int[][] aSqDist = new int[numRows][];

                const int InfD      = int.MaxValue;
                const int TargetVal = 0;

                // initialize the arrays
                for (int i = 0; i < numRows; i++)
                {
                    aRx[i]     = new int[numColumns];
                    aRy[i]     = new int[numColumns];
                    aSqDist[i] = new int[numColumns];
                    ReadInputRow(input, i, aSqDist[i], TargetVal, InfD);
                }

                // *******************************************************************
                // raster distance calculation pass one - top to bottom, left to right
                // *******************************************************************
                // int[] row1 = new int[numColumns];
                // int[] row2 = new int[numColumns];
                int[] aNcels = new int[4]; // the values of four neighbouring cells (W, NW, N, NE)
                int[] aDiff  = new int[4]; // the | y coordinate distances to nearest target cell

                for (int row = 1; row < numRows; row++)
                {
                    //// read the row from input raster
                    // ReadInputRow(input, rowIndex, row2, targetVal, infD);
                    for (int col = 1; col < numColumns - 1; col++)
                    {
                        int val = aSqDist[row][col];

                        // Continue processing only if the current cell is not a target
                        if (val == TargetVal)
                        {
                            continue;
                        }

                        // read the values of the cell's neighbours
                        aNcels[0] = aSqDist[row][col - 1];     // W
                        aNcels[1] = aSqDist[row - 1][col - 1]; // NW
                        aNcels[2] = aSqDist[row - 1][col];     // N
                        aNcels[3] = aSqDist[row - 1][col + 1]; // NE

                        // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell
                        aDiff[0] = (aNcels[0] < InfD) ? aNcels[0] + (2 * aRx[row][col - 1]) + 1 : InfD;
                        aDiff[1] = (aNcels[1] < InfD) ? aNcels[1] + (2 * (aRx[row - 1][col - 1] + aRy[row - 1][col - 1] + 1)) : InfD;
                        aDiff[2] = (aNcels[2] < InfD) ? aNcels[2] + (2 * aRy[row - 1][col]) + 1 : InfD;
                        aDiff[3] = (aNcels[3] < InfD) ? aNcels[3] + (2 * (aRx[row - 1][col + 1] + aRy[row - 1][col + 1] + 1)) : InfD;

                        // find neighbouring cell with minimum distance difference
                        int minDiff     = aDiff[0];
                        int minDiffCell = 0;
                        for (int i = 1; i < 4; i++)
                        {
                            if (aDiff[i] < minDiff)
                            {
                                minDiff     = aDiff[i];
                                minDiffCell = i;
                            }
                        }

                        // if a neighbouring cell with known distance was found:
                        if (minDiff < InfD)
                        {
                            // assign the minimum euclidean distance
                            aSqDist[row][col] = minDiff;

                            // update the (rX, rY) cell-to-nearest-target vector
                            switch (minDiffCell)
                            {
                            case 0:     // W
                                aRx[row][col] = aRx[row][col - 1] + 1;
                                aRy[row][col] = aRy[row][col - 1];
                                break;

                            case 1:     // NW
                                aRx[row][col] = aRx[row - 1][col - 1] + 1;
                                aRy[row][col] = aRy[row - 1][col - 1] + 1;
                                break;

                            case 2:     // N
                                aRx[row][col] = aRx[row - 1][col];
                                aRy[row][col] = aRy[row - 1][col] + 1;
                                break;

                            case 3:     // NE
                                aRx[row][col] = aRx[row - 1][col + 1] + 1;
                                aRy[row][col] = aRy[row - 1][col + 1] + 1;
                                break;
                            }
                        }

                        // end of update (rX, rY) cell-to-nearest-target vector
                    }

                    // end or current row processing - report progress
                    int percent = (int)(row / (double)numRows * 100f);
                    if (percent > lastUpdate)
                    {
                        lastUpdate += 1;
                        cancelProgressHandler.Progress(lastUpdate, TextStrings.Pass1 + lastUpdate + TextStrings.progresscompleted);
                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }

                // *******************************************************************
                // end of first pass for loop
                // *******************************************************************

                // *******************************************************************
                // raster distance calculation PASS TWO - bottom to top, right to left
                // *******************************************************************
                lastUpdate = 0;
                for (int row = numRows - 2; row > 0; row--)
                {
                    for (int col = numColumns - 2; col > 0; col--)
                    {
                        int val = aSqDist[row][col];

                        // Continue processing only if the current cell is not a target
                        if (val == TargetVal)
                        {
                            continue;
                        }

                        // read the values of the cell's neighbours
                        aNcels[0] = aSqDist[row][col + 1];     // E
                        aNcels[1] = aSqDist[row + 1][col + 1]; // SE
                        aNcels[2] = aSqDist[row + 1][col];     // S
                        aNcels[3] = aSqDist[row + 1][col - 1]; // SW

                        // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell
                        aDiff[0] = (aNcels[0] < InfD) ? aNcels[0] + (2 * aRx[row][col + 1]) + 1 : InfD;
                        aDiff[1] = (aNcels[1] < InfD) ? aNcels[1] + (2 * (aRx[row + 1][col + 1] + aRy[row + 1][col + 1] + 1)) : InfD;
                        aDiff[2] = (aNcels[2] < InfD) ? aNcels[2] + (2 * aRy[row + 1][col]) + 1 : InfD;
                        aDiff[3] = (aNcels[3] < InfD) ? aNcels[3] + (2 * (aRx[row + 1][col - 1] + aRy[row + 1][col - 1] + 1)) : InfD;

                        // find neighbouring cell with minimum distance difference
                        int minDiff     = aDiff[0];
                        int minDiffCell = 0;
                        for (int i = 1; i < 4; i++)
                        {
                            if (aDiff[i] < minDiff)
                            {
                                minDiff     = aDiff[i];
                                minDiffCell = i;
                            }
                        }

                        // if a neighbouring cell with known distance smaller than current known distance was found:
                        if (minDiff < val)
                        {
                            // assign the minimum euclidean distance
                            aSqDist[row][col] = minDiff;

                            // update the (rX, rY) cell-to-nearest-target vector
                            switch (minDiffCell)
                            {
                            case 0:     // E
                                aRx[row][col] = aRx[row][col + 1] + 1;
                                aRy[row][col] = aRy[row][col + 1];
                                break;

                            case 1:     // SE
                                aRx[row][col] = aRx[row + 1][col + 1] + 1;
                                aRy[row][col] = aRy[row + 1][col + 1] + 1;
                                break;

                            case 2:     // S
                                aRx[row][col] = aRx[row + 1][col];
                                aRy[row][col] = aRy[row + 1][col] + 1;
                                break;

                            case 3:     // SW
                                aRx[row][col] = aRx[row + 1][col - 1] + 1;
                                aRy[row][col] = aRy[row + 1][col - 1] + 1;
                                break;
                            }
                        }

                        // end of update (rX, rY) cell-to-nearest-target vector
                    }

                    // Write row to output raster
                    WriteOutputRow(outRaster, row, aSqDist[row]);

                    // Report progress
                    int percent = (int)(row / (double)numRows * 100f);
                    if (percent > lastUpdate)
                    {
                        lastUpdate += 1;
                        cancelProgressHandler.Progress(lastUpdate, TextStrings.Pass2 + lastUpdate + TextStrings.progresscompleted);
                        if (cancelProgressHandler.Cancel)
                        {
                            return(false);
                        }
                    }
                }
            }

            // *******************************************************************
            // end of second pass proximity calculation loop
            // *******************************************************************

            // save output raster
            output.Save();

            return(true);
        }
        /// <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 = MapWindow.Analysis.VectorToRaster.ToRaster(source, ref cellSize, fieldName, output.Filename, "", new string[]{}, cancelProgressHandler);
            output.Save();
            return true;
        }
示例#20
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());
            }
        }
示例#21
0
        /// <summary>
        /// Executes the Erase Opaeration tool programaticaly
        /// </summary>
        /// <param name="input1">The input raster</param>
        /// <param name="input2">The input raster</param>
        /// <param name="output">The output raster</param>
        /// <param name="cancelProgressHandler">The progress handler</param>
        /// <returns></returns>
        public bool Execute(IRaster input1, IRaster input2, IRaster output, MapWindow.Tools.ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (input1 == null || input2 == null || output == null)
            {
                return false;
            }

            IEnvelope envelope = new Envelope() as IEnvelope;

            envelope = UnionEnvelope(input1, input2);

            int noOfCol;
            int noOfRow;

            //Figures out which raster has smaller cells
            IRaster smallestCellRaster;
            if (input1.CellWidth < input2.CellWidth) smallestCellRaster = input1;
            else smallestCellRaster = input2;

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

            //Create the new raster with the appropriate dimensions
            Raster Temp = new Raster();
            //Temp.CreateNew(output.Filename, noOfRow, noOfCol, input1.DataType);
            Temp.CreateNew(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new string[] { "" });

            Temp.CellWidth = smallestCellRaster.CellWidth;
            Temp.CellHeight = smallestCellRaster.CellHeight;
            Temp.Xllcenter = envelope.Minimum.X + (Temp.CellWidth / 2);
            Temp.Yllcenter = envelope.Minimum.Y + (Temp.CellHeight / 2);

            MapWindow.Geometries.ICoordinate I1 = new MapWindow.Geometries.Coordinate() as MapWindow.Geometries.ICoordinate;
            RcIndex v1 = new RcIndex();
            RcIndex v2 = new RcIndex();

            double val1;
            double val2;
            int previous=0;
            int current=0;
            int max = (Temp.Bounds.NumRows + 1);
            for (int i = 0; i < Temp.Bounds.NumRows; i++)
            {
                for (int j = 0; j < Temp.Bounds.NumColumns; j++)
                {
                    I1 = Temp.CellToProj(i, j);
                    v1 = input1.ProjToCell(I1);
                    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;

                    v2 = input2.ProjToCell(I1);
                    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)
                    {
                        Temp.Value[i, j] = Temp.NoDataValue;
                    }
                    else if (val1 != input1.NoDataValue && val2 == input2.NoDataValue)
                    {
                        Temp.Value[i, j] = val1;
                    }
                    else if (val1 == input1.NoDataValue && val2 != input2.NoDataValue)
                    {
                        Temp.Value[i, j] = val2;
                    }
                    else
                    {
                        Temp.Value[i, j] = val1;
                    }

                    if (cancelProgressHandler.Cancel == true)
                        return false;
                }
                current = Convert.ToInt32(Math.Round(i * 100D / max));
                //only update when increment in persentage
                if(current>previous)
                    cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed");
                previous = current;
            }

            output = Temp;
            output.Save();
            return true;
        }
        /// <summary>
        /// Executes the Erase Opaeration tool programaticaly.
        /// </summary>
        /// <param name="input1">The input raster.</param>
        /// <param name="input2">The input raster.</param>
        /// <param name="output">The output raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns></returns>
        public bool Execute(IRaster input1, IFeatureSet input2, IRaster output, MapWindow.Tools.ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (input1 == null || input2 == null || output == null)
            {
                return false;
            }

            int noOfCol = input1.NumColumns;
            int noOfRow = input1.NumRows;

            //Calculate the Intersect Envelope
            IEnvelope envelope1 = new Envelope() as IEnvelope;
            IEnvelope envelope2 = new Envelope() as IEnvelope;
            envelope1 = input1.Bounds.Envelope;
            envelope2 = input2.Envelope;
            envelope1 = envelope1.Intersection(envelope2);

            //Create the new raster with the appropriate dimensions
            IRaster Temp = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new string[] { });
            //Temp.CreateNew(output.Filename, noOfRow, noOfCol, input1.DataType);
            Temp.CellWidth = input1.CellWidth;
            Temp.CellHeight = input1.CellHeight;
            Temp.Xllcenter = envelope1.Minimum.X + (Temp.CellWidth / 2);
            Temp.Yllcenter = envelope1.Minimum.Y + (Temp.CellHeight / 2);

            MapWindow.Geometries.ICoordinate I1 = new MapWindow.Geometries.Coordinate() as MapWindow.Geometries.ICoordinate;
            RcIndex v1 = new RcIndex();
         
           // MapWindow.Analysis.Topology.Algorithm.PointLocator pointLocator1 = new MapWindow.Analysis.Topology.Algorithm.PointLocator();

            double val1;
            int previous = 0;
            int current = 0;

            
           
            int max = (Temp.Bounds.NumRows + 1);
            for (int i = 0; i < Temp.Bounds.NumRows; i++)
            {
                for (int j = 0; j < Temp.Bounds.NumColumns; j++)
                {
                    I1 = Temp.CellToProj(i, j);
                   
                    v1 = input1.ProjToCell(I1);

                    if (v1.Row <= input1.EndRow && v1.Column <= input1.EndColumn && v1.Row > -1 && v1.Column > -1)
                        val1 = input1.Value[v1.Row, v1.Column];
                    else
                        val1 = Temp.NoDataValue;

                    //test if the coordinate is inside of the polygon
                    bool isInside = false;
                    IFeature pointFeat = new Feature(new Point(I1)) as IFeature;
                        foreach (IFeature f in input2.Features)
                        {
                            if (f.Contains(pointFeat))
                            {
                                Temp.Value[i, j] = val1;
                                isInside = true;
                                break;
                            }
                        }
                 
                    if (isInside == false)
                    {
                        Temp.Value[i, j] = Temp.NoDataValue;
                    }

                    
                    
                    if (cancelProgressHandler.Cancel == true)
                        return false;
                }
                current = Convert.ToInt32(Math.Round(i * 100D / max));
                //only update when increment in percentage
                if (current > previous)
                    cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed");
                previous = current;
            }

            output = Temp;
            output.Save();
            return true;
        }
示例#23
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;
            Type dataType = input.DataType;

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

            output.Bounds = bound;

            output.NoDataValue = newValue;

            // 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);
        }
示例#24
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());
            }
        }
示例#25
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;

            //TODO jany_ correct code to work with new KdTree

            //// Populates the KD tree
            //KdTree kd = new KdTree(2);
            //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.ToArray()) != null)
            //    {
            //        coord.X = coord.X * 1.000000000000001D;
            //    }

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

            //// Makes sure we don't try to search for more points then exist
            //if (kd.Count < pointCount)
            //{
            //    pointCount = kd.Count;
            //}

            //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);
            //            Double[] pixelCoord = new double[2];
            //            pixelCoord[0] = output.CellToProj(y, x).X;
            //            pixelCoord[1] = output.CellToProj(y, x).Y;
            //            object[] result = kd.Nearest(pixelCoord, pointCount);

            //            // Sets up the IDW numerator and denominator
            //            double top = 0;
            //            double bottom = 0;
            //            foreach (object feat in result)
            //            {
            //                IFeature featurePt = feat as Feature;
            //                if (featurePt == null)
            //                {
            //                    continue;
            //                }

            //                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(
            //                string.Empty, lastUpdate, "Cell: " + (x * numRows) + " of " + (numColumns * numRows));
            //            if (cancelProgressHandler.Cancel)
            //            {
            //                return false;
            //            }
            //        }
            //    }
            //}

            output.Save();
            return(true);
        }
示例#26
0
        /// <summary>
        /// Executes the slope generation raster.
        /// </summary>
        /// <param name="ras">The input altitude raster.</param>
        /// <param name="inZFactor">The multiplicitive scaling factor for elveation.</param>
        /// <param name="slopeInPercent">Boolean that is true if the slope values should be returned as percentages.</param>
        /// <param name="result">The output slope raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>Boolean, true if the method was successful.</returns>
        private static bool Slope(
            ref IRaster ras,
            double inZFactor,
            bool slopeInPercent,
            ref IRaster result,
            ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (ras == null || result == null)
            {
                return false;
            }

            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 false;
                            }
                        }
                        else
                        {
                            temp.Value[i, j] = temp.NoDataValue;
                        }

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

                result = temp;
                if (result.IsFullyWindowed())
                {
                    result.Save();
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                // throw new SystemException("Error in Slope: ", ex);
                throw new SystemException(ex.ToString());
            }
        }
        /// <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());
            }
        }
        /// <summary>
        /// Executes the Erase Opaeration tool programaticaly.
        /// Ping deleted static for external testing 01/2010
        /// </summary>
        /// <param name="input1">The input raster.</param>
        /// <param name="input2">The input raster.</param>
        /// <param name="output">The output raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns></returns>
        public bool Execute(IRaster input1, IFeatureSet input2, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            //Validates the input and output data
            if (input1 == null || input2 == null || output == null)
            {
                return false;
            }
            double cellWidth = input1.CellWidth;
            double cellHeight = input1.CellHeight;
            

            //Calculate the Intersect Envelope
            IEnvelope envelope1 = input1.Bounds.Envelope;
            IEnvelope envelope2 = input2.Envelope;
            envelope1 = envelope1.Intersection(envelope2);

            int noOfCol = Convert.ToInt32(envelope1.Height / cellHeight);

            int noOfRow = Convert.ToInt32(envelope1.Width / cellWidth);

            //create output raster
            output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, typeof(int), new[] { "" });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope1);
            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

            RcIndex v1;
         
           // MapWindow.Analysis.Topology.Algorithm.PointLocator pointLocator1 = new MapWindow.Analysis.Topology.Algorithm.PointLocator();

            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);
                   
                   

                    //test if the coordinate is inside of the polygon
                    bool isInside = false;
                    IFeature pointFeat = new Feature(new Point(cellCenter));
                        foreach (IFeature f in input2.Features)
                        {
                            if (f.Contains(pointFeat))
                            {
                                //output.Value[i, j] = val1;
                                isInside = true;
                                break;
                            }
                        }

                        if (isInside)
                        {
                            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 = output.NoDataValue;

                            output.Value[i, j] = val1;
                        }
                        else
                        {
                            output.Value[i, j] = output.NoDataValue;
                        }
                 
                                        
                    if (cancelProgressHandler.Cancel)
                        return false;
                }
                int current = Convert.ToInt32(Math.Round(i * 100D / max));
                //only update when increment in percentage
                if (current > previous)
                    cancelProgressHandler.Progress("", current, current + TextStrings.progresscompleted);
                previous = current;
            }

            //output = Temp;
            output.Save();
            return true;
        }
示例#29
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;
            Type dataType = input.DataType;

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

            output.NoDataValue = newValue;

            // 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;
        }                                           
示例#30
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="output">The output polygon feature set</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 cellsize based on the input extents
            if (cellSize == 0)
                cellSize = input.Envelope.Width / 255;

            //Defines the dimesions and position of the raster
            int numColumns = Convert.ToInt32(Math.Round(input.Envelope.Width / cellSize));
            int numRows = Convert.ToInt32(Math.Round(input.Envelope.Height / cellSize));
          
            output = Raster.Create(output.Filename, "",numColumns, numRows, 1, typeof(double), new[] {""} );

            output.CellHeight = cellSize;
            output.CellWidth = cellSize;
            output.Xllcenter = input.Envelope.Minimum.X + (cellSize/2);
            output.Yllcenter = input.Envelope.Minimum.Y + (cellSize/2);

            //Used to calculate progress
            int lastUpdate=0;

            //Populates the KD tree
            MapWindow.Analysis.Topology.KDTree.KDTree kd = new MapWindow.Analysis.Topology.KDTree.KDTree(2);
            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]].Coordinates[0];
                while (kd.Search(coord.ToArray()) != null)
                    coord.X = coord.X * 1.000000000000001D;                    
                kd.Insert(coord.ToArray(), input.Features[randomList[index]]);
                completed.Add(randomList[index]);
                randomList.RemoveAt(index);
            }

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

            //Makes sure we don't try to search for more points then exist
            if (kd.Count < pointCount)
                pointCount = kd.Count;

            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);
                        Double[] pixelCoord = new double[2];
                        pixelCoord[0] = output.CellToProj(y, x).X;
                        pixelCoord[1] = output.CellToProj(y, x).Y;
                        sw.Start();
                        object[] result = kd.Nearest(pixelCoord, pointCount);
                        sw.Stop();

                        //Sets up the IDW numerator and denominator
                        double top = 0;
                        double bottom = 0;
                        foreach (object feat in result)
                        {
                              IFeature featurePt = feat as Feature;
                              if (featurePt == null) continue;
                              double distanceToCell = cellCenter.Distance(featurePt.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;
                    }
                }
                System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds);
            }

            output.Save();
            return true;
        }
        public bool Execute1(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            StreamReader sr    = new StreamReader(Path.Combine(FileDirectory, "list.txt"));
            int          nfile = 0;

            while (!sr.EndOfStream)
            {
                sr.ReadLine();
                nfile++;
            }
            sr.Close();
            sr = new StreamReader(Path.Combine(FileDirectory, "list.txt"));
            string[] dirs = new string[nfile];
            for (int i = 0; i < nfile; i++)
            {
                var str = sr.ReadLine();
                dirs[i] = Path.Combine(FileDirectory, str + "_2.tif");
            }

            int[] bandlist = new int[] { 4, 3, 2 };
            //string[] dirs = Directory.GetFiles(FileDirectory, "*_2.tif");
            string        center_shp = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\Center35.shp";
            StreamWriter  sw         = new StreamWriter(Path.Combine(FileDirectory, "area.csv"));
            StreamWriter  sw_alpha   = new StreamWriter(Path.Combine(FileDirectory, "alpha.txt"));
            IFeatureSet   center_fs  = FeatureSet.Open(center_shp);
            List <double> vec        = new List <double>();

            try
            {
                double cell_area = 5 * 5;

                var center_pt  = center_fs.Features[0].Geometry.Coordinate;
                var center_vec = new double[3];
                var pt_vec     = new double[3];
                int progress   = 0;
                int count      = 1;
                int t          = 0;
                vec.Clear();
                foreach (var file in dirs)
                {
                    long    wcount     = 0;
                    var     temp       = Path.GetFileNameWithoutExtension(file);
                    var     daystr     = temp.Remove(10);
                    var     water_file = file.Replace("_2", "_water");
                    IRaster raster2    = Raster.OpenFile(file);
                    raster2.SaveAs(water_file);
                    IRaster raster3      = Raster.OpenFile(file.Replace("_2", "_3"));
                    IRaster raster4      = Raster.OpenFile(file.Replace("_2", "_4"));
                    IRaster raster_water = Raster.OpenFile(water_file);
                    double[,] img = new double[raster2.NumRows, raster2.NumColumns];
                    var cell = raster2.ProjToCell(center_pt);
                    center_vec[0] = raster2.Value[cell.Row, cell.Column];
                    center_vec[1] = raster3.Value[cell.Row, cell.Column];
                    center_vec[2] = raster4.Value[cell.Row, cell.Column];
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            if (raster2.Value[i, j] == raster2.NoDataValue)
                            {
                                img[i, j] = 0;
                                raster_water.Value[i, j] = 0;
                                sw_alpha.WriteLine(0);
                                vec.Add(0);
                            }
                            else
                            {
                                pt_vec[0] = raster2.Value[i, j];
                                pt_vec[1] = raster3.Value[i, j];
                                pt_vec[2] = raster4.Value[i, j];
                                var alpha = sam(pt_vec, center_vec);
                                if (alpha <= AlphaThreashhold)
                                {
                                    raster_water.Value[i, j] = 1;
                                    wcount++;
                                }
                                else
                                {
                                    raster_water.Value[i, j] = 0;
                                }
                                try
                                {
                                    raster_water.Value[i, j] = alpha;
                                }
                                catch (Exception ex)
                                {
                                    cancelProgressHandler.Progress("Package_Tool", progress, "Warning: " + ex.Message + " " + alpha);
                                    alpha = 0;
                                    raster_water.Value[i, j] = 0;
                                }
                                finally
                                {
                                    img[i, j] = alpha;
                                    vec.Add(alpha);
                                    sw_alpha.WriteLine(alpha);
                                }
                            }
                        }
                    }
                    var max   = vec.Max();
                    var min   = vec.Min();
                    var delta = max - min;
                    int k     = 0;
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            img[i, j] = (vec[k] - min) / delta * 255;
                            raster_water.Value[i, j] = img[i, j];
                            k++;
                        }
                    }

                    var sobled_img = sobel(img, raster2.NumRows, raster2.NumColumns);
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            raster_water.Value[i, j] = sobled_img[i, j];
                        }
                    }
                    var water_area = wcount * cell_area;
                    sw.WriteLine(daystr + "," + water_area);
                    raster2.Close();
                    raster3.Close();
                    raster4.Close();
                    raster_water.Save();
                    raster_water.Close();
                    progress = t * 100 / dirs.Length;
                    if (progress > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing: " + file);
                        count++;
                    }
                    t++;
                }
            }
            catch (Exception ex)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Error: " + ex.Message);
            }
            finally
            {
                sw_alpha.Close();
                sr.Close();
                sw.Close();
                center_fs.Close();
            }

            return(true);
        }