示例#1
0
        /// <summary>
        /// Retrieves the data from the cell that is closest to the specified coordinates. This will
        /// return a No-Data value if the specified coordintes are outside of the grid.
        /// </summary>
        /// <param name="raster">The raster to get the value from</param>
        /// <param name="x">The longitude or horizontal coordinate</param>
        /// <param name="y">The latitude or vertical coordinate</param>
        /// <returns>The double value of the cell that has a center closest to the specified coordinates</returns>
        public static double GetNearestValue(this IRaster raster, double x, double y)
        {
            RcIndex position = raster.ProjToCell(x, y);

            if (position.Row < 0 || position.Row >= raster.NumRows)
            {
                return(raster.NoDataValue);
            }
            if (position.Column < 0 || position.Column >= raster.NumColumns)
            {
                return(raster.NoDataValue);
            }
            return(raster.Value[position.Row, position.Column]);
        }
示例#2
0
        /// <summary>
        /// Retrieves the data from the cell that is closest to the specified coordinates. This will
        /// return a No-Data value if the specified coordintes are outside of the grid.
        /// </summary>
        /// <param name="raster">The raster to get the value from</param>
        /// <param name="location">A valid implementation of Icoordinate specifying the geographic location.</param>
        /// <returns>The value of type T of the cell that has a center closest to the specified coordinates</returns>
        public static double GetNearestValue(this IRaster raster, Coordinate location)
        {
            RcIndex position = raster.ProjToCell(location.X, location.Y);

            if (position.Row < 0 || position.Row >= raster.NumRows)
            {
                return(raster.NoDataValue);
            }
            if (position.Column < 0 || position.Column >= raster.NumColumns)
            {
                return(raster.NoDataValue);
            }
            return(raster.Value[position.Row, position.Column]);
        }
示例#3
0
        /// <summary>
        /// Retrieves the location from the cell that is closest to the specified coordinates. This will
        /// do nothing if the specified coordinates are outside of the raster.
        /// </summary>
        /// <param name="raster">The IRaster to set the value for</param>
        /// <param name="x">The longitude or horizontal coordinate</param>
        /// <param name="y">The latitude or vertical coordinate</param>
        /// <param name="value">The value to assign to the nearest cell to the specified location</param>
        public static void SetNearestValue(this IRaster raster, double x, double y, double value)
        {
            RcIndex position = raster.ProjToCell(x, y);

            if (position.Row < 0 || position.Row >= raster.NumRows)
            {
                return;
            }
            if (position.Column < 0 || position.Column >= raster.NumColumns)
            {
                return;
            }
            raster.Value[position.Row, position.Column] = value;
        }
示例#4
0
        /// <summary>
        /// Retrieves the location from the cell that is closest to the specified coordinates. This will
        /// do nothing if the specified coordinates are outside of the raster.
        /// </summary>
        /// <param name="raster">The IRaster to set the value for</param>
        /// <param name="location">An Icoordinate specifying the location</param>
        /// <param name="value">The value to assign to the nearest cell to the specified location</param>
        public static void SetNearestValue(this IRaster raster, Coordinate location, double value)
        {
            RcIndex position = raster.ProjToCell(location.X, location.Y);

            if (position.Row < 0 || position.Row >= raster.NumRows)
            {
                return;
            }
            if (position.Column < 0 || position.Column >= raster.NumColumns)
            {
                return;
            }
            raster.Value[position.Row, position.Column] = value;
        }
示例#5
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            var fea    = (cmbGrid.SelectedValue as MapPointLayer).DataSet;
            var coords = from ff in fea.Features select ff.Coordinates.First();

            _Mapping.FromDataTable(dataGridView1.DataSource as DataTable);
            foreach (var para in _Paras)
            {
                var array_para = para as ArrayParam <float>;
                int i          = 0;
                foreach (var cc in coords)
                {
                    var cell = _SelectedRaster.ProjToCell(cc);
                    if (cell != null && cell.Row >= 0 && cell.Column >= 0)
                    {
                        var uid = _SelectedRaster.Value[cell.Row, cell.Column].ToString();
                        array_para.Values[i] = _Mapping.Map(para.Name, uid);
                    }
                    i++;
                }
            }
        }
