Esempio n. 1
0
        public Dictionary<string,object> FindValue(IFeatureClass pFeatureClass, string keyName, string targetName)
        {
            //int keyFieldIndex = pFeatureClass.Fields.FindField(keyField);
            //int targetFieldIndex = pFeatureClass.Fields.FindField(targetField);
            //IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false);
            //IFeature pFeature;
            //while ((pFeature = pFeatureCursor.NextFeature()) != null)
            //{
            //    if (pFeature.Value[keyFieldIndex].ToString() == keyValue) break;

            //}
            //Marshal.ReleaseComObject(pFeatureCursor);
            //return pFeature == null ? null : pFeature.Value[targetFieldIndex];
            int keyFieldIndex = pFeatureClass.Fields.FindField(keyName);
            int targetFieldIndex = pFeatureClass.Fields.FindField(targetName);
            Dictionary<string,object> dic=new Dictionary<string, object>(pFeatureClass.FeatureCount(null));
            IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false);
            IFeature pFeature;
            while ((pFeature = pFeatureCursor.NextFeature()) != null)
            {
                if (!dic.ContainsKey(pFeature.Value[keyFieldIndex].ToString()))
                {
                    dic.Add(pFeature.Value[keyFieldIndex].ToString(), pFeature.Value[targetFieldIndex]);
                    
                }
            }
            Marshal.ReleaseComObject(pFeatureCursor);
            return dic;
        }
Esempio n. 2
0
        private List<double> overlapStandard(IFeatureClass featureClass, string targetLayerName)
        {
            List<double> overlapList = new List<double>();
            IFeatureClass targetFeatureClass = GisUtil.getFeatureClass(mapFolder, targetLayerName);
            for (int i = 0; i < featureClass.FeatureCount(null); i++)
            {
                IFeature feature = featureClass.GetFeature(i);
                IGeometry geometry = feature.ShapeCopy;
                geometry.SpatialReference = mapControl.SpatialReference;
                ITopologicalOperator tpOp = geometry as ITopologicalOperator;
                IArea area = geometry as IArea;
                ISpatialFilter cityFilter = new SpatialFilterClass();
                cityFilter.Geometry = geometry;
                cityFilter.GeometryField = "SHAPE";
                cityFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                IFeatureCursor feaCursor = targetFeatureClass.Search(cityFilter, false);

                //获取所有与该块相交的要素, 然后检测其相交的面积, 依照比例计算最终的值.
                IFeature cityFea = feaCursor.NextFeature();
                double overlap = 0;
                while (cityFea != null)
                {
                    if (cityFea != null)
                    {
                        IGeometry intersectedGeom = tpOp.Intersect(cityFea.ShapeCopy, esriGeometryDimension.esriGeometry2Dimension);
                        IArea intersectedGeomArea = intersectedGeom as IArea;
                        //获取gridcode.
                        ITable table = cityFea.Table;
                        IRow row = table.GetRow(0);
                        int fieldNum = table.FindField("GRIDCODE");
                        double value = (double)cityFea.get_Value(fieldNum);
                        overlap = overlap + value * (intersectedGeomArea.Area / area.Area);
                    }
                    cityFea = feaCursor.NextFeature();
                }
                overlapList.Add(overlap);
            }
            return overlapList;
        }
Esempio n. 3
0
        private List<double> distanceStandard(IFeatureClass featureClass, string targetLayerName)
        {
            List<double> distanceList = new List<double>();
            IFeatureClass targetFeatureClass = GisUtil.getFeatureClass(mapFolder, targetLayerName);
            //将所有的geometry放入一个arraylist.
            List<IGeometry> geometryList = new List<IGeometry>();
            for (int i = 0; i < targetFeatureClass.FeatureCount(null); i++)
            {
                geometryList.Add(targetFeatureClass.GetFeature(i).ShapeCopy);
            }
            IGeometry geometry = GisUtil.unionAllFeature(geometryList);
            IProximityOperator proOp = geometry as IProximityOperator;

            //求到路的距离.
            for (int i = 0; i < featureClass.FeatureCount(null); i++)
            {
                IFeature fea = featureClass.GetFeature(i);
                IGeometry geom = fea.ShapeCopy;
                geom.SpatialReference = mapControl.SpatialReference;
                double distance = proOp.ReturnDistance(geom);
                distanceList.Add(distance);
            }
            return distanceList;
        }
