Ejemplo n.º 1
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string shpFileLoc = "";

            DA.GetData <string>("Shapefile Location", ref shpFileLoc);

            ////int SRef = 3857;
            GdalConfiguration.ConfigureOgr();
            GdalConfiguration.ConfigureGdal();

            OSGeo.OGR.Driver     drv = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
            OSGeo.OGR.DataSource ds  = OSGeo.OGR.Ogr.Open(shpFileLoc, 0);

            List <OSGeo.OGR.Layer> layerset = new List <OSGeo.OGR.Layer>();
            List <int>             fc       = new List <int>();

            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("FAILURE: Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fc.Add(featureCount);
                layerset.Add(layer);
            }

            //Get OGR envelope of Shapefile
            OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
            layerset[0].GetExtent(ext, 1);
            Point3d extMin = new Point3d();
            Point3d extMax = new Point3d();

            extMin.X = ext.MinX;
            extMin.Y = ext.MinY;
            extMax.X = ext.MaxX;
            extMax.Y = ext.MaxY;

            OSGeo.OSR.SpatialReference sr = layerset[0].GetSpatialRef();

            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");

            //Get the spatial refernce of the input Shapefile
            string sRef;

            sr.ExportToWkt(out sRef);

            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            //Get bounding box of data in Shapefile
            double[] extMinPT = new double[3] {
                extMin.X, extMin.Y, extMin.Z
            };
            double[] extMaxPT = new double[3] {
                extMax.X, extMax.Y, extMax.Z
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
            Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.ToXYZ(extPTmin), Heron.Convert.ToXYZ(extPTmax));

            //Declare trees
            GH_Structure <GH_String> fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>  gset    = new GH_Structure <GH_Point>();
            GH_Structure <GH_String> layname = new GH_Structure <GH_String>();

            OSGeo.OGR.FeatureDefn def = layerset[0].GetLayerDefn();

            //Loop through input boundaries
            for (int i = 0; i < boundary.Count; i++)
            {
                if (rec.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Min) && (rec.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Max)))
                {
                    //Create bounding box for clipping geometry
                    Point3d  min   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Min);
                    Point3d  max   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Max);
                    double[] minpT = new double[3];
                    double[] maxpT = new double[3];

                    minpT[0] = min.X;
                    minpT[1] = min.Y;
                    minpT[2] = min.Z;
                    maxpT[0] = max.X;
                    maxpT[1] = max.Y;
                    maxpT[2] = max.Z;
                    revTransform.TransformPoint(minpT);
                    revTransform.TransformPoint(maxpT);

                    OSGeo.OGR.Geometry bbox  = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + min.X + " " + min.Y + ", " + min.X + " " + max.Y + ", " + max.X + " " + max.Y + ", " + max.X + " " + min.Y + ", " + min.X + " " + min.Y + "))");
                    OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                    //Clip Shapefile
                    //http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                    OSGeo.OGR.Layer clipped_layer = layerset[0];
                    clipped_layer.SetSpatialFilter(ebbox);

                    //Loop through geometry
                    OSGeo.OGR.Feature feat;
                    def = clipped_layer.GetLayerDefn();

                    int m = 0;
                    while ((feat = layerset[0].GetNextFeature()) != null)
                    {
                        if (feat.GetGeometryRef() != null)
                        {
                            //Get geometry points and field values
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            //Start get points if open polylines and points
                            for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                            { //Loop through geometry points
                                double[] pT = new double[3];
                                pT[0] = geom.GetX(gpc);
                                pT[1] = geom.GetY(gpc);
                                pT[2] = geom.GetZ(gpc);
                                if (Double.IsNaN(geom.GetZ(gpc)))
                                {
                                    pT[2] = 0;
                                }
                                coordTransform.TransformPoint(pT);

                                Point3d pt3D = new Point3d();
                                pt3D.X = pT[0];
                                pt3D.Y = pT[1];
                                pt3D.Z = pT[2];

                                gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, m));
                                //End loop through geometry points

                                // Get Feature Values
                                if (fset.PathExists(new GH_Path(i, m)))
                                {
                                    fset.get_Branch(new GH_Path(i, m)).Clear();
                                }
                                for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                {
                                    OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                    if (feat.IsFieldSet(iField))
                                    {
                                        fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, m));
                                    }
                                    else
                                    {
                                        fset.Append(new GH_String("null"), new GH_Path(i, m));
                                    }
                                }
                                //End Get Feature Values
                            }
                            //End getting points if open polylines or points

                            //Start getting points if closed polylines and multipolygons
                            for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                            {
                                sub_geom = geom.GetGeometryRef(gi);
                                List <Point3d> geom_list = new List <Point3d>();

                                for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                {
                                    //Loop through geometry points
                                    double[] pT = new double[3];
                                    pT[0] = sub_geom.GetX(ptnum);
                                    pT[1] = sub_geom.GetY(ptnum);
                                    pT[2] = sub_geom.GetZ(ptnum);
                                    coordTransform.TransformPoint(pT);

                                    Point3d pt3D = new Point3d();
                                    pt3D.X = pT[0];
                                    pt3D.Y = pT[1];
                                    pt3D.Z = pT[2];

                                    gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, m, gi));
                                    //End loop through geometry points

                                    // Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, m));
                                        }
                                    }
                                    //End Get Feature Values
                                }
                                //End getting points from closed polylines
                            }
                            m++;
                        }
                        feat.Dispose();
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the Shapefile dataset.");
                    //return;
                }
            }

            //Get the field names
            List <string> fieldnames = new List <string>();

            for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
            {
                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                fieldnames.Add(fdef.GetNameRef());
            }

            DA.SetData(0, def.GetName());
            DA.SetDataList(1, fc);
            DA.SetData(2, rec);
            DA.SetData(3, sRef);
            DA.SetDataList(4, fieldnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);
        }
