Example #1
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;
            }
        }
 static OgrDataProvider()
 {
     GdalConfiguration.ConfigureOgr();
 }
Example #3
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

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

            string shpfilePath = string.Empty;

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

            ////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(shpfilePath, 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.WGSToXYZ(extPTmin), Heron.Convert.WGSToXYZ(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.XYZToWGS(boundary[i].GetBoundingBox(true).Min);
                    Point3d  max   = Heron.Convert.XYZToWGS(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.WGSToXYZ(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.WGSToXYZ(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);
        }
Example #4
0
 static Ogr()
 {
     GdalConfiguration.ConfigureOgr();
 }
Example #5
0
 public static void Configure()
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
     //does nothing but ensure that the Static initializer has been called.
 }
Example #6
0
        //DotSpatial.Data.WKBReader wkbReader = null;

        #endregion

        #region constructors

        static OgrDataReader()
        {
            GdalConfiguration.ConfigureOgr();
        }
 static OgrVectorProvider()
 {
     GdalConfiguration.ConfigureOgr();
 }
Example #8
0
 private void Form1_Load(object sender, EventArgs e)
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
 }
Example #9
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;
            }
        }
Example #10
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");
        }
Example #11
0
 public JTGdalInstaller()
 {
     GdalConfiguration.ConfigureGdal();
     GdalConfiguration.ConfigureOgr();
 }