Exemplo n.º 1
0
        /// <summary>
        /// Makes a snow raster in bgd format from the downloaded SNODAS data file
        /// </summary>
        /// <param name="snodasDatFile">the SNODAS unzipped data file in .dat format</param>
        /// <param name="bgdFile">the output bgd data file</param>
        /// <returns>The IRaster object</returns>
        public IRaster MakeSnowRaster(string snodasDatFile, string bgdFile)
        {
            //for masked case rows and columns:
            int numCols = 6935;
            int numRows = 3351;

            //for masked case lat and long bounding box:
            Extent maskedExtent = new Extent(-124.7337, 24.9504, -66.9421, 52.8754);

            int numCells = numCols * numRows;

            //read the SNODAS .dat binary file into an array
            Int16[] binaryData = BinaryFileHelper.ReadBinaryArray(snodasDatFile, numCells);

            IRaster ras = Raster.Create(bgdFile, "bgd", numCols, numRows, 1, typeof(Int16), new string[0]);

            //set the properties of our raster: bounds, projection, NoDataValue
            ras.Bounds           = new RasterBounds(numRows, numCols, maskedExtent);
            ras.ProjectionString = "+proj=longlat +datum=WGS84 +no_defs";
            ras.NoDataValue      = -9999;

            //set the raster's values
            for (int row = 0; row < numRows; row++)
            {
                for (int col = 0; col < numCols; col++)
                {
                    ras.Value[row, col] = binaryData[row * numCols + col];
                }
            }
            ras.Save();
            return(ras);
        }
Exemplo n.º 2
0
        public void BitmapGetterDisposeOnChange()
        {
            var raster = Raster.Create(FileTools.GetTempFileName(".bgd"), string.Empty, 1, 1, 1, typeof(byte), new[] { string.Empty });

            try
            {
                var target = new RasterLayer(raster);
                Assert.IsTrue(target.IsDisposed);
            }
            finally
            {
                File.Delete(raster.Filename);
            }
        }