Ejemplo n.º 2
0
        private static void TransformWKT(object srcProj, object dstProj, EPSGType srcType, EPSGType dstType, ref string wkt)
        {
            try
            {
                GdalConfiguration.ConfigureOgr();
                SpatialReference src = new SpatialReference("");
                switch (srcType)
                {
                case EPSGType.OGC_WKT:
                    string srcProj_str = srcProj.ToString();
                    src.ImportFromWkt(ref srcProj_str);
                    break;

                case EPSGType.PROJ4:
                    src.ImportFromProj4(srcProj.ToString());
                    break;

                case EPSGType.EPSG_NUM:
                    src.ImportFromEPSG((int)srcProj);
                    break;
                }

                SpatialReference dst = new SpatialReference("");
                switch (dstType)
                {
                case EPSGType.OGC_WKT:
                    string dstProj_str = dstProj.ToString();
                    dst.ImportFromWkt(ref dstProj_str);
                    break;

                case EPSGType.PROJ4:
                    dst.ImportFromProj4(dstProj.ToString());
                    break;

                case EPSGType.EPSG_NUM:
                    dst.ImportFromEPSG((int)dstProj);
                    break;
                }

                CoordinateTransformation coordinate = Osr.CreateCoordinateTransformation(src, dst);
                string wktType = wkt.Split('(')[0];
                wkt = wkt.Split('(')[2].Split(')')[0];
                string[] splitWKT = wkt.Split(',');
                double[] xPoints  = new double[splitWKT.Length];
                double[] yPoints  = new double[splitWKT.Length];
                for (int i = 0; i < splitWKT.Length; i++)
                {
                    double.TryParse(splitWKT[i].Split(' ')[0], out xPoints[i]);
                    double.TryParse(splitWKT[i].Split(' ')[1], out yPoints[i]);
                }
                coordinate.TransformPoints(splitWKT.Length, xPoints, yPoints, null);

                wkt = wktType + "((";
                for (int i = 0; i < xPoints.Length; i++)
                {
                    wkt += xPoints[i] + " " + yPoints[i] + ",";
                }
                wkt  = wkt.Substring(0, wkt.Length - 1);
                wkt += "))";
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
        public static FileProcessedTracker Run([QueueTrigger("downloadandunpacksnodas", Connection = "AzureWebJobsStorage")] FileReadyToDownloadQueueMessage myQueueItem,
                                               TraceWriter log)
        {
            log.Info($"C# Queue trigger function processed snodas date: {myQueueItem.FileDate}");

            string partitionName = myQueueItem.Filetype;

            var urlToDownload = myQueueItem.Url;

            log.Info($"Downloading Url {urlToDownload}");

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(urlToDownload);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("anonymous", "");
            List <string>  listOfUnpackedFiles = null;
            FtpWebResponse response            = (FtpWebResponse)request.GetResponse();

            log.Info($"File {urlToDownload} downloaded");
            Stream responseStream = response.GetResponseStream();

            listOfUnpackedFiles = SnodasUtilities.UnpackSnodasStream(responseStream);
            log.Info($"File {urlToDownload} unpacked");

            //fix the bard codes in the hdr files
            foreach (var f in listOfUnpackedFiles.Where(s => s.ToLower().Contains(".hdr")))
            {
                SnodasUtilities.RemoveBardCodesFromHdr(f);
            }

            log.Info($"Attempting to sign in to ad for datalake upload");
            var adlsAccountName = CloudConfigurationManager.GetSetting("ADLSAccountName");

            //auth secrets
            var domain           = CloudConfigurationManager.GetSetting("Domain");
            var webApp_clientId  = CloudConfigurationManager.GetSetting("WebAppClientId");
            var clientSecret     = CloudConfigurationManager.GetSetting("ClientSecret");
            var clientCredential = new ClientCredential(webApp_clientId, clientSecret);
            var creds            = ApplicationTokenProvider.LoginSilentAsync(domain, clientCredential).Result;

            // Create client objects and set the subscription ID
            var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);

            log.Info($"Attempting to upload unpacked files to adls");
#if DEBUG
//            listOfUnpackedFiles = listOfUnpackedFiles.Where(f => f.Contains(".Hdr")).Take(1).ToList();
#endif
            foreach (var file in listOfUnpackedFiles)
            {
                try
                {
                    adlsFileSystemClient.FileSystem.UploadFile(adlsAccountName, file, "/snodas-dat-us-v1/" + file.Split('\\').Last(), uploadAsBinary: true, overwrite: true);
                    log.Info($"Uploaded file: {file}");
                }
                catch (Exception e)
                {
                    log.Error($"Upload failed: {e.Message}");
                }
            }

            //1: Get values for lat/lon
            var locations = AzureUtilities.DownloadLocations(log);
#if DEBUG
            var executingAssemblyFile = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
            var executingDirectory    = Path.GetDirectoryName(executingAssemblyFile);

            if (string.IsNullOrEmpty(executingDirectory))
            {
                throw new InvalidOperationException("cannot get executing directory");
            }
            executingDirectory = Directory.GetParent(executingDirectory).FullName;

            var gdalPath = Path.Combine(executingDirectory, "gdal");
            log.Info($"Have gdal path {gdalPath}");
#endif
            log.Info($"Configuring gdal");
            GdalConfiguration.ConfigureGdal();
            var results = SnodasUtilities.GetValuesForCoordinates(locations, listOfUnpackedFiles.Where(f => f.Contains(".Hdr")).ToList());
            log.Info($"Have {results.Count} results for coordinates.");
            DateTime fileDate;
            string   fileName;
            using (MemoryStream s = new MemoryStream())
                using (StreamWriter csvWriter = new StreamWriter(s, Encoding.UTF8))
                {
                    csvWriter.WriteLine(SnodasRow.GetHeader);
                    foreach (var row in results)
                    {
                        csvWriter.WriteLine(row.ToString());
                    }
                    csvWriter.Flush();
                    s.Position = 0;

                    fileDate = results[0].Date;
                    fileName = fileDate.ToString("yyyyMMdd") + "Snodas.csv";
                    try
                    {
                        adlsFileSystemClient.FileSystem.Create(adlsAccountName, "/snodas-csv-westus-v1/" + fileName, s, overwrite: true);
                        log.Info($"Uploaded csv stream: {fileName}");
                    }
                    catch (Exception e)
                    {
                        log.Info($"Upload failed: {e.Message}");
                    }
                }

            log.Info($"Removing unpacked files");
            foreach (var f in listOfUnpackedFiles)
            {
                //delete local temp file
                File.Delete(f);
            }
            return(new FileProcessedTracker {
                ForecastDate = fileDate, PartitionKey = "snodas-westus-v1", RowKey = fileName, Url = "unknown"
            });
        }
Ejemplo n.º 4
0
 public void OneTimeSetUp()
 {
     GdalConfiguration.ConfigureGdal();
     if (!GdalConfiguration.Usable)
         Assert.Ignore($"GDAL not set up correctly, no binaries found in '{TestContext.CurrentContext.TestDirectory}\\gdal'");
 }
Ejemplo n.º 5
0
 public GdalUtilities()
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
 }