示例#6
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var fs = FeatureSet.Open(TargetFeatureFile);

            if (fs != null && File.Exists(FilenameList))
            {
                var          npt      = fs.NumRows();
                Coordinate[] coors    = new Coordinate[npt];
                int          progress = 0;
                for (int i = 0; i < npt; i++)
                {
                    var geo_pt = fs.GetFeature(i).Geometry;
                    coors[i] = geo_pt.Coordinate;
                }
                List <string> files = new List <string>();
                StreamReader  sr    = new StreamReader(FilenameList);
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    if (TypeConverterEx.IsNotNull(line))
                    {
                        files.Add(line.Trim());
                    }
                }
                sr.Close();
                if (files != null)
                {
                    int nstep   = files.Count();
                    var mat_out = new DataCube <float>(1, nstep, npt);
                    mat_out.Name           = OutputDataCube;
                    mat_out.Variables      = new string[] { VariableName };
                    mat_out.TimeBrowsable  = true;
                    mat_out.AllowTableEdit = false;
                    for (int t = 0; t < nstep; t++)
                    {
                        IRaster raster = Raster.Open(files[t]);
                        for (int i = 0; i < npt; i++)
                        {
                            var cell = raster.ProjToCell(coors[i]);
                            if (cell != null && cell.Row > 0)
                            {
                                mat_out[0, t, i] = (float)raster.Value[cell.Row, cell.Column];
                            }
                            else
                            {
                                mat_out[0, t, i] = 0;
                            }
                        }
                        progress = t * 100 / nstep;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing raster:" + files[t]);
                    }
                    Workspace.Add(mat_out);
                    fs.Close();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 50, "Failed to run. The input parameters are incorrect.");
                return(false);
            }
        }
 private void fillTrackGrid(IRaster gridTrack, IFeatureSet polyOut, int idxToFill)
 {
     int rowStart;
     int rowStop;
     int colStart;
     int colStop;
     RcIndex start;
     RcIndex stop;
     ICoordinate I;
     start = gridTrack.ProjToCell(polyOut.Features[idxToFill].Envelope.Minimum.X, polyOut.Features[idxToFill].Envelope.Maximum.Y);
     stop = gridTrack.ProjToCell(polyOut.Features[idxToFill].Envelope.Maximum.X, polyOut.Features[idxToFill].Envelope.Minimum.Y);
     rowStart = start.Row;
     colStart = start.Column;
     rowStop = stop.Row;
     colStop = stop.Column;
     for (int rowcell = rowStart; rowcell <= rowStop; rowcell++)
     {
         for (int colcell = colStart; colcell <= colStop; colcell++)
         {
             I = gridTrack.CellToProj(rowcell, colcell);
             Point pt = new Point(I);
             if (polyOut.Features[idxToFill].Covers(pt))
             {
                 gridTrack.Value[rowcell, colcell] = 1;
             }
         }
     }
 }