Exemplo n.º 3
0
        public void GetNoDataCellCountTest()
        {
            var          path               = FileTools.GetTempFileName(".bgd");
            const double Xllcorner          = 3267132.224761;
            const double Yllcorner          = 5326939.203029;
            const int    Ncols              = 512;
            const int    Nrows              = 128;
            const int    FrequencyOfNoValue = 5;

            const double Cellsize = 500;
            var          x2       = Xllcorner + (Cellsize * Ncols);
            var          y2       = Yllcorner + (Cellsize * Nrows);
            var          myExtent = new Extent(Xllcorner, Yllcorner, x2, y2);
            var          target   = (Raster)Raster.Create(path, string.Empty, Ncols, Nrows, 1, typeof(double), new[] { string.Empty });

            target.Bounds      = new RasterBounds(Nrows, Ncols, myExtent);
            target.NoDataValue = -9999;
            var mRow = target.Bounds.NumRows;
            var mCol = target.Bounds.NumColumns;

            for (var row = 0; row < mRow; row++)
            {
                for (var col = 0; col < mCol; col++)
                {
                    if (row % FrequencyOfNoValue == 0)
                    {
                        target.Value[row, col] = -9999d;
                    }
                    else
                    {
                        target.Value[row, col] = 2d;
                    }
                }
            }

            target.Save();

            const long Expected = ((Nrows / FrequencyOfNoValue) * Ncols) + Ncols;
            var        actual   = target.GetNoDataCellCount();

            Assert.AreEqual(Expected, actual);

            try
            {
                File.Delete(path);
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// This uses the BaseValue and BinSize properties in order to categorize the values
        /// according to the source.  The cells in the bin will receive a value that is equal
        /// to the midpoint between the range.  So a range from 0 to 10 will all have the value
        /// of 5.  Values with no data continue to be marked as NoData.
        /// </summary>
        /// <param name="source">The source raster.</param>
        /// <param name="destName">The output filename.</param>
        /// <param name="progressHandler">The progress handler for messages.</param>
        /// <returns>The IRaster of binned values from the original source.</returns>
        public bool BinRaster(IRaster source, string destName, ICancelProgressHandler progressHandler)
        {
            IRaster result;

            try
            {
                result            = Raster.Create(destName, string.Empty, source.NumColumns, source.NumRows, source.NumBands, source.DataType, new string[] { });
                result.Bounds     = source.Bounds.Copy();
                result.Projection = source.Projection;
            }
            catch (Exception)
            {
                File.Copy(source.Filename, destName);
                result = Raster.Open(destName);
            }

            bool finished;

            if (source.DataType == typeof(int))
            {
                finished = BinRaster(source.ToRaster <int>(), result.ToRaster <int>(), progressHandler);
            }
            else if (source.DataType == typeof(float))
            {
                finished = BinRaster(source.ToRaster <float>(), result.ToRaster <float>(), progressHandler);
            }
            else if (source.DataType == typeof(short))
            {
                finished = BinRaster(source.ToRaster <short>(), result.ToRaster <short>(), progressHandler);
            }
            else if (source.DataType == typeof(byte))
            {
                finished = BinRaster(source.ToRaster <byte>(), result.ToRaster <byte>(), progressHandler);
            }
            else if (source.DataType == typeof(double))
            {
                finished = BinRaster(source.ToRaster <double>(), result.ToRaster <double>(), progressHandler);
            }
            else
            {
                finished = BinRasterSlow(source, result, progressHandler);
            }

            if (finished)
            {
                result.Save();
            }

            return(finished);
        }
Exemplo n.º 5
0
        public void GetNoDataCellCountTest()
        {
            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\..\..\..\Data\GetNoDataCellCountTest.BGD";

            const double xllcorner          = 3267132.224761;
            const double yllcorner          = 5326939.203029;
            const int    ncols              = 512;
            const int    nrows              = 128;
            const int    frequencyOfNoValue = 5;

            const double cellsize = 500;
            double       x2       = xllcorner + (cellsize * ncols);
            double       y2       = yllcorner + (cellsize * nrows);
            Extent       myExtent = new Extent(xllcorner, yllcorner, x2, y2);
            Raster       target;

            target             = Raster.Create(path, String.Empty, ncols, nrows, 1, typeof(double), new[] { String.Empty }) as Raster;
            target.Bounds      = new RasterBounds(nrows, ncols, myExtent);
            target.NoDataValue = -9999;
            int mRow = target.Bounds.NumRows;
            int mCol = target.Bounds.NumColumns;

            for (int row = 0; row < mRow; row++)
            {
                for (int col = 0; col < mCol; col++)
                {
                    if (row % frequencyOfNoValue == 0)
                    {
                        target.Value[row, col] = -9999d;
                    }
                    else
                    {
                        target.Value[row, col] = 2d;
                    }
                }
            }
            target.Save();

            long expected = (nrows / frequencyOfNoValue) * ncols + ncols;
            long actual;

            actual = target.GetNoDataCellCount();
            Assert.AreEqual(expected, actual);

            System.IO.File.Delete(path);
        }
Exemplo n.º 6
0
        public void BitmapGetter_DisposeOnChange()
        {
            var raster = Raster.Create(FileTools.GetTempFileName(".bgd"), String.Empty, 1, 1, 1, typeof(byte), new[] { String.Empty });

            try
            {
                var target = new RasterLayer(raster)
                {
                    BitmapGetter = new ImageData()
                };
                var bitmapGetter = (DisposeBase)target.BitmapGetter;
                target.BitmapGetter = null;
                Assert.IsTrue(bitmapGetter.IsDisposed);
            }
            finally
            {
                File.Delete(raster.Filename);
            }
        }
Exemplo n.º 7
0
        public void SmallRasterTest()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "doubletest.BGD");

            const double xllcorner = 3267132.224761;
            const double yllcorner = 5326939.203029;
            const int    ncols     = 1098;
            const int    nrows     = 725;
            const double cellsize  = 500;
            double       x2        = xllcorner + (cellsize * ncols);
            double       y2        = yllcorner + (cellsize * nrows);
            Extent       myExtent  = new Extent(xllcorner, yllcorner, x2, y2);
            IRaster      output;

            output             = Raster.Create(path, String.Empty, ncols, nrows, 1, typeof(double), new[] { String.Empty });
            output.Bounds      = new RasterBounds(nrows, ncols, myExtent);
            output.NoDataValue = -9999;
            int mRow = output.Bounds.NumRows;
            int mCol = output.Bounds.NumColumns;

            // fill all cells to value=2 only for testing
            for (int row = 0; row < mRow; row++)
            {
                for (int col = 0; col < mCol; col++)
                {
                    output.Value[row, col] = 2d;
                }
            }
            output.Save();

            IRaster testRaster = Raster.Open(path);

            for (int row = 0; row < mRow; row++)
            {
                for (int col = 0; col < mCol; col++)
                {
                    Assert.AreEqual(output.Value[row, col], testRaster.Value[row, col]);
                }
            }

            File.Delete(path);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a new raster with the specified cell size.  If the cell size
        /// is zero, this will default to the shorter of the width or height
        /// divided by 256.  If the cell size produces a raster that is greater
        /// than 8, 000 pixels in either dimension, it will be re-sized to
        /// create an 8, 000 length or width raster.
        /// </summary>
        /// <param name="fs">The featureset to convert to a raster.</param>
        /// <param name="extent">Force the raster to this specified extent.</param>
        /// <param name="cellSize">The double extent of the cell.</param>
        /// <param name="fieldName">The integer field index of the file.</param>
        /// <param name="outputFileName">The fileName of the raster to create.</param>
        /// <param name="driverCode">The optional GDAL driver code to use if using GDAL
        /// for a format that is not discernable from the file extension.  An empty string
        ///  is usually perfectly acceptable here.</param>
        /// <param name="options">For GDAL rasters, they can be created with optional parameters
        ///  passed in as a string array.  In most cases an empty string is perfectly acceptable.</param>
        /// <param name="progressHandler">An interface for handling the progress messages.</param>
        /// <returns>Generates a raster from the vectors.</returns>
        public static IRaster ToRaster(IFeatureSet fs, Extent extent, double cellSize, string fieldName, string outputFileName, string driverCode, string[] options, IProgressHandler progressHandler)
        {
            Extent env = extent;

            if (cellSize == 0)
            {
                if (env.Width < env.Height)
                {
                    cellSize = env.Width / 256;
                }
                else
                {
                    cellSize = env.Height / 256;
                }
            }

            int w = (int)Math.Ceiling(env.Width / cellSize);

            if (w > 8000)
            {
                w        = 8000;
                cellSize = env.Width / 8000;
            }

            int h = (int)Math.Ceiling(env.Height / cellSize);

            if (h > 8000)
            {
                h = 8000;
            }

            Bitmap   bmp = new(w, h);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Transparent);
            g.SmoothingMode     = SmoothingMode.None;
            g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            Hashtable colorTable;
            MapArgs   args = new(new Rectangle(0, 0, w, h), env, g);

            switch (fs.FeatureType)
            {
            case FeatureType.Polygon:
            {
                MapPolygonLayer mpl = new(fs);
                PolygonScheme   ps  = new();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;

                // first draw the normal colors and then the selection colors on top
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    }, false);
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    }, true);
            }

            break;

            case FeatureType.Line:
            {
                MapLineLayer mpl = new(fs);
                LineScheme   ps  = new();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;

                // first draw the normal colors and then the selection colors on top
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    }, false);
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    }, true);
            }

            break;

            default:
            {
                MapPointLayer mpl = new(fs);
                PointScheme   ps  = new();
                colorTable    = ps.GenerateUniqueColors(fs, fieldName);
                mpl.Symbology = ps;

                // first draw the normal colors and then the selection colors on top
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    }, false);
                mpl.DrawRegions(args, new List <Extent> {
                        env
                    }, true);
            }

            break;
            }

            Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType;

            // We will try to convert to double if it is a string
            if (tp == typeof(string))
            {
                tp = typeof(double);
            }

            InRamImageData image = new(bmp, env);
            ProgressMeter  pm    = new(progressHandler, "Converting To Raster Cells", h);

            var output = Raster.Create(outputFileName, driverCode, w, h, 1, tp, options);

            output.Bounds = new RasterBounds(h, w, env);

            double noDataValue = output.NoDataValue;

            if (fieldName != "FID")
            {
                // We can't use this method to calculate Max on a non-existent FID field.
                double dtMax = Convert.ToDouble(fs.DataTable.Compute("Max(" + fieldName + ")", string.Empty));
                double dtMin = Convert.ToDouble(fs.DataTable.Compute("Min(" + fieldName + ")", string.Empty));

                if (dtMin <= noDataValue && dtMax >= noDataValue)
                {
                    if (dtMax != GetFieldValue(tp, "MaxValue"))
                    {
                        output.NoDataValue = noDataValue;
                    }
                    else if (dtMin != GetFieldValue(tp, "MinValue"))
                    {
                        output.NoDataValue = noDataValue;
                    }
                }
            }

            List <RcIndex> locations   = new();
            List <string>  failureList = new();

            for (int row = 0; row < h; row++)
            {
                for (int col = 0; col < w; col++)
                {
                    Color c = image.GetColor(row, col);
                    if (c.A == 0)
                    {
                        output.Value[row, col] = output.NoDataValue;
                    }
                    else
                    {
                        if (colorTable.ContainsKey(c) == false)
                        {
                            if (c.A < 125)
                            {
                                output.Value[row, col] = output.NoDataValue;
                                continue;
                            }

                            // Use a color matching distance to pick the closest member
                            object val = GetCellValue(w, h, row, col, image, c, colorTable, locations);

                            output.Value[row, col] = GetDouble(val, failureList);
                        }
                        else
                        {
                            output.Value[row, col] = GetDouble(colorTable[c], failureList);
                        }
                    }
                }

                pm.CurrentValue = row;
            }

            const int MaxIterations = 5;
            int       iteration     = 0;

            while (locations.Count > 0)
            {
                List <RcIndex> newLocations = new();
                foreach (RcIndex location in locations)
                {
                    object val = GetCellValue(w, h, location.Row, location.Column, image, image.GetColor(location.Row, location.Column), colorTable, newLocations);
                    output.Value[location.Row, location.Column] = GetDouble(val, failureList);
                }

                locations = newLocations;
                iteration++;
                if (iteration > MaxIterations)
                {
                    break;
                }
            }

            pm.Reset();
            return(output);
        }