Esempio n. 4
0
        private List<double> IntersectRestraint(IFeatureClass featureClass, string targetLayerName)
        {
            List<double> ratioList = new List<double>();
            IFeatureClass targetFeatureClass = GisUtil.getFeatureClass(mapFolder, targetLayerName);
            List<IGeometry> geometryList = new List<IGeometry>();
            for (int i = 0; i < targetFeatureClass.FeatureCount(null); i++)
            {
                geometryList.Add(targetFeatureClass.GetFeature(i).Shape);
            }
            IGeometry geometry = GisUtil.unionAllFeature(geometryList); //e0图层所有的几何图形.
            ITopologicalOperator toOp = geometry as ITopologicalOperator;

            for (int i = 0; i < featureClass.FeatureCount(null); i++)
            {
                IFeature feature = featureClass.GetFeature(i);
                IGeometry srcGeom = feature.ShapeCopy;
                srcGeom.SpatialReference = mapControl.SpatialReference;
                IGeometry intersectedGeom = toOp.Intersect(srcGeom, esriGeometryDimension.esriGeometry2Dimension);
                //测量相交图形的面积, 超过原图形的一半, 有效.
                IArea area = intersectedGeom as IArea;
                IArea srcArea = srcGeom as IArea;
                double ratio = (area.Area / srcArea.Area) * 100;
                ratioList.Add(ratio);
            }
            return ratioList;
        }
Esempio n. 5
0
        /// <summary>
        /// count the number of features in a feature class
        /// </summary>
        public static int FeatureCount(IFeatureClass ThisFC, string WhereClause)
        {
            IQueryFilter ThisQF;

            ThisQF = new QueryFilterClass();
            ThisQF.WhereClause = WhereClause;

            try
            {
                return ThisFC.FeatureCount(ThisQF);
            }
            catch
            {
            }

            return -1;
        }