Ejemplo n.º 6
0
 public static void Configure()
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
     //does nothing but ensure that the Static initializer has been called.
 }
Ejemplo n.º 7
0
        //DotSpatial.Data.WKBReader wkbReader = null;

        #endregion

        #region constructors

        static OgrDataReader()
        {
            GdalConfiguration.ConfigureOgr();
        }
Ejemplo n.º 8
0
 public JTGdalInstaller()
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
 }
Ejemplo n.º 9
0
 private void Form1_Load(object sender, EventArgs e)
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
 }
Ejemplo n.º 10
0
 static OgrVectorProvider()
 {
     GdalConfiguration.ConfigureOgr();
 }
Ejemplo n.º 11
0
        private void Import(String filename = null)
        {
            var rasterFile = filename;

            if (rasterFile == null)
            {
                LandCoverTableViewModel.BufferDistance = BankModificationIndicator.BufferDistance;
                LandCoverTableViewModel.ImportStep     = false;
                var id = new LandCoverImportWindow {
                    Owner = Application.Current.MainWindow, DataContext = LandCoverTableViewModel
                };
                if (id.ShowDialog() != true)
                {
                    return;
                }
                BankModificationIndicator.BufferDistance = LandCoverTableViewModel.BufferDistance;
                var dialog = new OpenFileDialog
                {
                    Title           = "Import Land Cover GeoTIFF",
                    DefaultExt      = ".tif",
                    CheckFileExists = true
                };
                if (dialog.ShowDialog() != true)
                {
                    return;
                }
                rasterFile = dialog.FileName;
            }

            if (String.IsNullOrWhiteSpace(rasterFile))
            {
                return;
            }

            GdalConfiguration.ConfigureOgr();
            GdalConfiguration.ConfigureGdal();

            var ci = Model.EcosystemVitality.FetchIndicator <ConnectivityIndicator>();

            if (!(ci?.Reaches?.Count > 0))
            {
                MessageBox.Show(
                    "You must have reaches for the Connectivity Indicator imported in order to process the channel modification.");
                return;
            }

            var raster = Gdal.Open(rasterFile, Access.GA_ReadOnly);

            var progress = new ProgressDialog
            {
                Label           = $"Processing Channel Modification:\n{raster.GeoTiffDescription()}",
                Owner           = Application.Current.MainWindow,
                IsCancellable   = true,
                IsIndeterminate = false
            };

            var result = new Dictionary <byte, int>();

            progress.Execute((ct, p) =>
            {
                var ip          = new Progress <int>();
                var reachNumber = 0;
                var sr          = new SpatialReference(ArcGisUtils.WkidToWktxt(Model.Attributes.Wkid));

                foreach (var reach in ci.Reaches)
                {
                    var line = new Geometry(wkbGeometryType.wkbLineString);

                    line.AssignSpatialReference(sr);
                    foreach (var node in reach.Nodes)
                    {
                        line.AddPoint_2D(node.Location.Longitude, node.Location.Latitude);
                    }
                    // convert from the user specified buffer distance (in meters) to the projected buffer units. no idea how well this works in general.
                    var distance = sr.IsGeographic() == 1 ?  BankModificationIndicator.BufferDistance / 110000 * Math.Abs(Math.Cos(sr.GetAngularUnits() * reach.Nodes[0].Location.Latitude)) : BankModificationIndicator.BufferDistance / sr.GetLinearUnits();
                    GdalRasterUtils.ReadRasterRows(raster, line.Buffer(distance, 5), out var tally, ct, ip);

                    foreach (var key in tally.Keys)
                    {
                        if (!result.ContainsKey(key))
                        {
                            result[key] = 0;
                        }
                        result[key] += tally[key];
                    }

                    p.Report((int)(100.0 * reachNumber++ / ci.Reaches.Count));
                }
            });

            var message = new TextWindow
            {
                Owner = Application.Current.MainWindow,
                Text  = "Histogram of extracted data:\n" + GdalRasterUtils.DumpResult(result) +
                        "\n\n--- Raster File Details ---\n" + GdalRasterUtils.DumpDatasetInfo(raster)
            };

            message.ShowDialog();

            BankModificationIndicator.Notes = message.Text;
            var coverage = BankModificationIndicator.Coverage.Clone();

            foreach (var item in coverage)
            {
                item.Area = 0.0;
                if (item.Mapping == null)
                {
                    continue;
                }

                foreach (var map in item.Mapping)
                {
                    if (result.ContainsKey(map))
                    {
                        item.Area += result[map];
                    }
                }
            }
            var total = coverage.Sum(x => x.Area);

            for (var i = 0; i < coverage.Count; i++)
            {
                BankModificationIndicator.Coverage[i].Area = 100.0 * coverage[i].Area / total;
            }
        }