示例#8
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet      fs            = FeatureSet.Open(FeatureFile);
            int              var_index     = 0;
            int              con_var_index = 0;
            var              mat           = Get3DMat(Matrix, ref var_index);
            DataCube <float> con_mat       = null;

            if (Filter != FilterMode.None)
            {
                con_mat = Get3DMat(ConMat, ref con_var_index);
            }
            if (fs != null && mat != null)
            {
                IRaster raster = Raster.Open(TemplateFile);
                raster.SaveAs(TemplateFile + ".tif");
                int          fea_count = fs.NumRows();
                Coordinate[] coors     = new Coordinate[fea_count];
                for (int i = 0; i < fea_count; i++)
                {
                    coors[i] = fs.GetFeature(i).Geometry.Coordinates[0];
                }
                var      nsteps   = mat.Size[1];
                int      progress = 0;
                string[] fns      = new string[nsteps];
                if (mat.DateTimes != null)
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        fns[t] = string.Format("{0}_{1}.tif", VariableName, mat.DateTimes[t].ToString(DateFormat));
                    }
                }
                else
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        fns[t] = string.Format("{0}_{1}.tif", VariableName, t.ToString("0000"));
                    }
                }
                if (Filter != FilterMode.None)
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        string outras = Path.Combine(Direcotry, fns[t]);
                        int    i      = 0;
                        foreach (var cor in coors)
                        {
                            var cell = raster.ProjToCell(cor);
                            var temp = mat[var_index, t, i] * Scale;

                            if (Filter == FilterMode.Maximum)
                            {
                                if (temp > con_mat[0, 0, i])
                                {
                                    temp = con_mat[0, 0, i];
                                }
                            }
                            else if (Filter == FilterMode.Minimum)
                            {
                                if (temp < con_mat[0, 0, i])
                                {
                                    temp = con_mat[0, 0, i];
                                }
                            }

                            raster.Value[cell.Row, cell.Column] = temp;
                            i++;
                        }
                        raster.SaveAs(outras);

                        progress = t * 100 / nsteps;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Saving raster to:" + outras);
                    }
                }
                else
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        string outras = Path.Combine(Direcotry, fns[t]);
                        int    i      = 0;
                        foreach (var cor in coors)
                        {
                            var cell = raster.ProjToCell(cor.X - 500, cor.Y + 500);
                            var temp = mat[var_index, t, i] * Scale;
                            raster.Value[cell.Row, cell.Column] = temp;
                            i++;
                        }
                        raster.SaveAs(outras);

                        progress = t * 100 / nsteps;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Saving raster to:" + outras);
                    }
                }
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Failed to run. The input parameters are incorrect.");
                return(false);
            }
        }
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int progress = 0;
            int count    = 1;

            if (_target_layer != null)
            {
                var nrow    = _target_layer.NumRows();
                var dx      = System.Math.Sqrt(_target_layer.GetFeature(0).Geometry.Area);
                int nsample = (int)System.Math.Floor(dx / _dem_layer.CellHeight);
                var mat     = new DataCube <float>(1, 1, nrow);
                mat.Name           = Matrix;
                mat.Variables      = new string[] { Matrix };
                mat.TimeBrowsable  = false;
                mat.AllowTableEdit = true;
                List <Coordinate> list = new List <Coordinate>();
                if (_target_layer.FeatureType == FeatureType.Polygon)
                {
                    for (int i = 0; i < nrow; i++)
                    {
                        float sum_cellv = 0;
                        int   npt       = 0;
                        list.Clear();
                        var fea = _target_layer.GetFeature(i).Geometry;
                        var x0  = (from p in fea.Coordinates select p.X).Min();
                        var y0  = (from p in fea.Coordinates select p.Y).Min();
                        for (int r = 0; r <= nsample; r++)
                        {
                            var y = y0 + r * _dem_layer.CellHeight;
                            for (int c = 0; c <= nsample; c++)
                            {
                                var        x  = x0 + c * _dem_layer.CellWidth;
                                Coordinate pt = new Coordinate(x, y);
                                list.Add(pt);
                            }
                        }
                        foreach (var pt in list)
                        {
                            var cell = _dem_layer.ProjToCell(pt);
                            if (cell != null && cell.Row > 0)
                            {
                                var buf = (float)_dem_layer.Value[cell.Row, cell.Column];
                                if (buf != _dem_layer.NoDataValue)
                                {
                                    sum_cellv += buf;
                                    npt++;
                                }
                            }
                        }
                        if (npt > 0)
                        {
                            sum_cellv = sum_cellv / npt;
                        }
                        mat[0, 0, i] = sum_cellv;

                        progress = i * 100 / nrow;
                        if (progress > count)
                        {
                            cancelProgressHandler.Progress("Package_Tool", progress, "Processing polygon: " + i);
                            count++;
                        }
                    }
                }
                else
                {
                    Coordinate[] coors = new Coordinate[nrow];

                    for (int i = 0; i < nrow; i++)
                    {
                        var geo_pt = _target_layer.GetFeature(i).Geometry;
                        coors[i] = geo_pt.Coordinate;
                    }

                    for (int i = 0; i < nrow; i++)
                    {
                        var cell = _dem_layer.ProjToCell(coors[i]);
                        if (cell != null && cell.Row > 0)
                        {
                            mat[0, 0, i] = (float)_dem_layer.Value[cell.Row, cell.Column];
                        }
                        progress = i * 100 / nrow;
                        if (progress > count)
                        {
                            cancelProgressHandler.Progress("Package_Tool", progress, "Processing point: " + i);
                            count++;
                        }
                    }
                }
                Workspace.Add(mat);
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Error message: the input layers are incorrect.");
                return(false);
            }
        }
示例#10
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);
        }
示例#11
0
        /// <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;
        }
        /// <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;
        }
示例#13
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);
        }
        /// <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;
        }
        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 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;
        }