Esempio n. 6
0
        /// <summary>
        /// used by the GenerateFlatAreas and GenerateExcludedAreas logic to add in at least one polygon if their
        /// processes result in zero polygons being generated
        /// </summary>
        public static void CreateFillerPolygon(IFeatureClass ThisFeatureClass, int SurveyID, ref string ErrorMessage)
        {
            IFeatureCursor ThisFCursor;
            IFeatureBuffer ThisFBuffer;
            IQueryFilter ThisQueryFilter;
            IPolygon BoundarPoly;
            int SurveyIDIndex;

            ThisQueryFilter = new QueryFilterClass();
            ThisQueryFilter.WhereClause = "SurveyID=" + SurveyID;

            SurveyIDIndex = ThisFeatureClass.FindField("SurveyID");
            if (SurveyIDIndex == -1)
            {
                ErrorMessage = "Could not find SurveyID field in " + ((IDataset)ThisFeatureClass).Name + " FeatureClass.";
                return;
            }

            if (ThisFeatureClass.FeatureCount(ThisQueryFilter) > 0) return;

            BoundarPoly = Util.GetSurveyBoundary(Convert.ToString(SurveyID), ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            try
            {
                BoundarPoly = Util.EnvelopeToPolygon(BoundarPoly.Envelope.UpperLeft.Envelope);

                ThisFCursor = ThisFeatureClass.Insert(true);
                ThisFBuffer = ThisFeatureClass.CreateFeatureBuffer();

                ThisFBuffer.Shape = BoundarPoly;
                ThisFBuffer.set_Value(SurveyIDIndex, SurveyID);

                ThisFCursor.InsertFeature(ThisFBuffer);
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error occured while inserting filler shape for "
                    + ((IDataset)ThisFeatureClass).Name + " FeatureClass. " + ex.Message;
            }

            ThisFCursor = null;
        }
Esempio n. 7
0
        public static void updateAcetate(SEE see, IFeatureClass featureClass, ISDUTExtension ext)
        {
            if(see == null)
            {
                return;
            }

            Logger.Write("Update acetate");
            IFeature feat = null;
            if(featureClass.FeatureCount(null) < 1)
            {
                feat = featureClass.CreateFeature();
                feat.Shape = see.Shape;
                feat.Store();
            }
            else
            {
                feat = featureClass.Update(null,false).NextFeature();
                feat.Shape = see.Shape;
                feat.Store();
            }
            Logger.Write("Update acetate -- Refresh");

            ((IActiveView)ext.FocusMap).Refresh();
        }
        public static int GetFeaturesForInput(IGPValue inputValue, out IFeatureClass inputFClass, out IFeatureCursor inputFeatures)
        {
            //
            // GET FEATURECURSOR RESPECTING SELECTION
            IGPUtilities gpUtils = new GPUtilitiesClass();
            int numFeatures = 0;
            IGeoFeatureLayer inputFLayer = null;

            if (inputValue is IDEFeatureClass)
            {
                // IF THE INPUT IS A FEATURECLASS THEN JUST OPEN THE DATASET AND
                // CREATE A FEATURE CURSOR OF ALL THE FEATURES AND RETURN THE TOTAL
                // NUMBER OF FEATURES IN THE FEATURECLASS
                inputFClass = (IFeatureClass)gpUtils.OpenDataset(inputValue);
                inputFeatures = inputFClass.Search(null, false);
                numFeatures = inputFClass.FeatureCount(null);
            }
            else
            {
                // IF THE INPUT IS A FEATURELAYER THEN OPEN THE FEATURELAYER
                // AND USE THE DISPLAYFEATURECLASS THAT RESPECTS JOINED FIELDS.
                inputFLayer = (IGeoFeatureLayer)gpUtils.OpenDataset(inputValue);
                inputFClass = inputFLayer.DisplayFeatureClass;
                IFeatureSelection inputSelection = (IFeatureSelection)inputFLayer;
                if (inputSelection.SelectionSet.Count > 0)
                {
                    // IF THE FEATURELAYER HAS A SELECTION THEN CREATE A FEATURECURSOR
                    // OF ALL THE SELECTED FEATURES AND RETURN THE NUMBER OF FEATURES
                    // IN THE SELECTION
                    ICursor selectionCursor = null;
                    inputSelection.SelectionSet.Search(null, false, out selectionCursor);
                    inputFeatures = (IFeatureCursor)selectionCursor;
                    numFeatures = inputSelection.SelectionSet.Count;
                }
                else
                {
                    // IF THE FEATURELAYER HAS NO SELECTION THEN CREATE A FEATURECURSOR
                    // USING THE DEFINITIONEXPRESSION OF THE LAYER AND RETURN THE NUMBER
                    // OF FEATURES BASED ON THE DEFINITIONEXPRESSION.
                    IFeatureLayerDefinition layerDef = (IFeatureLayerDefinition)inputFLayer;
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = layerDef.DefinitionExpression;
                    inputFeatures = inputFLayer.SearchDisplayFeatures(queryFilter, false);
                    numFeatures = inputFLayer.FeatureClass.FeatureCount(queryFilter);
                }
            }

            return numFeatures;
        }
Esempio n. 9
0
        /// <summary>
        /// 创建实体表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateEntiTable_Click(object sender, EventArgs e)
        {
            //显示进度条
            this.labelX1.Visible            = true;
            this.progressBarXEntiDB.Visible = true;

            IWorkspaceFactory2 pWorkspaceFactory = new FileGDBWorkspaceFactoryClass() as IWorkspaceFactory2;
            //20180131
            string path = System.IO.Path.GetDirectoryName(this.txbGdbPath.Text);
            //string entitableName = this.txbEntiName.Text.ToString();
            string entitableName = System.IO.Path.GetFileName(this.txbGdbPath.Text);

            IWorkspace2       pWorkspace       = pWorkspaceFactory.OpenFromFile(path, 0) as IWorkspace2;
            IFeatureWorkspace featureWorkspace = pWorkspace as IFeatureWorkspace;


            IMapControl4         pMainMapControl = ClsControl.MapControlMain;
            IMap                 pMap            = pMainMapControl.Map;
            List <IFeatureLayer> pFeatlayerList  = new List <IFeatureLayer>();

            //把dbf表转换成为ITable
            string dbfPath      = System.IO.Path.GetDirectoryName(this.txbVersionPath.Text);
            string dbfName      = System.IO.Path.GetFileName(this.txbVersionPath.Text);
            ITable versionTable = OpenDBFTable(dbfPath, dbfName);

            int pBarNumberTotal = 0;

            if (pMap != null)
            {
                ClsCommon pClsCommon = new ClsCommon();
                pFeatlayerList = pClsCommon.GetFeatureLayers(pMap);

                ITable entitable = null;

                //如果表存在,就删除数据
                if (pWorkspace.get_NameExists(esriDatasetType.esriDTTable, entitableName))
                {
                    entitable = featureWorkspace.OpenTable(entitableName);
                    //IWorkspaceEdit workspaceEdit = pWorkspace as IWorkspaceEdit;
                    //workspaceEdit.StartEditing(true);
                    //workspaceEdit.StartEditOperation();

                    //ICursor cursor = entitable.Search(null, false);
                    //IRow r = cursor.NextRow();
                    //while (r != null)
                    //{
                    //    r.Delete();
                    //    r = cursor.NextRow();
                    //}
                    //workspaceEdit.StopEditOperation();
                    //workspaceEdit.StopEditing(true);
                }
                //如果表不存在,就创建字段创建表
                else
                {
                    IFields fileds = null;
                    fileds    = CreateEntiTableFields(pWorkspace);
                    entitable = CreateTable(pWorkspace, entitableName, fileds);
                }

                //进度条
                ClsBarSync pBarEntiDB = new ClsBarSync(progressBarXEntiDB);
                pBarEntiDB.SetStep(1);

                foreach (IFeatureLayer pFeatureLay in pFeatlayerList)
                {
                    IFeatureClass pFeatureCls = pFeatureLay.FeatureClass;
                    int           pCount      = pFeatureCls.FeatureCount(null);
                    pBarNumberTotal += pCount;
                    //pBarEntiDB.PerformOneStep();
                }
                pBarEntiDB.SetMax(pBarNumberTotal);
                foreach (IFeatureLayer pFeatureLay in pFeatlayerList)
                {
                    IFeatureClass pFeatureCls     = pFeatureLay.FeatureClass;
                    string        pFeatureLayname = pFeatureLay.Name;
                    FillEntiTable(pFeatureCls, entitable, versionTable, pFeatureLayname, pBarEntiDB);
                    //pBarEntiDB.PerformOneStep();
                }
            }

            //DialogResult dr = MessageBox.Show("内容?", "对话框标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            DialogResult dr = MessageBox.Show("实体表创建成功!", "实体表提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (dr == DialogResult.OK)
            {
                //点确定的代码
                this.Close();
            }
            else
            {
                //点取消的代码
            }
            //MessageBox.Show("实体表创建成功!");
        }
Esempio n. 10
0
        private void btnup_Click(object sender, EventArgs e)
        {
            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;

            //设置步长,即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            progressBarControl1.Position = 0;

            //设置一个最小值
            progressBarControl2.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl2.Properties.Maximum = listView1.CheckedItems.Count * 2;
            //设置步长,即每次增加的数
            progressBarControl2.Properties.Step = 1;
            //设置进度条的样式
            progressBarControl2.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            progressBarControl2.Position = 0;

            ////设置一个最小值
            //progressBar2.Minimum = 0;
            ////设置一个最大值
            //progressBar2.Maximum = listView1.CheckedItems.Count * 2;
            ////设置步长,即每次增加的数
            //progressBar2.Step = 1;
            //progressBar2.Value = 0;


            IFeatureClass tFeatureClass = pFeatureLayer_QYYJY.FeatureClass;

            DataEditCommon.DeleteFeatureByWhereClause(tFeatureClass, "");
            IGeometryArray pgeoArrayHong = new GeometryArrayClass();
            IGeometryArray pgeoArrayHang = new GeometryArrayClass();

            for (int i = 0; i < listView1.CheckedItems.Count; i++)
            {
                string        layer         = listView1.CheckedItems[i].SubItems[1].Text.ToString();
                ILayer        pLayer        = DataEditCommon.GetLayerByName(DataEditCommon.g_pMap, layer);
                IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                if (pFeatureLayer == null)
                {
                    continue;
                }
                IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                //设置一个最大值
                progressBarControl1.Properties.Maximum = pFeatureClass.FeatureCount(null);
                IFeatureCursor pCursor  = pFeatureClass.Search(null, false);
                IFeature       pFeature = pCursor.NextFeature();

                while (pFeature != null)
                {
                    ITopologicalOperator pTopo = (ITopologicalOperator)pFeature.Shape;
                    IGeometry            pGeo  = pTopo.Buffer(hongse);
                    pgeoArrayHong.Add(pGeo);
                    IGeometry pGeoH = pTopo.Buffer(huangse);
                    if (pFeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        pTopo = (ITopologicalOperator)pGeoH;
                        pGeoH = pTopo.Difference(pGeo);
                    }
                    pgeoArrayHang.Add(pGeoH);
                    pFeature = pCursor.NextFeature();
                    this.progressBarControl1.PerformStep();
                    Application.DoEvents();
                }
                List <ziduan> list = new List <ziduan>();
                list.Add(new ziduan("dengji", "1"));
                list.Add(new ziduan("layername", layer));
                list.Add(new ziduan("BID", "0"));
                DataEditCommon.CreateFeature(tFeatureClass, pgeoArrayHong, list);
                this.progressBarControl2.PerformStep();
                //progressBar2.Value += 1;
                Application.DoEvents();
                List <ziduan> listH = new List <ziduan>();
                listH.Add(new ziduan("dengji", "2"));
                listH.Add(new ziduan("layername", layer));
                listH.Add(new ziduan("BID", "0"));
                DataEditCommon.CreateFeature(tFeatureClass, pgeoArrayHang, listH);
                this.progressBarControl2.PerformStep();
                //progressBar2.Value += 1;
                Application.DoEvents();
            }
            if (pFeatureLayer_QYYJY.Visible == false)
            {
                pFeatureLayer_QYYJY.Visible = true;
            }
            DataEditCommon.g_pMyMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            MessageBox.Show("完成!");
        }
Esempio n. 11
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add ShortPathSolveCommand.OnClick implementation
            //string name = NetWorkAnalysClass.getPath(path) + "\\data\\HuanbaoGeodatabase.gdb";
            string            name        = NetWorkAnalysClass.getPath(path) + "\\Data\\TestNet.gdb";
            IFeatureWorkspace pFWorkspace = NetWorkAnalysClass.OpenWorkspace(name) as IFeatureWorkspace;

            //"RouteNetwork", "BaseData"参数不可更改
            networkDataset = NetWorkAnalysClass.OpenPathNetworkDataset(pFWorkspace as IWorkspace, "NetWork_wy_ND", "NetWork_wy");
            m_NAContext    = NetWorkAnalysClass.CreatePathSolverContext(networkDataset);
            //通过网络数据集创建网络分析上下文
            //打开要素数据集
            inputFClass   = pFWorkspace.OpenFeatureClass("Stops");
            barriesFClass = pFWorkspace.OpenFeatureClass("Barries");
            if (IfLayerExist("NetworkDataset") == false)
            {
                ILayer        layer;
                INetworkLayer networkLayer;
                networkLayer = new NetworkLayerClass();
                networkLayer.NetworkDataset = networkDataset;
                layer      = networkLayer as ILayer;
                layer.Name = "NetworkDataset";
                m_hookHelper.ActiveView.FocusMap.AddLayer(layer);
                layer.Visible = false;
            }
            if (IfLayerExist(m_NAContext.Solver.DisplayName) == true)
            {
                for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
                {
                    if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                    {
                        m_hookHelper.FocusMap.DeleteLayer(m_hookHelper.FocusMap.get_Layer(i));
                    }
                }
            }
            INALayer naLayer = m_NAContext.Solver.CreateLayer(m_NAContext);
            ILayer   pLayer  = naLayer as ILayer;

            pLayer.Name = m_NAContext.Solver.DisplayName;
            m_hookHelper.ActiveView.FocusMap.AddLayer(pLayer);
            if (inputFClass.FeatureCount(null) < 2)
            {
                MessageBox.Show("只有一个站点,不能进行路径分析!");
                return;
            }
            IGPMessages gpMessages = new GPMessagesClass();

            //加载站点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Stops", inputFClass, m_NAContext, 50);
            //加载障碍点要素,并设置容差
            NetWorkAnalysClass.LoadNANetworkLocations("Barriers", barriesFClass, m_NAContext, 5);
            INASolver naSolver = m_NAContext.Solver;//创建网络分析对象

            try
            {
                naSolver.Solve(m_NAContext, gpMessages, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("未能找到有效路径" + ex.Message, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            for (int i = 0; i < m_hookHelper.FocusMap.LayerCount; i++)
            {
                if (m_hookHelper.FocusMap.get_Layer(i).Name == m_NAContext.Solver.DisplayName)
                {
                    ICompositeLayer pCompositeLayer = m_hookHelper.FocusMap.get_Layer(i) as ICompositeLayer;
                    {
                        for (int t = 0; t < pCompositeLayer.Count; t++)
                        {
                            ILayer pResultLayer = pCompositeLayer.get_Layer(t);
                            if (pResultLayer.Name == "Stops" || pResultLayer.Name == "Barriers")
                            {
                                pResultLayer.Visible = false;
                                continue;
                            }
                        }
                    }
                }
            }
            IGeoDataset geoDataset;
            IEnvelope   envelope;

            geoDataset = m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;
            envelope   = geoDataset.Extent;
            if (!envelope.IsEmpty)
            {
                envelope.Expand(1.1, 1.1, true);
            }
            m_hookHelper.ActiveView.Extent = envelope;
            m_hookHelper.ActiveView.Refresh();
        }
Esempio n. 12
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            int intDeciPlaces = 5;

            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

            pfrmProgress.lblStatus.Text    = "Processing:";
            pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
            pfrmProgress.Show();

            REngine pEngine = m_pForm.pEngine;
            // Creates the input and output matrices from the shapefile//
            string strLayerName = cboTargetLayer.Text;

            int    intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName);
            ILayer pLayer    = m_pForm.axMapControl1.get_Layer(intLIndex);

            IFeatureLayer pFLayer  = pLayer as IFeatureLayer;
            IFeatureClass pFClass  = pFLayer.FeatureClass;
            int           nFeature = pFClass.FeatureCount(null);

            IFeatureCursor pFCursor = pFLayer.Search(null, true);
            IFeature       pFeature = pFCursor.NextFeature();

            //Get index for independent and dependent variables
            //Get variable index
            string strVarNM1  = (string)cboFldnm1.SelectedItem;
            string strVarNM2  = (string)cboFldnm2.SelectedItem;
            int    intVarIdx1 = pFClass.FindField(strVarNM1);
            int    intVarIdx2 = pFClass.FindField(strVarNM2);

            //Store Variable at Array
            double[] arrVar1 = new double[nFeature];
            double[] arrVar2 = new double[nFeature];

            int i = 0;

            while (pFeature != null)
            {
                arrVar1[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx1));
                arrVar2[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx2));
                i++;
                pFeature = pFCursor.NextFeature();
            }

            //Plot command for R
            StringBuilder plotCommmand = new StringBuilder();

            string strStartPath = m_pForm.strPath;
            string pathr        = strStartPath.Replace(@"\", @"/");

            pEngine.Evaluate("source('" + pathr + "/AllFunctions_LeeL.R')");

            //Get the file path and name to create spatial weight matrix
            string strNameR = m_pSnippet.FilePathinRfromLayer(pFLayer);

            if (strNameR == null)
            {
                return;
            }

            //Create spatial weight matrix in R
            pEngine.Evaluate("library(spdep); library(maptools)");
            pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
            pEngine.Evaluate("sample.nb <- poly2nb(sample.shp)");

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

            pEngine.SetSymbol("sample.v1", vecVar1);
            NumericVector vecVar2 = pEngine.CreateNumericVector(arrVar2);

            pEngine.SetSymbol("sample.v2", vecVar2);

            string strNonZeroDiag = null;

            if (chkNonZeroDiag.Checked)
            {
                strNonZeroDiag = "FALSE";
            }
            else
            {
                strNonZeroDiag = "TRUE";
            }

            if (cboSAM.Text == "Lee's L")
            {
                pEngine.Evaluate("sample.g <- L.global.test(sample.v1, sample.v2, sample.nb, style='W', alternative='two.sided', diag.zero=" + strNonZeroDiag + ")");


                //Print Output
                string   strDecimalPlaces = "N" + intDeciPlaces.ToString();
                string[] strResults       = new string[7];
                if (chkNonZeroDiag.Checked)
                {
                    strResults[0] = cboSAM.Text + "* under " + cboAssumption.Text;
                }
                else
                {
                    strResults[0] = cboSAM.Text + "0 under " + cboAssumption.Text;
                }

                strResults[1] = "";
                NumericVector vecResults = pEngine.Evaluate("sample.g$estimate").AsNumeric();
                strResults[2] = "Statistic: " + vecResults[0].ToString(strDecimalPlaces);
                strResults[3] = "Expectation: " + vecResults[1].ToString(strDecimalPlaces);
                strResults[4] = "Variance: " + vecResults[2].ToString(strDecimalPlaces);
                double dblStd  = pEngine.Evaluate("sample.g$statistic").AsNumeric().First();
                double dblPval = pEngine.Evaluate("sample.g$p.value").AsNumeric().First();
                strResults[5] = "Standard deviate: " + dblStd.ToString(strDecimalPlaces);
                strResults[6] = "p-value: " + dblPval.ToString(strDecimalPlaces);

                frmGenResult pfrmResult = new frmGenResult();
                pfrmResult.Text                = "Summary";
                pfrmResult.txtField.Text       = strVarNM1 + " & " + strVarNM2;
                pfrmResult.txtStatistics.Lines = strResults;

                pfrmResult.Show();
            }
            pfrmProgress.Close();
        }