Ejemplo n.º 12
0
        public MainPresenter(
            IAppContext context,
            IMainView view,
            IProjectService projectService,
            IConfigService configService
            )
            : base(view)
        {
            Logger.Current.Trace("Start MainPresenter");
            if (view == null)
            {
                throw new ArgumentNullException("view");
            }
            if (projectService == null)
            {
                throw new ArgumentNullException("projectService");
            }
            if (configService == null)
            {
                throw new ArgumentNullException("configService");
            }

            // PM 2016-03-02 Added:
            //修改,依据界面类型来判断是否为一般形态还是Ribbon


            _context        = context;
            _projectService = projectService;
            _configService  = configService;
            GdalConfiguration.ConfigureOgr();
            GlobalListeners.Attach(Logger.Current);


            try
            {
                var appContext = context as AppContext;
                if (appContext == null)
                {
                    throw new InvalidCastException("Invalid type of IAppContext instance");
                }

                appContext.Init(view, projectService, configService);


                view.ViewClosing  += OnViewClosing;
                view.ViewUpdating += OnViewUpdating;
                view.BeforeShow   += OnBeforeShow;

                var container = context.Container;
                _statusBarListener  = container.GetSingleton <StatusBarListener>();
                _menuGenerator      = container.GetSingleton <MenuGenerator>();
                _menuListener       = container.GetSingleton <MenuListener>();
                _mainPluginListener = container.GetSingleton <MainPluginListener>();
                _menuUpdater        = new MenuUpdater(_context, PluginIdentity.Default);
                SplashView.Instance.ShowStatus("Loading plugins");
                appContext.InitPlugins(configService); // must be called after docking is initialized

                // this will display progress updates and debug window
                // file based-logger is already working
                Logger.Current.Init(appContext);
            }
            finally
            {
            }

            View.AsForm.Shown += ViewShown;
            Logger.Current.Trace("End MainPresenter");
        }