示例#17
0
        //        #endregion

        //        #region "Create SWAT *.Fig"
        //        /// <summary>
        //        /// A function to generate a *.fig file from joined basins for use in SWAT.
        //        /// </summary>
        //        /// <param name="JoinBasinShapePath"></param>
        //        /// <param name="ResultFigPath"></param>
        //        /// <param name="callback"></param>
        //        /// <returns></returns>
        //        public static bool CreateSWATFig(string JoinBasinShapePath, string ResultFigPath, IProgressHandler callback)
        //        {
        //            int OutletIDFieldNum = -1, DSWSIDFieldNum = -1, USWSIDFieldNum1 = -1, USWSIDFieldNum2 = -1, ReservoirFieldNum = -1;
        //            if (callback != null) callback.Progress("Status", 0, "Create SWAT *.fig");
        //            Shapefile sf = new Shapefile();

        //            sf.Open(JoinBasinShapePath, null);
        //            for (int i = 0; i < sf.NumFields; i++)
        //            {
        //                switch (sf.DataTable.Columns[i].ColumnName)
        //                {
        //                    case "OutletID":
        //                        OutletIDFieldNum = i;
        //                        break;
        //                    case "DSWSID":
        //                        DSWSIDFieldNum = i;
        //                        break;
        //                    case "USWSID1":
        //                        USWSIDFieldNum1 = i;
        //                        break;
        //                    case "USWSID2":
        //                        USWSIDFieldNum2 = i;
        //                        break;
        //                    case "Reservoir":
        //                        ReservoirFieldNum = i;
        //                        break;
        //                }
        //            }
        //            if (OutletIDFieldNum == -1 || DSWSIDFieldNum == -1 || USWSIDFieldNum1 == -1 || USWSIDFieldNum2 == -1)
        //            {
        //                return false;
        //            }

        //            StreamWriter fig = new StreamWriter(ResultFigPath);

        //            Stack<int> substack = new Stack<int>();
        //            List<int> subIDs = new List<int>();
        //            int Hyd_Stor_Num = 0;
        //            int Res_Num = 0;
        //            int InFlow_Num1 = 0;
        //            int InFlow_Num2 = 0;
        //            int InFlow_ID = 0;
        //            int UpstreamCount, UpstreamFinishedCount;

        //            //Write subbasins
        //            for (int i = 0; i < sf.NumRows(); i++)
        //            {
        //                Hyd_Stor_Num++;
        //                fig.Write("subbasin       1{0,6:G6}{0,6:G6}                              Subbasin: {0:G}\n          {0,5:D5}0000.sub\n", Hyd_Stor_Num);
        //                if (sf.get_CellValue(DSWSIDFieldNum, i).ToString() == "-1")
        //                {
        //                    substack.Push(i);
        //                }
        //                subIDs.Add(-1);
        //            }

        //            //Write the rest
        //            int curridx;
        //            string currUS1, currUS2;
        //            int currUS1idx, currUS2idx, currUS1ID, currUS2ID;
        //            while (substack.Count > 0)
        //            {
        //                curridx = substack.Pop();

        //                currUS1 = sf.get_CellValue(USWSIDFieldNum1, curridx).ToString();
        //                currUS2 = sf.get_CellValue(USWSIDFieldNum2, curridx).ToString();
        //                if (currUS1 == "-1" && currUS2 == "-1") //then we're on an outer reach.
        //                {
        //                    if (subIDs[curridx] == -1) //then it hasn't been added yet. add a route
        //                    {
        //                        Hyd_Stor_Num++;
        //                        InFlow_Num1 = curridx + 1;
        //                        fig.Write("route          2{0,6:G6}{1,6:G6}{2,6:G6}\n          {1,5:D5}0000.rte{1,5:D5}0000.swq\n", Hyd_Stor_Num, curridx + 1, InFlow_Num1);
        //                        subIDs[curridx] = Hyd_Stor_Num;

        //                        if (sf.get_CellValue(ReservoirFieldNum, curridx).ToString() == "1") //it's a reservoir
        //                        {
        //                            Hyd_Stor_Num++;
        //                            Res_Num++;
        //                            InFlow_Num1 = Hyd_Stor_Num - 1;
        //                            InFlow_ID = curridx + 1;
        //                            fig.Write("routres        3{0,6:G6}{1,6:G6}{2,6:G6}{3,6:G6}\n          {3,5:D5}0000.res{3,5:D5}0000.lwq\n", Hyd_Stor_Num, Res_Num, InFlow_Num1, InFlow_ID);
        //                            subIDs[curridx] = Hyd_Stor_Num;
        //                        }
        //                    }
        //                }
        //                else //we're on a middle or final reach
        //                {
        //                    UpstreamCount = 0;
        //                    UpstreamFinishedCount = 0;

        //                    //Get the hydro IDs and indexes of the upstream links
        //                    currUS1ID = -2;
        //                    currUS2ID = -2;
        //                    currUS1idx = -1;
        //                    currUS2idx = -1;
        //                    if (currUS1 != "-1")
        //                    {
        //                        UpstreamCount++;
        //                        currUS1idx = GetBasinIndexByID(sf, Int32.Parse(currUS1));
        //                        if (currUS1idx >= 0)
        //                        {
        //                            currUS1ID = subIDs[currUS1idx];
        //                            if (currUS1ID != -1)
        //                            {
        //                                UpstreamFinishedCount++;
        //                            }
        //                        }
        //                    }
        //                    if (currUS2 != "-1")
        //                    {
        //                        UpstreamCount++;
        //                        currUS2idx = GetBasinIndexByID(sf, Int32.Parse(currUS2));
        //                        if (currUS2idx >= 0)
        //                        {
        //                            currUS2ID = subIDs[currUS2idx];
        //                            if (currUS2ID != -1)
        //                            {
        //                                UpstreamFinishedCount++;
        //                            }
        //                        }
        //                    }

        //                    if (UpstreamCount == UpstreamFinishedCount) //all upstreams finished
        //                    {
        //                        if (currUS1ID != -2 && currUS2ID != -2) //It has two upstream, have to do a double sum
        //                        {
        //                            Hyd_Stor_Num++;
        //                            InFlow_Num1 = currUS1ID;
        //                            InFlow_Num2 = curridx + 1;
        //                            fig.Write("add            5{0,6:G6}{1,6:G6}{2,6:G6}\n", Hyd_Stor_Num, InFlow_Num1, InFlow_Num2);

        //                            Hyd_Stor_Num++;
        //                            InFlow_Num1 = currUS2ID;
        //                            InFlow_Num2 = Hyd_Stor_Num - 1;
        //                            fig.Write("add            5{0,6:G6}{1,6:G6}{2,6:G6}\n", Hyd_Stor_Num, InFlow_Num1, InFlow_Num2);
        //                        }
        //                        else if (currUS1ID != -2) //It only has one upstream, check if it's 1
        //                        {
        //                            Hyd_Stor_Num++;
        //                            InFlow_Num1 = currUS1ID;
        //                            InFlow_Num2 = curridx + 1;
        //                            fig.Write("add            5{0,6:G6}{1,6:G6}{2,6:G6}\n", Hyd_Stor_Num, InFlow_Num1, InFlow_Num2);
        //                        }
        //                        else if (currUS2ID != -2) //It only has one upstream, check if it's 2
        //                        {
        //                            Hyd_Stor_Num++;
        //                            InFlow_Num1 = currUS2ID;
        //                            InFlow_Num2 = curridx + 1;
        //                            fig.Write("add            5{0,6:G6}{1,6:G6}{2,6:G6}\n", Hyd_Stor_Num, InFlow_Num1, InFlow_Num2);
        //                        }

        //                        //After summing, create the route and possibly reservoir
        //                        Hyd_Stor_Num++;
        //                        InFlow_Num1 = Hyd_Stor_Num - 1;
        //                        fig.Write("route          2{0,6:G6}{1,6:G6}{2,6:G6}\n          {1,5:D5}0000.rte{1,5:D5}0000.swq\n", Hyd_Stor_Num, curridx + 1, InFlow_Num1);
        //                        subIDs[curridx] = Hyd_Stor_Num;

        //                        if (sf.get_CellValue(ReservoirFieldNum, curridx).ToString() == "1")
        //                        {
        //                            Hyd_Stor_Num++;
        //                            Res_Num++;
        //                            InFlow_Num1 = Hyd_Stor_Num - 1;
        //                            InFlow_ID = curridx + 1;
        //                            fig.Write("routres        3{0,6:G6}{1,6:G6}{2,6:G6}{3,6:G6}\n          {3,5:D5}0000.res{3,5:D5}0000.lwq\n", Hyd_Stor_Num, Res_Num, InFlow_Num1, InFlow_ID);
        //                            subIDs[curridx] = Hyd_Stor_Num;
        //                        }
        //                    }
        //                    else //There are upstream items that need to still be processed before this one
        //                    {
        //                        substack.Push(curridx);
        //                        if (currUS1idx != -1 && currUS1ID == -1)
        //                        {
        //                            substack.Push(currUS1idx);
        //                        }
        //                        if (currUS2idx != -1 && currUS2ID == -1)
        //                        {
        //                            substack.Push(currUS2idx);
        //                        }
        //                    }
        //                }

        //            }

        //            //Write out the saveconc and finish commands
        //            int SaveFile_Num = 1;
        //            int Print_Freq = 0; //0 for daily, 1 for hourly
        //            fig.Write("saveconc      14{0,6:G6}{1,6:G6}{2,6:G6}\n          watout.dat\n", Hyd_Stor_Num, SaveFile_Num, Print_Freq);
        //            fig.WriteLine("finish         0");

        //            fig.Close();
        //            sf.Close();
        //            return true;
        //        }
        //        #endregion

        //        #region "Hydrology Private Helper Functions"

        private static void GetStreamElevationPoints(int sindx, IFeatureSet streamShape, IRaster demGrid, out double elevLow, out double elevHigh)
        {
            var shapePoints = streamShape.get_Shape(sindx).NumPoints;
            elevLow = 10000000;
            elevHigh = -1000000;
            for (var i = 0; i < shapePoints; i += 2)
            {
                var pt = streamShape.get_Shape(sindx).Coordinates[i];

                RcIndex position = demGrid.ProjToCell(pt.X, pt.Y);
                if (position.IsEmpty()) continue;

                double currVal = demGrid.Value[position.Row, position.Column];
                if (currVal < elevLow)
                {
                    elevLow = currVal;
                }

                if (currVal > elevHigh)
                {
                    elevHigh = currVal;
                }
            }
        }