Esempio n. 13
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            frmProgress pfrmProgress = new frmProgress();
            pfrmProgress.lblStatus.Text = "Collecting Data:";
            pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
            pfrmProgress.Show();

            //Get number of variables            
            int intnVar = dgvVariables.Rows.Count - 1;

            for(int j =0; j< intnVar; j++)
            {
                if(dgvVariables.Rows[j].Cells[0].Value.ToString()==""|| dgvVariables.Rows[j].Cells[1].Value.ToString() == "")
                {
                    MessageBox.Show("Please select both variable and standard errors.", "Errors");
                    return;
                }
            }


            clsSnippet pSnippet = new clsSnippet();

            
            // Gets the variable names and indices
            BhattaVariables[] pBVariable = new BhattaVariables[intnVar];
            int nFeature = m_pFClass.FeatureCount(null);

            for (int j = 0; j < intnVar; j++)
            {
                pBVariable[j].variableNames = (string)dgvVariables.Rows[j].Cells[0].Value;
                pBVariable[j].errorNames = (string)dgvVariables.Rows[j].Cells[1].Value;

                pBVariable[j].idVar = m_pFClass.Fields.FindField(pBVariable[j].variableNames);
                pBVariable[j].idError = m_pFClass.Fields.FindField(pBVariable[j].errorNames);

                pBVariable[j].arrVar = new double[nFeature];
                pBVariable[j].arrError = new double[nFeature];
            }

            //Get values of var and error from shp file
            IFeatureCursor pFCursor = m_pFClass.Search(null, true);
            IFeature pFeature = pFCursor.NextFeature();
            
            //Store independent values at Array
            
            int i = 0;
            while (pFeature != null)
            {
                for (int j = 0; j < intnVar; j++)
                {
                    //arrInDepen[j] = new double[nFeature];
                    pBVariable[j].arrVar[i] = Convert.ToDouble(pFeature.get_Value(pBVariable[j].idVar));
                    pBVariable[j].arrError[i] = Convert.ToDouble(pFeature.get_Value(pBVariable[j].idError));
                }

                i++;
                pFeature = pFCursor.NextFeature();
            }

            pfrmProgress.lblStatus.Text = "Creating Distance Matrix";

            //Create Matrix for Distance calculation
            m_pEngine.Evaluate("Bhatta.diss < -matrix(0, " + nFeature.ToString() + ", " + nFeature.ToString()+")");
            StringBuilder[] plotCommmand = new StringBuilder[4];

            //Need to optimize 12132017 HK
            for(int k = 0; k < nFeature; k++)
            {
                for (int l = 0; l < nFeature; l++)
                {
                    plotCommmand[0].Append("x1 < -cbind(");
                    plotCommmand[1].Append("x2 < -cbind(");
                    plotCommmand[2].Append("v1 < -cbind(");
                    plotCommmand[3].Append("v2 < -cbind(");

                    for (int j = 0; j < intnVar; j++)
                    {
                        plotCommmand[0].Append(pBVariable[j].arrVar[k].ToString()+", ");
                        plotCommmand[1].Append(pBVariable[j].arrVar[l].ToString() + ", ");
                        plotCommmand[2].Append(pBVariable[j].arrError[k].ToString() + ", ");
                        plotCommmand[3].Append(pBVariable[j].arrError[k].ToString() + ", ");
                    }

                    for (int j=0; j < 4; j++)
                    {
                        plotCommmand[j].Remove(plotCommmand[j].Length - 2, 2);
                        plotCommmand[j].Append(")");
                        m_pEngine.Evaluate(plotCommmand[j].ToString());
                    }

                    m_pEngine.Evaluate("Bhatta.diss[" + k.ToString() + ", " + l.ToString() + "] < -Bhatta.mdist(x1, x2, v1, v2)");
                }
            }

            pfrmProgress.lblStatus.Text = "Finding Clusters";

            m_pEngine.Evaluate("sample.hclu < -hclust(as.dist(Bhatta.diss))");

            string strTitle = "Dendrogram";
            string strCommand = "plot(plot(sample.hclu));";
            pSnippet.drawPlottoForm(strTitle, strCommand);

            int intNClasses = Convert.ToInt32(nudNClasses.Value);
            m_pEngine.Evaluate("sample.cut <- cutree(sample.hclu, "+intNClasses.ToString()+")");

            //Save Outputs in SHP

                //The field names are related with string[] DeterminedName in clsSnippet 
                string strOutputFldName = lstSave.Items[0].SubItems[1].Text;

                //Get EVs and residuals
                NumericVector nvResiduals = m_pEngine.Evaluate("as.numeric(sum.lm$residuals)").AsNumeric();

                // Create field, if there isn't
                if (m_pFClass.FindField(strOutputFldName) == -1)
                {
                    //Add fields
                    IField newField = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)newField;
                    fieldEdit.Name_2 = strOutputFldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                    m_pFClass.AddField(newField);
                }
                else
                {
                    DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strOutputFldName + " field?", "Overwrite", MessageBoxButtons.YesNo);

                    if (dialogResult == DialogResult.No)
                    {
                        return;
                    }
                }


                //Update Field
                pFCursor.Flush();
                pFCursor = m_pFClass.Update(null, false);
                pFeature = pFCursor.NextFeature();

                int featureIdx = 0;
                int intResiFldIdx = m_pFClass.FindField(strOutputFldName);

                while (pFeature != null)
                {
                    //Update Residuals
                    pFeature.set_Value(intResiFldIdx, (object)nvResiduals[featureIdx]);

                    pFCursor.UpdateFeature(pFeature);

                    pFeature = pFCursor.NextFeature();
                    featureIdx++;
                }

                MessageBox.Show("Residuals are stored in the shape file");
            }