Ejemplo n.º 13
0
        public void init()
        {
            GdalConfiguration.ConfigureGdal();

            Gdal.AllRegister();
        }
Ejemplo n.º 14
0
 static OgrDataProvider()
 {
     GdalConfiguration.ConfigureOgr();
 }
Ejemplo n.º 15
0
        private void Import(String filename = null)
        {
            var rasterFile = filename;

            if (rasterFile == null)
            {
                LandCoverTableViewModel.ImportStep = false;
                var id = new LandCoverImportWindow {
                    Owner = Application.Current.MainWindow, DataContext = LandCoverTableViewModel
                };
                if (id.ShowDialog() != true)
                {
                    return;
                }
                var dialog = new OpenFileDialog
                {
                    Title           = "Import Land Cover GeoTIFF",
                    DefaultExt      = ".tif",
                    CheckFileExists = true
                };
                if (dialog.ShowDialog() != true)
                {
                    return;
                }
                rasterFile = dialog.FileName;
            }

            if (String.IsNullOrWhiteSpace(rasterFile))
            {
                return;
            }



            var directory = Globals.Model.Assets.PathTo("BasinShapefile");

            if (String.IsNullOrWhiteSpace(directory))
            {
                MessageBox.Show(
                    "The assessment needs to have a basin shapefile before the land cover can be computed.");
                return;
            }
            var shapeFile = Directory.EnumerateFiles(directory, "*.shp").FirstOrDefault();

            if (String.IsNullOrWhiteSpace(shapeFile))
            {
                MessageBox.Show("Basin shapefile in model seems to have an error.");
                return;
            }

            GdalConfiguration.ConfigureOgr();
            GdalConfiguration.ConfigureGdal();

            var dataSource = Ogr.Open(shapeFile, 0);
            var layer      = dataSource.GetLayerByIndex(0);
            var geometry   = layer.GetNextFeature().GetGeometryRef();
            var raster     = Gdal.Open(rasterFile, Access.GA_ReadOnly);

            var progress = new ProgressDialog
            {
                Label           = $"Processing Land Cover:\n{raster.GeoTiffDescription()}",
                Owner           = Application.Current.MainWindow,
                IsCancellable   = true,
                IsIndeterminate = false
            };

            Dictionary <byte, int> result = null;

            progress.Execute((ct, p) => GdalRasterUtils.ReadRasterRows(raster, geometry, out result, ct, p));

            var message = new TextWindow
            {
                Owner = Application.Current.MainWindow,
                Text  = "Histogram of extracted data:\n" + GdalRasterUtils.DumpResult(result) +
                        "\n\n--- Raster File Details ---\n" + GdalRasterUtils.DumpDatasetInfo(raster)
            };

            message.ShowDialog();
            LandCoverIndicator.Notes = message.Text;
            var coverage = LandCoverIndicator.Coverage.Clone();

            foreach (var item in coverage)
            {
                item.Area = 0.0;
                if (item.Mapping == null)
                {
                    continue;
                }

                foreach (var map in item.Mapping)
                {
                    if (result.ContainsKey(map))
                    {
                        item.Area += result[map];
                    }
                }
            }

            var total = coverage.Sum(x => x.Area);

            for (var i = 0; i < coverage.Count; i++)
            {
                LandCoverIndicator.Coverage[i].Area = 100.0 * coverage[i].Area / total;
            }
        }