示例#18
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);
        }
示例#19
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;
        }
示例#20
0
        private void PrePro(Dictionary<int, ReachFeatureCollection> fealist, out string msg)
        {
            double rs = 0, slope = 0, yint = 0;
            var dt = _out_sfr_layer.DataTable;
            var prj = MyAppManager.Instance.CompositionContainer.GetExportedValue<IProjectService>();
            msg = "";
            for (int i = 0; i < _out_sfr_layer.Features.Count; i++)
            {
                try
                {
                    var dr = dt.Rows[i];
                    var geo = _out_sfr_layer.GetFeature(i).Geometry;
                    if (geo.Length <= _dem_layer.CellHeight)
                    {
                        continue;
                    }
                    var npt = geo.Coordinates.Count();
                    int segid = int.Parse(dr[SegmentField].ToString()) + 1;
                    double[] dis = new double[npt];
                    double[] ac_dis = new double[npt];
                    double[] elvs = new double[npt];
                    double elev_av = 0;
                    var pt0 = geo.Coordinates[0];
                    var cell = _dem_layer.ProjToCell(pt0.X, pt0.Y);
                    double ad = 0;
                    dis[0] = 0;
                    elvs[0] = _dem_layer.Value[cell.Row, cell.Column];
                    for (int j = 0; j < npt; j++)
                    {
                       cell = _ad_layer.ProjToCell(geo.Coordinates[j].X, geo.Coordinates[j].Y);
                       ad += _ad_layer.Value[cell.Row, cell.Column];
                    }
                    ad = ad / npt;
                    for (int j = 1; j < npt; j++)
                    {
                        cell = _dem_layer.ProjToCell(geo.Coordinates[j].X, geo.Coordinates[j].Y);
                        elvs[j] = _dem_layer.Value[cell.Row, cell.Column];
                        dis[j] = SpatialDistance.DistanceBetween(geo.Coordinates[j - 1], geo.Coordinates[j]);
                    }
                    for (int j = 0; j < npt; j++)
                    {
                        ac_dis[j] = dis.Take(j + 1).Sum();
                    }

                    MyStatisticsMath.LinearRegression(ac_dis, elvs, 0, elvs.Length, out rs, out yint, out slope);

                    if (slope < 0)
                    {
                        slope = -slope;
                    }
                    else if (slope == 0)
                    {
                        slope = _minum_slope;
                    }

                    for (int j = 0; j < npt; j++)
                    {
                        elvs[j] = yint + slope * ac_dis[j];
                    }
                    elev_av = elvs.Average();

                    if (slope < _minum_slope)
                        slope = _minum_slope;
                    if (slope > _maximum_slope)
                        slope = _maximum_slope;

                    var rch = new ReachFeature()
                    {
                        Row = dr,
                        Elevation = elev_av,
                        Slope = slope
                    };

                    if (fealist[segid].Reaches.ContainsKey(ad))
                    {
                        ad += i * 0.001;
                    }
                    fealist[segid].Reaches.Add(ad, rch);
                    fealist[segid].OutSegmentID = int.Parse(dr["DSLINKNO"].ToString());
                    dr["Length"] = geo.Length;
                }
                catch (Exception ex)
                {
                    msg += ex.Message + "\n";
                }
            }
        }
示例#21
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;
        }
        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);
        }