Ejemplo n.º 16
0
 static Ogr()
 {
     GdalConfiguration.ConfigureOgr();
 }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            if (args[0] != null && args[0].StartsWith("h"))
            {
                Hydrology hydrology = new Hydrology();
                hydrology.init();
                hydrology.run();
                return;
            }



            KoppenGeiger koppenGeiger = new KoppenGeiger();

            // CHELSA - now
            String tmeansFileNames = @"data\CHELSA\CHELSA_temp10_";
            String precsFileNames  = @"data\CHELSA\CHELSA_prec_";
            String outFileName     = "tmp_CHELSA.tif";

            if (koppenGeiger.PMIP3_CNRM_CM5)
            {
                tmeansFileNames = @"data\PMIP3\PMIP3_CNRM_CM5\CHELSA_PMIP_CNRM-CM5_tmean_";
                precsFileNames  = @"data\PMIP3\PMIP3_CNRM_CM5\CHELSA_PMIP_CNRM-CM5_prec_";
                outFileName     = "tmp_PMIP3.tif";
            }
            else if (koppenGeiger.PMIP3_MPI_ESM_P)
            {
                tmeansFileNames = @"data\PMIP3\PMIP3_MPI_ESM_P\CHELSA_PMIP_MPI-ESM-P_tmean_";
                precsFileNames  = @"data\PMIP3\PMIP3_MPI_ESM_P\CHELSA_PMIP_MPI-ESM-P_prec_";
                outFileName     = "tmp_PMIP3_MPI_ESM_P.tif";
            }

            GdalConfiguration.ConfigureGdal();

            Gdal.AllRegister();

            int width;
            int height;

            Band[] precsBands  = new Band[NUM_MONTH];
            Band[] tmeansBands = new Band[NUM_MONTH];

            // for all files
            for (int month = 1; month <= 12; month++)
            {
                String fileName = koppenGeiger.getFileNameTemp(tmeansFileNames, month);
                tmeansBands[month - 1] = koppenGeiger.getBand(fileName);

                Console.WriteLine("Tmean File: " + fileName);

                fileName = koppenGeiger.getFileNamePrec(precsFileNames, month);
                precsBands[month - 1] = koppenGeiger.getBand(fileName);

                Console.WriteLine("Prec File: " + fileName);
            }

            // Get the width and height of the Dataset - assuming all sizes the same
            width  = tmeansBands[0].XSize;
            height = tmeansBands[0].YSize;

            koppenGeiger.init(width);

            String  refFile = koppenGeiger.getFileNamePrec(precsFileNames, 1);
            Dataset ds      = koppenGeiger.getDataset(outFileName, refFile);
            Band    ba      = ds.GetRasterBand(1);

            short[] koppen = new short[width];

            short[] precs   = new short[NUM_MONTH * width];
            short[] tmeans  = new short[NUM_MONTH * width];
            short[] _precs  = new short[width];
            short[] _tmeans = new short[width];

            int i;

            for (i = 0; i < height; i++)
            {
                for (int month = 0; month < NUM_MONTH; month++)
                {
                    tmeansBands[month].ReadRaster(0, i, width, 1, _tmeans, width, 1, 0, 0);
                    precsBands[month].ReadRaster(0, i, width, 1, _precs, width, 1, 0, 0);
                    Array.Copy(_tmeans, 0, tmeans, month * width, width);
                    Array.Copy(_precs, 0, precs, month * width, width);
                }

                // Console.WriteLine("X:Y " + i + " " + i * W);

                koppenGeiger.clear(width);
                koppenGeiger.calculateMaps(precs, tmeans, NUM_MONTH, width, i <= (height / 2));
                koppenGeiger.calculateKoppen(koppen, 0, width);

                ba.WriteRaster(0, i, width, 1, koppen, width, 1, 0, 0);
            }

            ba.FlushCache();
            ds.FlushCache();

            /*
             * // Create a Bitmap to store the GDAL image in
             * Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
             * int j;
             * for (i = 0; i < height; i++)
             * {
             *  for (j = 0; j < width; j++)
             *  {
             *      bitmap.SetPixel(j, i, Color.FromArgb(koppen[i*j + j]));
             *  }
             * }
             *
             * bitmap.Save(outFileName);
             */

            Console.WriteLine("Done");
        }