private byte[] editFeatureOperHandler(NameValueCollection boundVariables,
                                              JsonObject operationInput,
                                              string outputFormat,
                                              string requestProperties,
                                              out string responseProperties)
        {
            responseProperties = null;

            // get the id of the feature to be edited
            object featureIdObj;

            operationInput.TryGetObject("featureId", out featureIdObj);
            int updateFeatureId = Convert.ToInt32(featureIdObj.ToString());

            object featureJSONObj;

            operationInput.TryGetObject("featureJSON", out featureJSONObj);
            JsonObject updateFeatureJSON = (JsonObject)featureJSONObj;

            // set a filter for the specific feature
            QueryFilter queryFilter = new QueryFilter();

            if (this.fc == null)
            {
                return(createErrorObject(
                           406,
                           "Incorrect layer id provided.",
                           new String[] { "Please provide layer id of a feature layer." }));
            }

            IClass myClass = (IClass)this.fc;

            queryFilter.WhereClause = myClass.OIDFieldName + "=" + updateFeatureId;

            IFeatureCursor featureCursor = this.fc.Search(queryFilter, false);

            // attempt retrieval of the feature and check if it does exist
            IFeatureCursor myFeatureCursor = (IFeatureCursor)featureCursor;
            IFeature       updateFeature   = myFeatureCursor.NextFeature();

            if (updateFeature == null)
            {
                return(createErrorObject(
                           406,
                           "Incorrect feature id provided.",
                           new String[] { "No feature exists for feature id "
                                          + updateFeatureId + "." }));
            }

            JsonObject response = new JsonObject();

            // edit feature
            string result = System.Text.Encoding.GetEncoding("utf-8").GetString(performEdits(updateFeature, updateFeatureJSON));

            featureCursor.Flush();
            if (result.Equals(System.Boolean.TrueString))
            {
                response.AddString("status", "success");
                response.AddString("message", "Feature " + updateFeatureId + " updated");
            }
            else
            {
                response.AddString("status", "failure");
                response.AddString("message", result);
            }

            // send response back to client app
            return(Encoding.UTF8.GetBytes(response.ToJson()));
        }
Ejemplo n.º 2
0
        public void PlotShorePoints(string sShorelineLayer, double dblInterval)
        {
            IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
            IMap        pmap   = pmxdoc.FocusMap;


            IFeatureLayer pShorelineLayer = FindLayer(pmap, sShorelineLayer) as IFeatureLayer;
            IFeatureLayer pShorePoints    = FindLayer(pmap, "ShorePoints") as IFeatureLayer;



            //Set up the Outpoints cursor
            IFeatureCursor pFCurOutPoints = pShorePoints.Search(null, false);

            pFCurOutPoints = pShorePoints.FeatureClass.Insert(true);


            ////Set up the LineLayer Cursor
            //IFeatureCursor pFCur = pShorelineLayer.Search(null, false);
            //IFeature pLineFeature = pFCur.NextFeature();
            IFeatureSelection pShoreLineSelection = pShorelineLayer as IFeatureSelection;

            if (pShoreLineSelection.SelectionSet.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("You must first select at least one feature in the shoreline layer to proceed.");
                pmap.DeleteLayer(pShorelineLayer);
                pmap.DeleteLayer(pShorePoints);
                return;
            }
            ICursor        pShorelineCursor;
            IFeatureCursor pSelShoreFeatCur;

            pShoreLineSelection.SelectionSet.Search(null, false, out pShorelineCursor);
            pSelShoreFeatCur = pShorelineCursor as IFeatureCursor;
            IFeature pShoreLineFeature = pSelShoreFeatCur.NextFeature();



            IFeatureBuffer pFBuffer = pShorePoints.FeatureClass.CreateFeatureBuffer();
            ICurve         pCurve;
            IPoint         ppoint;

            double dblTotalDistanceCalculated = 0;
            double dblDistance = 0;

            while (pShoreLineFeature != null)
            {
                pCurve = pShoreLineFeature.Shape as ICurve;
                pCurve.Project(pmap.SpatialReference);

                ppoint = new PointClass();

                while (dblTotalDistanceCalculated <= pCurve.Length)
                {
                    //this code set the point on the line at a distance
                    pCurve.QueryPoint(0, dblDistance, false, ppoint);

                    dblDistance = dblDistance + dblInterval;
                    dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval;

                    //Insert the feature into the featureclass
                    pFBuffer.Shape = ppoint;
                    pFCurOutPoints.InsertFeature(pFBuffer);
                }
                dblDistance = 0;
                dblTotalDistanceCalculated = 0;
                pShoreLineFeature          = pSelShoreFeatCur.NextFeature();
            }
            pFCurOutPoints.Flush();
            pSelShoreFeatCur.Flush();
            pmxdoc.ActiveView.Refresh();
        }
Ejemplo n.º 3
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            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();
            }

            pFCursor.Flush();

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

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

            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_LARRY.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_neighbor.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_SASbi.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 strSigLv   = nudSigLv.Value.ToString();
            string strLSig    = cboLocalL.Text;
            string strRsig    = cboLocalPearson.Text;
            string strRowStd  = cboRowStandardization.Text;
            string strNonZero = null;

            if (chkDiagZero.Checked)
            {
                strNonZero = "FALSE";
            }
            else
            {
                strNonZero = "TRUE";
            }

            pEngine.Evaluate("sample.result <- LARRY.bivariate.spatial.cluster(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, global.sig = " +
                             strSigLv + ", method = '" + strLSig + "', type.row.stand = '" + strRowStd + "', alternative = 'two', diag.zero = " + strNonZero + ")");

            string[] strGlobal = pEngine.Evaluate("as.character(sample.result[[1]]$sig.global)").AsCharacter().ToArray();
            string[] strFDR    = pEngine.Evaluate("as.character(sample.result[[1]]$sig.FDR)").AsCharacter().ToArray();
            string[] strSpBonf = pEngine.Evaluate("as.character(sample.result[[1]]$sig.spBonf)").AsCharacter().ToArray();
            string[] strBonf   = pEngine.Evaluate("as.character(sample.result[[1]]$sig.genBonf)").AsCharacter().ToArray();
            string[] strQuad   = pEngine.Evaluate("as.character(sample.result[[1]]$final.quad)").AsCharacter().ToArray();

            string[] strSigLevels = pEngine.Evaluate("as.character(round(sample.result[[2]],6))").AsCharacter().ToArray();
            //Save Output on SHP
            //Add Target fields to store results in the shapefile
            for (int j = 0; j < 5; j++)
            {
                string strfldName = lvFields.Items[j].SubItems[1].Text;
                if (pFClass.FindField(strfldName) == -1)
                {
                    IField     newField  = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)newField;
                    fieldEdit.Name_2 = strfldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    pFClass.AddField(newField);

                    //MessageBox.Show("Same field name exists.", "Same field name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //pfrmProgress.Close();
                    //return;
                }
            }

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

            string strFinalQuadFldName  = lvFields.Items[4].SubItems[1].Text;
            int    intGlobalFldIdx      = pFClass.FindField(lvFields.Items[0].SubItems[1].Text);
            int    intFDRFldIdx         = pFClass.FindField(lvFields.Items[1].SubItems[1].Text);
            int    intSpatialBonfFldIdx = pFClass.FindField(lvFields.Items[2].SubItems[1].Text);
            int    intGenBonfFldIdx     = pFClass.FindField(lvFields.Items[3].SubItems[1].Text);
            int    intFinalQuadFldIdx   = pFClass.FindField(strFinalQuadFldName);

            int featureIdx = 0;

            while (pFeature != null)
            {
                pFeature.set_Value(intGlobalFldIdx, strGlobal[featureIdx]);
                pFeature.set_Value(intFDRFldIdx, strFDR[featureIdx]);
                pFeature.set_Value(intSpatialBonfFldIdx, strSpBonf[featureIdx]);
                pFeature.set_Value(intGenBonfFldIdx, strBonf[featureIdx]);
                pFeature.set_Value(intFinalQuadFldIdx, strQuad[featureIdx]);

                pFCursor.UpdateFeature(pFeature);

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

            if (chkMap.Checked)
            {
                double[,] adblMinMaxForLabel = new double[2, 4];
                ITable pTable = (ITable)pFClass;

                IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                pUniqueValueRenderer.FieldCount = 1;
                pUniqueValueRenderer.set_Field(0, strFinalQuadFldName);
                ISimpleFillSymbol pSymbol;
                IQueryFilter      pQFilter = new QueryFilterClass();
                int    intTotalCount       = 0;
                string strHeading          = null;
                int    intSigIdx           = 0;

                for (int j = 0; j < 16; j++)
                {
                    pSymbol       = new SimpleFillSymbolClass();
                    pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                    pSymbol.Color = m_pSnippet.getRGB(m_pClusterSymbols[j].R, m_pClusterSymbols[j].G, m_pClusterSymbols[j].B);


                    if (j % 4 == 0)
                    {
                        intTotalCount = 0;
                        for (int k = 0; k < 4; k++)
                        {
                            pQFilter.WhereClause = strFinalQuadFldName + " = '" + m_pClusterSymbols[j + k].Value + "'";
                            int intCnt = pTable.RowCount(pQFilter);
                            intTotalCount += intCnt;
                        }

                        intSigIdx = 3;

                        strHeading = m_pClusterSymbols[j].Heading + " (" + intTotalCount.ToString() + ")";
                        pUniqueValueRenderer.AddValue(m_pClusterSymbols[j].Value, strHeading, (ISymbol)pSymbol);
                        pUniqueValueRenderer.set_Label(m_pClusterSymbols[j].Value, m_pClusterSymbols[j].Label + "(" + strSigLevels[intSigIdx] + ")");
                    }
                    else
                    {
                        intSigIdx--;
                        pUniqueValueRenderer.AddValue(m_pClusterSymbols[j].Value, strHeading, (ISymbol)pSymbol);
                        pUniqueValueRenderer.set_Label(m_pClusterSymbols[j].Value, m_pClusterSymbols[j].Label + "(" + strSigLevels[intSigIdx] + ")");
                    }
                }

                string strNotSig = "not sig.";
                pSymbol       = new SimpleFillSymbolClass();
                pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                pSymbol.Color = m_pSnippet.getRGB(255, 255, 255);

                pQFilter.WhereClause = strFinalQuadFldName + " = '" + strNotSig + "'";
                intTotalCount        = pTable.RowCount(pQFilter);

                pUniqueValueRenderer.AddValue(strNotSig, null, (ISymbol)pSymbol);
                pUniqueValueRenderer.set_Label(strNotSig, "Not significant (" + intTotalCount.ToString() + ")");

                pUniqueValueRenderer.UseDefaultSymbol = false;

                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = pFClass;
                pNewFLayer.Name         = "Bivariate Spatial Clusters";
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                m_pActiveView.FocusMap.AddLayer(pGFLayer);
                m_pActiveView.Refresh();
                m_pForm.axTOCControl1.Update();
                pfrmProgress.Close();
            }
            else
            {
                MessageBox.Show("Complete. The results are stored in the shape file");
            }
        }
        //开始计算
        private void Btn_Compute_Click(object sender, EventArgs e)
        {
            string tpFiledName = this.CB_Fields.Text;

            object obj = this.comboBox1.SelectedItem;

            if (obj != null && obj is CommonComboBoxItem)
            {
                CommonComboBoxItem item             = obj as CommonComboBoxItem;
                IFeatureClass      pFeatureClass    = item.Tag as IFeatureClass;
                decimal            ellipseArea      = 0;
                AnyTrapeziaEllipseAreaCompute_JF jf = new AnyTrapeziaEllipseAreaCompute_JF();
                //获取坐标系
                jf.Datum = EnumProjectionDatum.CGCS2000;
                if (this.rb2000.Checked == true)
                {
                    jf.Datum = EnumProjectionDatum.CGCS2000;
                }
                if (this.rb_xian80.Checked == true)
                {
                    jf.Datum = EnumProjectionDatum.Xian80;
                }
                if (this.rb_beijing54.Checked == true)
                {
                    jf.Datum = EnumProjectionDatum.Bejing54;
                }
                //获取大数设置
                jf.IsBigNumber = false;
                if (this.CB_IsBigNumber.Checked == true)
                {
                    jf.IsBigNumber = true;
                }
                //获取分度设置
                jf.Strip = EnumStrip.Strip6;
                if (CB_FD.Checked == true)
                {
                    jf.Strip = EnumStrip.Strip3;
                }
                //获取中央子午线
                jf.L0 = CommonClass.TDec(this.txt_DD.Text) * (int)jf.Strip;

                int             fIndex    = 0;
                int             tmpFCount = pFeatureClass.FeatureCount(null);
                frmProgressBar1 pb        = new frmProgressBar1();
                pb.Text                   = "正在进行椭球面积计算...";
                pb.KDCaption1             = "正在进行椭球面积计算...";
                pb.KDProgressBar1.Maximum = tmpFCount + 1;
                pb.KDProgressBar1.Value   = 0;
                pb.Show();
                Application.DoEvents();

                IFeatureCursor fcur = pFeatureClass.Update(null, false);
                IFeature       feat = fcur.NextFeature();
                while (feat != null)
                {
                    fIndex += 1;
                    if (fIndex % 500 == 0)
                    {
                        pb.KDCaption1           = "已计算完成要素个数:" + fIndex.ToString() + "/总" + tmpFCount.ToString();
                        pb.KDProgressBar1.Value = fIndex;
                        Application.DoEvents();
                        fcur.Flush();
                    }
                    ellipseArea = jf.Compute(feat.ShapeCopy);
                    //save ellipseArea...
                    ZhFeature zhfeat = new ZHFeaturePolygon(feat);
                    zhfeat.setFieldValue(tpFiledName, ellipseArea);

                    fcur.UpdateFeature(feat);

                    feat = fcur.NextFeature();
                }
                fcur.Flush();

                TokayWorkspace.ComRelease(fcur);
                fcur = null;


                pb.Close();
                pb.Dispose();
                pb = null;

                MessageBox.Show(this, "计算椭球面积完毕!", "提示");
            }
        }
Ejemplo n.º 5
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();


                if (cboFldNm1.Text == "")
                {
                    MessageBox.Show("Please select a proper field");
                    return;
                }

                // 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;
                //pFClass = pFLayer.FeatureClass;
                int nFeature = m_pFClass.FeatureCount(null);

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

                if (!m_blnCreateSWM)
                {
                    //Get the file path and name to create spatial weight matrix
                    string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer);

                    if (strNameR == null)
                    {
                        return;
                    }

                    //Create spatial weight matrix in R
                    if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
                    }
                    else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')");
                    }
                    else
                    {
                        MessageBox.Show("This geometry type is not supported");
                        pfrmProgress.Close();
                        this.Close();
                    }


                    int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress);
                    if (intSuccess == 0)
                    {
                        return;
                    }
                }

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

                //if (strNameR == null)
                //    return;

                //int intSuccess = 0;


                ////Create spatial weight matrix in R
                //if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                //{
                //    m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
                //    intSuccess = m_pSnippet.CreateSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked);

                //}
                //else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                //{
                //    m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')");
                //    //intSuccess = m_pSnippet.ExploreSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked);
                //    intSuccess = m_pSnippet.CreateSpatialWeightMatrixPts(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked, m_pClippedPolygon);

                //    //chkCumulate.Visible = false;
                //}
                //else
                //{
                //    MessageBox.Show("This geometry type is not supported");
                //    pfrmProgress.Close();
                //    this.Close();
                //}

                //if (intSuccess == 0)
                //    return;


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

                //Get index for independent and dependent variables
                //Get variable index
                string strVarNM  = (string)cboFldNm1.SelectedItem;
                int    intVarIdx = m_pFClass.FindField(strVarNM);
                int    intFIDIdx = m_pFClass.FindField(m_pFClass.OIDFieldName);  // Collect FIDs to apply Brushing and Linking

                //Store Variable at Array
                double[] arrVar = new double[nFeature];
                int[]    arrFID = new int[nFeature];

                int i = 0;

                m_arrXYCoord = new double[nFeature, 2];
                List <int>[] NBIDs = new List <int> [nFeature];

                IArea  pArea;
                IPoint pPoint;

                while (pFeature != null)
                {
                    if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        pArea = (IArea)pFeature.Shape;
                        m_arrXYCoord[i, 0] = pArea.Centroid.X;
                        m_arrXYCoord[i, 1] = pArea.Centroid.Y;
                    }
                    else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        pPoint             = (IPoint)pFeature.Shape;
                        m_arrXYCoord[i, 0] = pPoint.X;
                        m_arrXYCoord[i, 1] = pPoint.Y;
                    }
                    NBIDs[i] = m_pEngine.Evaluate("sample.nb[[" + (i + 1).ToString() + "]]").AsInteger().ToList();

                    arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx));
                    arrFID[i] = Convert.ToInt32(pFeature.get_Value(intFIDIdx));
                    i++;
                    pFeature = pFCursor.NextFeature();
                }
                pFCursor.Flush();


                //Collect NB for Brushing and linking

                NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar);
                m_pEngine.SetSymbol(strVarNM, vecVar);

                if (chkStd.Checked)
                {
                    m_pEngine.Evaluate(strVarNM + " <- scale(" + strVarNM + ")");     //Scaled
                    vecVar = m_pEngine.Evaluate(strVarNM).AsNumeric();
                }

                NumericVector vecWeightVar = null;
                if (cboMethod.Text == "MC")
                {
                    vecWeightVar = m_pEngine.Evaluate("wx.sample <- lag.listw(sample.listw, " + strVarNM + ", zero.policy=TRUE)").AsNumeric();
                }
                else if (cboMethod.Text == "GR")
                {
                    string strStartPath = m_pForm.strPath;
                    string pathr        = strStartPath.Replace(@"\", @"/");
                    m_pEngine.Evaluate("source('" + pathr + "/AllFunctions.R')");

                    vecWeightVar = m_pEngine.Evaluate("wx.sample <- diff.lag.listw(sample.listw, " + strVarNM + ")").AsNumeric();
                }
                else if (cboMethod.Text == "L")
                {
                    string strStartPath = m_pForm.strPath;
                    string pathr        = strStartPath.Replace(@"\", @"/");
                    m_pEngine.Evaluate("source('" + pathr + "/AllFunctions.R')");

                    vecWeightVar = m_pEngine.Evaluate("wx.sample <- diff.lag.listw(sample.listw, " + strVarNM + ")").AsNumeric();
                }

                m_pEngine.SetSymbol("WVar.sample", vecWeightVar);
                //double[] arrWeightVar = vecWeightVar.ToArray();
                NumericVector vecCoeff = m_pEngine.Evaluate("lm(WVar.sample~" + strVarNM + ")$coefficients").AsNumeric();

                frmMScatterResults pfrmMScatterResult = new frmMScatterResults();
                pfrmMScatterResult.m_arrXYCoord = m_arrXYCoord;
                pfrmMScatterResult.m_NBIDs      = NBIDs;
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsStartedFromZero = false;
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsMarginVisible   = true;

                pfrmMScatterResult.pChart.ChartAreas[0].AxisY.IsStartedFromZero = false;

                pfrmMScatterResult.Text = "Moran Scatter Plot of " + m_pFLayer.Name;
                pfrmMScatterResult.pChart.Series.Clear();
                System.Drawing.Color pMarkerColor = System.Drawing.Color.Blue;
                var seriesPts = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name              = "Points",
                    Color             = pMarkerColor,
                    BorderColor       = pMarkerColor,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                    MarkerStyle       = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle
                };

                pfrmMScatterResult.pChart.Series.Add(seriesPts);

                for (int j = 0; j < vecVar.Length; j++)
                {
                    seriesPts.Points.AddXY(vecVar[j], vecWeightVar[j]);
                }



                var VLine = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name            = "VLine",
                    Color           = System.Drawing.Color.Black,
                    BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash,
                    //BorderColor = System.Drawing.Color.Black,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                };
                pfrmMScatterResult.pChart.Series.Add(VLine);

                VLine.Points.AddXY(vecVar.Average(), vecWeightVar.Min());
                VLine.Points.AddXY(vecVar.Average(), vecWeightVar.Max());

                var HLine = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name            = "HLine",
                    Color           = System.Drawing.Color.Black,
                    BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash,
                    //BorderColor = System.Drawing.Color.Black,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                };
                pfrmMScatterResult.pChart.Series.Add(HLine);

                HLine.Points.AddXY(vecVar.Min(), vecWeightVar.Average());
                HLine.Points.AddXY(vecVar.Max(), vecWeightVar.Average());

                var seriesLine = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name  = "RegLine",
                    Color = System.Drawing.Color.Red,
                    //BorderColor = System.Drawing.Color.Black,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                };

                pfrmMScatterResult.pChart.Series.Add(seriesLine);

                seriesLine.Points.AddXY(vecVar.Min(), vecVar.Min() * vecCoeff[1] + vecCoeff[0]);
                seriesLine.Points.AddXY(vecVar.Max(), vecVar.Max() * vecCoeff[1] + vecCoeff[0]);

                if (chkStd.Checked)
                {
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.Title = "standardized " + strVarNM;
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisY.Title = "Spatially lagged standardized " + strVarNM;
                    pfrmMScatterResult.lblRegression.Text = "Spatially lagged standardized " + strVarNM + " = " + vecCoeff[1].ToString("N3") + " * " + "standardized " + strVarNM;
                }
                else
                {
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.Title = strVarNM;
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisY.Title = "Spatially lagged " + strVarNM;
                    pfrmMScatterResult.lblRegression.Text = "Spatially lagged " + strVarNM + " = " + vecCoeff[1].ToString("N3") + " * " + strVarNM + " + " + vecCoeff[0].ToString("N3");
                }

                pfrmMScatterResult.m_pForm       = m_pForm;
                pfrmMScatterResult.m_pFLayer     = m_pFLayer;
                pfrmMScatterResult.m_pActiveView = m_pActiveView;
                pfrmMScatterResult.arrVar        = arrVar;
                pfrmMScatterResult.arrFID        = arrFID;
                pfrmMScatterResult.strFIDNM      = m_pFClass.OIDFieldName;
                //pfrmMScatterResult.arrWeightVar = arrWeightVar;
                pfrmMScatterResult.pMakerColor = pMarkerColor;
                pfrmMScatterResult.strVarNM    = strVarNM;

                if (chkStd.Checked)
                {
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false;
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.CustomLabels.Clear();
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.TickMarkStyle = System.Windows.Forms.DataVisualization.Charting.TickMarkStyle.None;
                    //pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.Interval = 1;
                    //pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.IntervalOffset = -2;

                    int intMin = Convert.ToInt32(Math.Floor(vecVar.Min()));
                    int intMax = Convert.ToInt32(Math.Ceiling(vecVar.Max()));
                    for (int n = intMin; n < intMax; n++)
                    {
                        System.Windows.Forms.DataVisualization.Charting.CustomLabel pcutsomLabel = new System.Windows.Forms.DataVisualization.Charting.CustomLabel();
                        pcutsomLabel.FromPosition = n - 0.5;
                        pcutsomLabel.ToPosition   = n + 0.5;
                        pcutsomLabel.Text         = n.ToString();
                        pfrmMScatterResult.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel);
                    }
                }

                pfrmMScatterResult.Show();
                pfrmProgress.Close();
                //this.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 6
0
        private void EvalStat(double[] cb)
        {
            IFeatureClass pFClass      = m_pFLayer.FeatureClass;
            string        strValueFld  = m_pRenderedLayer.strValueFldName;
            string        strUncernfld = string.Empty;

            if (m_pRenderedLayer.strUncernFldName == string.Empty)
            {
                strUncernfld = cboUncernFld.Text;
            }
            else
            {
                strUncernfld = m_pRenderedLayer.strUncernFldName;
            }
            if (strUncernfld == string.Empty)
            {
                return;
            }

            int intValueIdx  = pFClass.FindField(strValueFld);
            int intUncernIdx = pFClass.FindField(strUncernfld);

            int intClassCount = cb.Length - 1;

            double[,] arrEvalStat = new double[intClassCount, 5];

            string strTempfldName = txtFldName.Text;

            strTempfldName = "MinSepfave";

            int   intFCounts = pFClass.FeatureCount(null);
            Chart pChart     = new Chart();



            IFeatureCursor pFCursor = null;

            pFCursor = pFClass.Search(null, false);

            IQueryFilter pQfilter = new QueryFilterClass();

            for (int j = 0; j < intClassCount; j++)
            {
                if (j == 0)
                {
                    pQfilter.WhereClause = strValueFld + " >= " + cb[j].ToString() + " AND " + strValueFld + " <= " + cb[j + 1].ToString();
                }
                else
                {
                    pQfilter.WhereClause = strValueFld + " > " + cb[j].ToString() + " AND " + strValueFld + " <= " + cb[j + 1].ToString();
                }

                pFCursor = pFClass.Search(pQfilter, true);
                IFeatureCursor pSortedCursor = SortData(pFCursor, pFClass, pQfilter, strValueFld);
                IFeature       pFeat         = null;
                pFeat = pSortedCursor.NextFeature();
                int      intSelCnt = pFClass.FeatureCount(pQfilter);
                int      i         = 0;
                double[] arrSubEst = new double[intSelCnt];
                double[] arrSubVar = new double[intSelCnt];

                while (pFeat != null)
                {
                    arrSubEst[i] = Convert.ToDouble(pFeat.get_Value(intValueIdx));
                    arrSubVar[i] = Convert.ToDouble(pFeat.get_Value(intUncernIdx));
                    i++;
                    pFeat = pSortedCursor.NextFeature();
                }
                pSortedCursor.Flush();

                arrEvalStat[j, 0] = intSelCnt;
                arrEvalStat[j, 1] = SumSeperablility(arrSubEst, arrSubVar);
                arrEvalStat[j, 2] = SumBhatta(arrSubEst, arrSubVar);
                arrEvalStat[j, 3] = MaxSeperablility(arrSubEst, arrSubVar);
                arrEvalStat[j, 4] = MaxBhatta(arrSubEst, arrSubVar);
            }

            //int k = 0;
            //IFeatureCursor pSortedCursor = SortData(pFCursor, pFClass

            UpdateRangeRobustness(lvSymbol, intClassCount, cb, dblClsMean, dblMeanRobustness, arrEvalStat);

            //double[,] arrRobustness = new double[intFCounts, 2];
            //arrValue = new double[intFCounts];//For visualizing

            //int i = 0;
            //while (pFeat != null)
            //{
            //    for (int j = 0; j < intClassCount; j++)
            //    {

            //        double dblValue = Convert.ToDouble(pFeat.get_Value(intValueIdx));
            //        double dblStd = Convert.ToDouble(pFeat.get_Value(intUncernIdx));
            //        if (j == 0)
            //        {
            //            if (dblValue >= cb[j] && dblValue <= cb[j + 1])
            //            {
            //                double dblUpperZvalue = (cb[j + 1] - dblValue) / dblStd;
            //                double dblUpperConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblUpperZvalue);
            //                double dblLowerZvalue = (cb[j] - dblValue) / dblStd;
            //                double dblLowerConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblLowerZvalue);
            //                arrRobustness[i, 0] = dblUpperConfLev - dblLowerConfLev;
            //                arrRobustness[i, 1] = j;
            //                arrValue[i] = arrRobustness[i, 0];
            //                if (chkRobustness.Checked)
            //                    pFeat.set_Value(intTempfldIdx, arrValue[i]);
            //            }

            //        }
            //        else
            //        {
            //            if (dblValue > cb[j] && dblValue <= cb[j + 1])
            //            {
            //                double dblUpperZvalue = (cb[j + 1] - dblValue) / dblStd;
            //                double dblUpperConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblUpperZvalue);
            //                double dblLowerZvalue = (cb[j] - dblValue) / dblStd;
            //                double dblLowerConfLev = pChart.DataManipulator.Statistics.NormalDistribution(dblLowerZvalue);
            //                arrRobustness[i, 0] = dblUpperConfLev - dblLowerConfLev;
            //                arrRobustness[i, 1] = j;
            //                arrValue[i] = arrRobustness[i, 0];
            //                if (chkRobustness.Checked)
            //                    pFeat.set_Value(intTempfldIdx, arrValue[i]);
            //            }
            //        }
            //    }
            //    i++;
            //    if (chkRobustness.Checked)
            //        pFCursor.UpdateFeature(pFeat);
            //    pFeat = pFCursor.NextFeature();
            //}
            //double[,] dblClsMean = new double[intClassCount, 3];
            //double dblSumRobustness = 0;
            //for (int j = 0; j < intFCounts; j++)
            //{
            //    dblSumRobustness = dblSumRobustness + arrRobustness[j, 0];
            //    for (int k = 0; k < intClassCount; k++)
            //    {
            //        if (arrRobustness[j, 1] == k)
            //        {
            //            dblClsMean[k, 0] = arrRobustness[j, 0] + dblClsMean[k, 0];
            //            dblClsMean[k, 1] = dblClsMean[k, 1] + 1;
            //        }
            //    }
            //}
            //for (int k = 0; k < intClassCount; k++)
            //{
            //    dblClsMean[k, 2] = dblClsMean[k, 0] / dblClsMean[k, 1];
            //}
            //double dblMeanRobustness = dblSumRobustness / intFCounts;
            //UpdateRangeRobustness(lvSymbol, intClassCount, cb, dblClsMean, dblMeanRobustness);
        }
Ejemplo n.º 7
0
        public bool constuctGrid3Ds(int mingxid, int maxgxid, int mingyid, int maxgyid, short type)
        {
            DataTable gridTable = new DataTable();
            Hashtable para      = new Hashtable();

            para["minGXID"] = mingxid;
            para["maxGXID"] = maxgxid;
            para["minGYID"] = mingyid;
            para["maxGYID"] = maxgyid;
            para["type"]    = type;

            gridTable = IbatisHelper.ExecuteQueryForDataTable("getDefect", para);
            if (gridTable.Rows.Count < 1)
            {
                return(false);
            }

            IDataset   dataset   = (IDataset)pFeatureLayer.FeatureClass;
            IWorkspace workspace = dataset.Workspace;
            //Cast for an IWorkspaceEdit
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            //start an edit session and operation
            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            int    gxid, gyid, level;
            double x1, y1, x2, y2, z;
            double recePower;
            double gbaseheight = GridHelper.getInstance().getGBaseHeight();
            double gheight     = GridHelper.getInstance().getGHeight();
            //循环添加
            int cnt = 0;

            foreach (DataRow dataRow in gridTable.Rows)
            {
                if (++cnt % 100 == 0)
                {
                    Console.WriteLine(cnt + "/" + gridTable.Rows.Count);
                }
                gxid  = int.Parse(dataRow["GXID"].ToString());
                gyid  = int.Parse(dataRow["GYID"].ToString());
                level = int.Parse(dataRow["GZID"].ToString());

                if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1)))
                {
                    continue;
                }
                if (!(double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2)))
                {
                    continue;
                }
                if (!(double.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower)))
                {
                    continue;
                }
                z = gheight * level;

                IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z);
                IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z);
                IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z);
                IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z);

                IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD });
                GeometryUtilities.MakeZAware(pGeometryColl as IGeometry);


                pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
                pFeatureBuffer.Shape = pGeometryColl as IGeometry;
                pFeatureBuffer.set_Value(this.GXIDIndex, gxid);
                pFeatureBuffer.set_Value(this.GYIDIndex, gyid);
                pFeatureBuffer.set_Value(this.LevelIndex, level);

                if (recePower > -41)
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, -41);
                }
                else
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, recePower);
                }
                pFeatureCursor.InsertFeature(pFeatureBuffer);
            }

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            //IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;
            //pFeatureClassManage.UpdateExtent();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);

            //GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            return(true);
        }
Ejemplo n.º 8
0
        //不剪裁输出
        private void notcutExport(IFeatureClass pFromFeaCls, IFeatureClass pToFeatureClass, DateTime dt, string strUser, ref int intSucCount, ref string strError)
        {
            try
            {
                strError    = "";
                intSucCount = 0;
                int            intCount       = pFromFeaCls.FeatureCount(null);
                IFeatureCursor pCursor        = pFromFeaCls.Search(null, false);
                IFeature       pFeature       = pCursor.NextFeature();
                IFeatureCursor pFeatureCursor = pToFeatureClass.Insert(true);
                IFeatureBuffer pFeatureBuffer = pToFeatureClass.CreateFeatureBuffer();

                OnInitProBarChangHandler(intCount);
                OnLblChange("正在复制:" + pFromFeaCls.AliasName);

                int iCount = 0;
                while (pFeature != null)
                {
                    for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                    {
                        string sFieldName = pFeature.Fields.get_Field(i).Name;

                        int iIndex = pFeatureBuffer.Fields.FindField(sFieldName);

                        if ((iIndex > -1) && (pFeatureBuffer.Fields.get_Field(iIndex).Editable == true))
                        {
                            pFeatureBuffer.set_Value(iIndex, pFeature.get_Value(i));
                        }
                    }
                    if (pEnumFieldError != null)//yjl20110804 add
                    {
                        pEnumFieldError.Reset();
                        IFieldError pFieldError = pEnumFieldError.Next();
                        while (pFieldError != null)
                        {
                            int srcIx = pFieldError.FieldIndex;                                             //错误字段的源索引
                            int desIx = pFeatureBuffer.Fields.FindField(pFixedField.get_Field(srcIx).Name); //错误字段的新索引
                            if (desIx == -1)
                            {
                                pFieldError = pEnumFieldError.Next();
                                continue;
                            }
                            IField pFld = pFeatureBuffer.Fields.get_Field(desIx);
                            if ((desIx > -1) && (pFld.Editable == true) && pFld.Type != esriFieldType.esriFieldTypeGeometry)
                            {
                                pFeatureBuffer.set_Value(desIx, pFeature.get_Value(srcIx));
                            }
                            pFieldError = pEnumFieldError.Next();
                        }
                    }
                    ////插入日期和入库人
                    //int intDateIndex = pFeatureBuffer.Fields.FindField("ImportTime");
                    //if (intDateIndex > -1) pFeatureBuffer.set_Value(intDateIndex, dt);
                    //int intUserIndex = pFeatureBuffer.Fields.FindField("ImportUser");
                    //if (intUserIndex > -1) pFeatureBuffer.set_Value(intUserIndex, strUser);

                    pFeatureBuffer.Shape = pFeature.ShapeCopy;
                    if (!InsertFea(ref pFeatureCursor, ref pFeatureBuffer))
                    {
                        strError = strError + Environment.NewLine + pFeature.OID + "  无法复制";

                        pFeatureCursor.Flush();
                        iCount = 0;
                        OnGoStepChangHandler();
                        pFeature = pCursor.NextFeature();
                        continue;
                    }

                    iCount++;
                    if (iCount == 2000)
                    {
                        pFeatureCursor.Flush();
                        iCount = 0;

                        Application.DoEvents();
                    }

                    //pbCopyRows.PerformStep();
                    OnGoStepChangHandler();
                    intSucCount++;

                    pFeature = pCursor.NextFeature();
                }
                if (iCount > 0)
                {
                    pFeatureCursor.Flush();
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                pFeatureCursor = null;

                System.Runtime.InteropServices.Marshal.ReleaseComObject(pCursor);
                pCursor        = null;
                pFeatureBuffer = null;
            }
            catch (Exception ex)
            {
                strError = strError + Environment.NewLine + ex.Message;
            }
        }
        public void GeneratePoints2(string sLineLayer, string sDepthPointsLayer, double dblInterval, string strDepthField)
        {
            try
            {
                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;

                IFeatureLayer pDepthSoundings = FindLayer(pmap, sDepthPointsLayer) as IFeatureLayer;
                IFeatureLayer pLineLayer      = FindLayer(pmap, sLineLayer) as IFeatureLayer;
                IFeatureLayer pOutpoints      = new FeatureLayerClass();
                pOutpoints.FeatureClass = MakePointFC();
                pOutpoints.Name         = "Output Points";
                ArcMap.Document.ActiveView.FocusMap.AddLayer(pOutpoints);

                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", pLineLayer.FeatureClass.FeatureCount(null), 1);
                pProgressDialog.ShowDialog();

                //Set up the Outpoints cursor
                IFeatureCursor pFCurOutPoints = pOutpoints.Search(null, false);
                pFCurOutPoints = pOutpoints.FeatureClass.Insert(true);

                //Set up the LineLayer Cursor
                IFeatureCursor pFCur        = pLineLayer.Search(null, false);
                IFeature       pLineFeature = pFCur.NextFeature();

                IFeatureBuffer pFBuffer = pOutpoints.FeatureClass.CreateFeatureBuffer();

                ICurve pCurve;
                IPoint ppoint;

                int    iLineProgressCount         = 1;
                double dblDistance                = 0;
                double dblTotalDistanceCalculated = 0;
                double iNumIntervals              = 0;
                double dblElevationDiff           = 0;
                double dblElevationInterval       = 0;
                double dblElevation               = 0;
                double dlbStartElevation          = 0;
                double dblEndElevation            = 0;

                pProgressDialog.Description = "Generating points for Line: " + iLineProgressCount + " of " + pLineLayer.FeatureClass.FeatureCount(null).ToString();

                while (pLineFeature != null)
                {
                    int iStartVertex = 0;
                    int iEndVertex   = 1;
                    //Get the vertices of the line feature
                    IPointCollection4 pPointColl = pLineFeature.Shape as IPointCollection4;


                    //loop thru the vertices
                    for (int i = 0; i <= pPointColl.PointCount - 1; i++)
                    {
                        IPoint pStartPoint = pPointColl.get_Point(iStartVertex);
                        IPoint pEndPoint   = pPointColl.get_Point(iEndVertex);
                        //Make an intermediate line segment between each set of vertices
                        IPath pPath = MakePath(pStartPoint, pEndPoint);

                        //Get the starting elevation from the depth point layer
                        dlbStartElevation = GetPointElevation(pDepthSoundings, pLineLayer, pStartPoint, strDepthField);
                        dblElevation      = dlbStartElevation;
                        IPointCollection pPointForPath = null;
                        //Get the ending elevation from the next vertex
                        pEndPoint       = pPointColl.get_Point(iEndVertex);
                        dblEndElevation = GetPointElevation(pDepthSoundings, pLineLayer, pEndPoint, strDepthField);
                        //If the returned elevation is 0, then there is no coincident depth point, move to the next vertex for your endpoint
                        if (dblEndElevation == 0)
                        {
                            //IPointCollection reshapePath = new PathClass();
                            object missing = Type.Missing;
                            pPointForPath = new PathClass();
                            pPointForPath.AddPoint(pStartPoint, ref missing, ref missing);
                            while (dblEndElevation == 0)
                            {
                                pEndPoint       = pPointColl.get_Point(iEndVertex);
                                dblEndElevation = GetPointElevation(pDepthSoundings, pLineLayer, pEndPoint, strDepthField);


                                pPointForPath.AddPoint(pEndPoint, ref missing, ref missing);
                                //pLineSegment.Reshape(reshapePath as IPath);

                                if (dblEndElevation != 0)
                                {
                                    break;
                                }
                                iEndVertex++;
                            }
                        }

                        if (pPointForPath != null)
                        {
                            pPath = pPointForPath as IPath;
                        }



                        //number of line segments based on the user's interval
                        iNumIntervals    = Convert.ToDouble(pPath.Length / dblInterval);
                        dblElevationDiff = dblEndElevation - dlbStartElevation;

                        //The calculated elevation interval to step up each time
                        dblElevationInterval = dblElevationDiff / iNumIntervals;


                        ppoint = new PointClass();

                        while (dblTotalDistanceCalculated <= pPath.Length)
                        {
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dblDistance, 4));
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("Elevation"), Math.Round(dblElevation, 4));


                            //this code set the point on the line at a distance
                            pPath.QueryPoint(0, dblDistance, false, ppoint);



                            pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), ppoint.X);
                            pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), ppoint.Y);

                            //reCalc the new distance and elevation values for the next iteration
                            dblDistance = dblDistance + dblInterval;
                            dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval;

                            //Insert the feature into the featureclass
                            pFBuffer.Shape = ppoint;

                            if (!IsPointCoincident(ppoint, pOutpoints))
                            {
                                pFCurOutPoints.InsertFeature(pFBuffer);
                            }


                            if (dblTotalDistanceCalculated >= pPath.Length)
                            {
                                break;
                            }

                            dblElevation = dblElevation + dblElevationInterval;
                        }



                        //start the next line segment at the end of last one
                        iStartVertex = iEndVertex;
                        //look to the next vertex for the new ending point
                        iEndVertex++;


                        if (iEndVertex == pPointColl.PointCount)
                        {
                            ////if its the last vertex of the last line, add a point
                            //pFBuffer.Shape = pPath.ToPoint;
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dblDistance, 4));
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("Elevation"), Math.Round(dblElevation, 4));
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), pPath.ToPoint.X);
                            //pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), pPath.ToPoint.Y);
                            //pFCurOutPoints.InsertFeature(pFBuffer);

                            //Reset the distance values back to 0 for the next feature
                            dblDistance = 0;
                            dblTotalDistanceCalculated = 0;
                            pStepProgressor.Step();
                            iLineProgressCount++;
                            pPath.SetEmpty();
                            break;
                        }


                        //Reset the distance values back to 0 for the next feature
                        dblDistance = 0;
                        dblTotalDistanceCalculated = 0;
                        //pLineFeature = pFCur.NextFeature();
                        pStepProgressor.Step();
                        //pProgressDialog.Description = "Generating points for Line: " + iLineProgressCount + " of " + pLineLayer.FeatureClass.FeatureCount(null).ToString();
                        iLineProgressCount++;
                        pPath.SetEmpty();
                    }
                    pLineFeature = pFCur.NextFeature();
                }



                //cleanup
                pFCurOutPoints.Flush();
                pFCur.Flush();
                pProgressDialog.HideDialog();
                pmxdoc.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 构造小区立体顶面覆盖网格
        /// </summary>
        /// <param name="cellname"></param>
        /// <param name="lac"></param>
        /// <param name="ci"></param>
        public void constuctCellGrid3Dtops(string cellname, int eNodeB, int ci)
        {
            DataTable gridTable = new DataTable();
            Hashtable ht        = new Hashtable();

            ht["eNodeB"] = eNodeB;
            ht["CI"]     = ci;
            gridTable    = IbatisHelper.ExecuteQueryForDataTable("GetSpecifiedCellGrid3Ds", ht);
            //gridTable = IbatisHelper.ExecuteQueryForDataTable("GetAreaGrid3Ds", null);

            IDataset   dataset   = (IDataset)pFeatureLayer.FeatureClass;
            IWorkspace workspace = dataset.Workspace;
            //Cast for an IWorkspaceEdit
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            //start an edit session and operation
            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            int    gxid, gyid, level;
            double x1, y1, x2, y2, z;
            double recePower, pathLoss;
            double gbaseheight = GridHelper.getInstance().getGBaseHeight();
            double gheight     = GridHelper.getInstance().getGHeight();

            //循环添加
            foreach (DataRow dataRow in gridTable.Rows)
            {
                gxid  = int.Parse(dataRow["Gxid"].ToString());
                gyid  = int.Parse(dataRow["Gyid"].ToString());
                level = int.Parse(dataRow["level"].ToString());
                Geometric.Point p   = GridHelper.getInstance().GridToGeo(gxid, gyid);
                double          lon = p.X;
                double          lat = p.Y;
                if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1) && double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2) && double.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower) && double.TryParse(dataRow["PathLoss"].ToString(), out pathLoss)))
                {
                    continue;
                }
                z = gheight * (level - 1) + gbaseheight;

                IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z);
                IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z);
                IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z);
                IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z);

                IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD });
                GeometryUtilities.MakeZAware(pGeometryColl as IGeometry);


                pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
                pFeatureBuffer.Shape = pGeometryColl as IGeometry;
                pFeatureBuffer.set_Value(this.GXIDIndex, gxid);
                pFeatureBuffer.set_Value(this.GYIDIndex, gyid);
                pFeatureBuffer.set_Value(this.LevelIndex, level);
                pFeatureBuffer.set_Value(this.eNodeBIndex, eNodeB);
                pFeatureBuffer.set_Value(this.CIIndex, ci);
                pFeatureBuffer.set_Value(this.cellNameIndex, cellname);
                pFeatureBuffer.set_Value(this.LongitudeIndex, lon);
                pFeatureBuffer.set_Value(this.LatitudeIndex, lat);
                if (recePower > -41)
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, -41);
                }
                //else if (recePower < -110)
                //    pFeatureBuffer.set_Value(this.RecePowerIndex, -110);
                else
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, recePower);
                }
                pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss);
                pFeatureCursor.InsertFeature(pFeatureBuffer);
            }

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            //IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;
            //pFeatureClassManage.UpdateExtent();

            GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            //GISMapApplication.Instance.FullExtent(pFeatureLayer.AreaOfInterest);
        }
Ejemplo n.º 11
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++)
            {
                //BhattaVariables tmp = new BhattaVariables();
                //tmp.variableNames = (string)dgvVariables.Rows[j].Cells[0].Value;
                //tmp.errorNames = (string)dgvVariables.Rows[j].Cells[1].Value;

                //tmp.idVar = m_pFClass.Fields.FindField(tmp.variableNames);
                //tmp.idError = m_pFClass.Fields.FindField(tmp.errorNames);

                //tmp.arrVar = new double[nFeature];
                //tmp.arrError = new double[nFeature];

                //pBVariable.Add(tmp);
                pBVariable[j] = new BhattaVariables();
                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";

            if (cboDistance.Text == "Bhattacharyya distance") //Bhatta dist
            {
                string strStartPath = m_pForm.strPath;
                string pathr        = strStartPath.Replace(@"\", @"/");
                m_pEngine.Evaluate("source('" + pathr + "/clustering.R')");

                //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 < k + 1; l++)
                    {
                        for (int j = 0; j < 4; j++)
                        {
                            plotCommmand[j] = new StringBuilder();
                        }

                        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[l].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 + 1).ToString() + ", " + (l + 1).ToString() + "] <- Bhatta.mdist(x1, x2, v1, v2)");
                        m_pEngine.Evaluate("Bhatta.diss[" + (l + 1).ToString() + ", " + (k + 1).ToString() + "] <- Bhatta.mdist(x2, x1, v2, v1)");
                    }
                }

                pfrmProgress.lblStatus.Text = "Finding Clusters";

                m_pEngine.Evaluate("sample.hclu <- hclust(as.dist(Bhatta.diss))");
            }
            else if (cboDistance.Text == "Euclidean distance")
            {
                StringBuilder plotCommmand = new StringBuilder();
                plotCommmand.Append("Euc.dis <- dist(cbind(");

                for (int j = 0; j < intnVar; j++)
                {
                    NumericVector vecVar = m_pEngine.CreateNumericVector(pBVariable[j].arrVar);
                    m_pEngine.SetSymbol(pBVariable[j].variableNames, vecVar);
                    plotCommmand.Append(pBVariable[j].variableNames + ", ");
                }

                plotCommmand.Remove(plotCommmand.Length - 2, 2);
                plotCommmand.Append("))");
                m_pEngine.Evaluate(plotCommmand.ToString());

                pfrmProgress.lblStatus.Text = "Finding Clusters";

                m_pEngine.Evaluate("sample.hclu <- hclust(Euc.dis)");
            }

            string strTitle   = "Dendrogram";
            string strCommand = "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
            pfrmProgress.lblStatus.Text = "Save Results";
            //The field names are related with string[] DeterminedName in clsSnippet
            string strOutputFldName = txtOutputFld.Text;

            //Get EVs and residuals
            NumericVector nvClasses = m_pEngine.Evaluate("sample.cut").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 intOutputFldIdx = m_pFClass.FindField(strOutputFldName);

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

                pFCursor.UpdateFeature(pFeature);

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

            //Not working properly
            ////Creating unique value map
            //IGeoFeatureLayer geoFeatureLayer = (IGeoFeatureLayer)m_pFLayer;
            //IUniqueValueRenderer uniqueValueRenderer = new UniqueValueRendererClass();
            //uniqueValueRenderer.FieldCount = 1;
            //uniqueValueRenderer.set_Field(0, strOutputFldName);


            //IDataStatistics pDataStat = new DataStatisticsClass();
            //pDataStat.Field = strOutputFldName;
            //ITable pTable = (ITable)m_pFClass;
            //ICursor pCursor = pTable.Search(null, true);
            //pDataStat.Cursor = pCursor;
            //int intUniqValueCnt = pDataStat.UniqueValueCount;

            //System.Collections.IEnumerator enumerator = pDataStat.UniqueValues;
            //enumerator.Reset();

            //ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbolClass();
            //simpleFillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
            //IEnumColors enumColors = CreateAlgorithmicColorRamp(intUniqValueCnt).Colors;


            //for (int j = 0; j < intUniqValueCnt; j++)
            //{
            //    string value = enumerator.Current.ToString();
            //    enumerator.MoveNext();
            //    simpleFillSymbol = new SimpleFillSymbolClass();
            //    simpleFillSymbol.Color = enumColors.Next();
            //    uniqueValueRenderer.AddValue(value, strOutputFldName, simpleFillSymbol as ISymbol);
            //}

            ////IFeatureCursor featureCursor = geoFeatureLayer.FeatureClass.Search(null, false);
            ////IFeature feature;
            ////if (featureCursor != null)
            ////{
            ////    IEnumColors enumColors = CreateAlgorithmicColorRamp(8).Colors;
            ////    //int fieldIndex = geoFeatureLayer.FeatureClass.Fields.FindField("continent");
            ////    for (int j = 0; j < uniqueValueRenderer.ValueCount; j++)
            ////    {
            ////        string value = uniqueValueRenderer.get_Value(i);
            ////        uniqueValueRenderer.set_Symbol(value, simpleFillSymbol as ISymbol);

            ////        feature = featureCursor.NextFeature();
            ////        string nameValue = feature.get_Value(intOutputFldIdx).ToString();
            ////        simpleFillSymbol = new SimpleFillSymbolClass();
            ////        simpleFillSymbol.Color = enumColors.Next();
            ////        uniqueValueRenderer.AddValue(nameValue, strOutputFldName, simpleFillSymbol as ISymbol);
            ////    }
            ////}

            //geoFeatureLayer.Renderer = uniqueValueRenderer as IFeatureRenderer;

            //m_pActiveView.Refresh();
            //m_pForm.axTOCControl1.Update();

            MessageBox.Show("Clustering results are stored in the source shapefile");


            pfrmProgress.Close();
        }
        private bool AddEditArea(IServerObject serverObject, string creator, string versionName, int editCount, IEnvelope editZone, bool autoExpandZone = true)
        {
            bool          isOk        = false;
            IFeatureClass editAreasFC = null;

            try
            {
                // Open edit areas feature class in default workspace
                editAreasFC = GetEditAreaFeatureClass(serverObject);

                // Get field indices
                int creatorFIdx      = editAreasFC.FindField(_creatorFName);
                int creationDateFIdx = editAreasFC.FindField(_creationDateFName);
                int lastUpdateFIdx   = editAreasFC.FindField(_lastUpdateFName);
                int editCountFIdx    = editAreasFC.FindField(_editCountFName);
                int versionNameFIdx  = editAreasFC.FindField(_versionNameFName);

                DateTime currentTime = DateTime.Now;

                // Expand zone to make it more visible
                if (autoExpandZone)
                {
                    double expandRatio = (editCount <= 3) ? 1.5 : 1.15;
                    editZone.Expand(expandRatio, expandRatio, true);
                }

                // Check if there's an existing area
                IFeature       curFeature = null;
                IFeatureCursor fCursor    = GetEditAreas(serverObject, versionName);

                if (fCursor != null && (curFeature = fCursor.NextFeature()) != null)
                {
                    // Union the edit zones
                    IPolygon  curZone     = (IPolygon)curFeature.Shape;
                    IGeometry geometryBag = new GeometryBag();
                    geometryBag.SpatialReference = curZone.SpatialReference;
                    IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag;
                    geometryCollection.AddGeometry(curZone);
                    geometryCollection.AddGeometry(editZone);

                    Polygon zoneConstructor      = new Polygon();
                    ITopologicalOperator newZone = (ITopologicalOperator)zoneConstructor;
                    newZone.ConstructUnion((IEnumGeometry)geometryCollection);

                    // Update feature values
                    curFeature.Shape = (IGeometry)newZone;
                    curFeature.Value[lastUpdateFIdx] = currentTime;
                    int curCount = (int)curFeature.Value[editCountFIdx];
                    curFeature.Value[editCountFIdx] = curCount + editCount;

                    // Store feature
                    curFeature.Store();
                    curFeature = null;
                }
                else
                {
                    // Save edit zone to feature class
                    IFeature zoneFeature = editAreasFC.CreateFeature();
                    zoneFeature.Value[creatorFIdx]      = creator;
                    zoneFeature.Value[creationDateFIdx] = currentTime;
                    zoneFeature.Value[lastUpdateFIdx]   = currentTime;
                    zoneFeature.Value[versionNameFIdx]  = versionName;
                    zoneFeature.Value[editCountFIdx]    = editCount;

                    // Set geometry
                    Polygon            editAreaPoly = new Polygon();
                    ISegmentCollection editAreaSeg  = (ISegmentCollection)editAreaPoly;
                    editAreaSeg.SetRectangle(editZone);
                    IZAware polyZAware = editAreaPoly as IZAware;
                    polyZAware.ZAware = false;
                    zoneFeature.Shape = polyZAware as IGeometry;

                    // Store feature
                    zoneFeature.Store();
                    fCursor.Flush();
                    fCursor     = null;
                    zoneFeature = null;
                }

                isOk = true;
            }
            catch (Exception e)
            {
                _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".AddEditArea()",
                                      200, "Error while adding edit are: " + e.ToString());
            }
            finally
            {
                editAreasFC = null;
            }
            return(isOk);
        }
Ejemplo n.º 13
0
        //复制要素
        public static void CopyFeatureAndTran(IFeatureCursor pCursor, IFeatureClass pToFeatureClass, ITransformation inTransformation)
        {
            IFeature       pFeature       = pCursor.NextFeature();
            IFeatureCursor pFeatureCursor = pToFeatureClass.Insert(true);
            int            iCount         = 0;

            while (pFeature != null)
            {
                IFeatureBuffer pFeatureBuffer = pToFeatureClass.CreateFeatureBuffer();

                for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                {
                    string sFieldName = pFeature.Fields.get_Field(i).Name;

                    int iIndex = pFeatureBuffer.Fields.FindField(sFieldName);

                    if ((iIndex > -1) && (pFeatureBuffer.Fields.get_Field(iIndex).Editable == true))
                    {
                        pFeatureBuffer.set_Value(iIndex, pFeature.get_Value(i));
                    }
                }
                if (pEnumFieldError != null)//yjl20110804 add
                {
                    pEnumFieldError.Reset();
                    IFieldError pFieldError = pEnumFieldError.Next();
                    while (pFieldError != null)
                    {
                        int srcIx = pFieldError.FieldIndex;                                             //错误字段的源索引
                        int desIx = pFeatureBuffer.Fields.FindField(pFixedField.get_Field(srcIx).Name); //错误字段的新索引
                        if (desIx == -1)
                        {
                            pFieldError = pEnumFieldError.Next();
                            continue;
                        }
                        IField pFld = pFeatureBuffer.Fields.get_Field(desIx);
                        if ((desIx > -1) && (pFld.Editable == true) && pFld.Type != esriFieldType.esriFieldTypeGeometry)
                        {
                            pFeatureBuffer.set_Value(desIx, pFeature.get_Value(srcIx));
                        }
                        pFieldError = pEnumFieldError.Next();
                    }
                }
                IGeometry    shpTransformed = pFeature.ShapeCopy;
                ITransform2D pTransform2D   = shpTransformed as ITransform2D;
                pTransform2D.Transform(esriTransformDirection.esriTransformForward, inTransformation);
                pFeatureBuffer.Shape = shpTransformed;
                pFeatureCursor.InsertFeature(pFeatureBuffer);
                if (iCount == 500)
                {
                    pFeatureCursor.Flush();
                    iCount = 0;
                }
                iCount++;
                pFeature = pCursor.NextFeature();
            }
            if (iCount > 0)
            {
                pFeatureCursor.Flush();
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
            pFeatureCursor = null;
        }
Ejemplo n.º 14
0
        private void ImportPipeClassToPointPatch(IWorkspace outWorkspace, I3DItem builderItem, IGeometry boundary = null)
        {
            try
            {
                if (builderItem.PointLayerInfo == null)
                    return;
                IWorkspaceEdit workspaceEdit = outWorkspace as IWorkspaceEdit;
                workspaceEdit.StartEditing(false);
                workspaceEdit.StartEditOperation();

                IFeatureCursor pCursor = null;
                if (boundary == null || boundary.IsEmpty == true)
                {
                    pCursor = builderItem.PointLayerInfo.FeatureClass.Search(null, false);
                }
                else
                {
                    ISpatialFilter pFilter = new SpatialFilterClass();
                    pFilter.Geometry = boundary;
                    pFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    pCursor = builderItem.PointLayerInfo.FeatureClass.Search((IQueryFilter)pFilter, false);
                }
                IFeature sFeature = null;
                IFeatureCursor insertCursor = builderItem.PointPatchClass.Insert(true);
                IFeatureBuffer featureBuffer = builderItem.PointPatchClass.CreateFeatureBuffer();
                int count = 0;
                while ((sFeature = pCursor.NextFeature()) != null)
                {
                    try
                    {
                        //开始读取原始数据
                        IGeometry pShape = sFeature.Shape;
                        if (pShape.IsEmpty) continue;
                        IGeometry patchGeometry = CreatePointPatch(sFeature, builderItem);
                        if (patchGeometry == null)
                            continue;
                        featureBuffer.Shape = patchGeometry;
                        featureBuffer.Value[builderItem.IdxPointLinkField] = sFeature.OID;

                        insertCursor.InsertFeature(featureBuffer);
                        count++;
                        if (count >= 1000)
                        {
                            count = 0;
                            insertCursor.Flush();
                            Marshal.ReleaseComObject(insertCursor);
                            insertCursor = builderItem.PointPatchClass.Insert(true);
                            featureBuffer = builderItem.PointPatchClass.CreateFeatureBuffer();
                        }
                    }
                    catch (Exception e)
                    {
                        throw new Exception(string.Format("OBJECTID:{0}\r\n{1}", sFeature.OID, e.Message));
                    }
                }
                insertCursor.Flush();
                Marshal.ReleaseComObject(insertCursor);
                Marshal.ReleaseComObject(pCursor);
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("{0}\r\n{1}", builderItem.PointLayerInfo.AliasName, e.Message));
            }
        }
Ejemplo n.º 15
0
        public void ExtractPointData(string sLineLayer, string sRasterLayer, double dblInterval, string strFileName)
        {
            try
            {
                strSaveFile = strFileName;

                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;


                IFeatureLayer pLineLayer   = FindLayer(sLineLayer) as IFeatureLayer;
                IRasterLayer  pRasterLayer = FindLayer(sRasterLayer) as IRasterLayer;
                //IFeatureLayer pPointLayer = FindLayer(sPointLayer) as IFeatureLayer;
                IFeatureLayer pPointLayer = new FeatureLayerClass();
                pPointLayer.FeatureClass = MakePointFC();
                //pPointLayer.Name = "Points";
                // ArcMap.Document.ActiveView.FocusMap.AddLayer(pPointLayer);


                //get the Workspace from the IDataset interface on the feature class
                IDataset   dataset   = (IDataset)pLineLayer.FeatureClass;
                IWorkspace workspace = dataset.Workspace;
                //Cast for an IWorkspaceEdit
                IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

                //Start an edit session and operation
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();

                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating...", pLineLayer.FeatureClass.FeatureCount(null), 1);
                pProgressDialog.ShowDialog();


                //Set up the Outpoints cursor
                IFeatureCursor pFCurOutPoints = pPointLayer.Search(null, false);
                pFCurOutPoints = pPointLayer.FeatureClass.Insert(true);

                //Set up the LineLayer Cursor
                IFeatureCursor pFCur        = pLineLayer.Search(null, false);
                IFeature       pLineFeature = pFCur.NextFeature();

                IFeatureBuffer pFBuffer = pPointLayer.FeatureClass.CreateFeatureBuffer();



                ICurve pCurve;


                double dlbProcessedLength = 0;
                double dblFCTotalLength   = 0;
                int    p = 0;

                while (pLineFeature != null)
                {
                    pProgressDialog.Description = "Calculating line segment " + p.ToString() + " of: " + pLineLayer.FeatureClass.FeatureCount(null).ToString();

                    //create startpoint
                    pCurve         = pLineFeature.Shape as ICurve;
                    pFBuffer.Shape = pCurve.FromPoint;


                    pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), 0);
                    pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                    pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), pCurve.FromPoint.X);
                    pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), pCurve.FromPoint.Y);

                    pFCurOutPoints.InsertFeature(pFBuffer);

                    double dblTotalDistance = pCurve.Length;
                    dlbProcessedLength = dblInterval;


                    IConstructPoint contructionPoint;
                    IPoint          ppoint;
                    while (dlbProcessedLength <= dblTotalDistance)
                    {
                        contructionPoint = new PointClass();
                        contructionPoint.ConstructAlong(pCurve, esriSegmentExtension.esriNoExtension, dlbProcessedLength, false);
                        ppoint = new PointClass();
                        ppoint = contructionPoint as IPoint;

                        pFBuffer.Shape = ppoint;



                        //dblFCTotalLength += dblInterval;

                        pFBuffer.set_Value(pFBuffer.Fields.FindField("Distance"), Math.Round(dlbProcessedLength, 4));
                        pFBuffer.set_Value(pFBuffer.Fields.FindField("LineOID"), pLineFeature.OID);
                        pFBuffer.set_Value(pFBuffer.Fields.FindField("X"), ppoint.X);
                        pFBuffer.set_Value(pFBuffer.Fields.FindField("Y"), ppoint.Y);

                        pFCurOutPoints.InsertFeature(pFBuffer);
                        dlbProcessedLength += dblInterval;

                        pStepProgressor.Step();
                    }

                    dblFCTotalLength += dblInterval;
                    p++;
                    pLineFeature = pFCur.NextFeature();
                }

                //cleanup
                pFCurOutPoints.Flush();
                pFCur.Flush();

                //Stop editing
                workspaceEdit.StopEditOperation();
                workspaceEdit.StopEditing(true);

                Extract(pRasterLayer, pPointLayer);

                pProgressDialog.HideDialog();
                pmxdoc.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 创建同位流模式分析结果要素
        /// </summary>
        /// <param name="originFeatureClass">输出的矢量要素</param>
        /// <param name="originUIDField">区分要素的唯一字段名</param>
        /// <param name="patternTable">同位流模式表</param>
        /// <param name="out_path">输出要素的路径</param>
        /// <param name="out_name">输出要素的名称</param>
        /// <param name="outObjectClass">输出区域要素类</param>
        /// <param name="outFlowClass">输出流线要素类</param>
        public void CreatePatternFeatures(IFeatureClass originFeatureClass,
                                          string originUIDField,
                                          IFeatureClass destFeatureClass,
                                          string destUIDField,
                                          DataTable patternTable,
                                          string out_path,
                                          string out_name,
                                          ref IFeatureClass outObjectClass,
                                          ref IFeatureClass outFlowClass,
                                          ref string message)
        {
            string parent_path         = System.IO.Path.GetDirectoryName(out_path);
            string featuredataset_name = "";
            string extension           = System.IO.Path.GetExtension(parent_path);

            if (extension == ".gdb" || extension == ".mdb")
            {
                featuredataset_name = System.IO.Path.GetFileName(out_path);
                out_path            = parent_path;
            }

            var    originSpatialRef = ((IGeoDataset)originFeatureClass).SpatialReference;
            var    destSpatialRef   = ((IGeoDataset)destFeatureClass).SpatialReference;
            IClone comparison       = originSpatialRef as IClone;

            if (!comparison.IsEqual((IClone)destSpatialRef))
            {
                message = "Different Spatial Reference in Origin and Destination FeatureClass.";
                return;
            }

            // 获取 UID字段-要素 字典
            var originPolygonDict = GetUIDPolygonDict(originFeatureClass, originUIDField);
            Dictionary <string, IPolygon> destPolygonDict = null;

            if (originFeatureClass == destFeatureClass)
            {
                destPolygonDict = originPolygonDict;
            }
            else
            {
                destPolygonDict = GetUIDPolygonDict(destFeatureClass, destUIDField);
            }


            // 字段的最大长度
            int d_length   = patternTable.AsEnumerable().Max(r => ((string)r["Dests"]).Length);
            int o_length   = patternTable.AsEnumerable().Max(r => ((string)r["Origins"]).Length);
            int max_length = d_length;

            if (o_length > d_length)
            {
                max_length = o_length;
            }

            var dataMangementTools = new DataManagementTools();

            // 合并后的区域要素
            outObjectClass = dataMangementTools.CreateFeatureClass(
                out_path, out_name + "_OBJ", featuredataset_name, originFeatureClass.ShapeType, originSpatialRef);
            // 同位流要素
            outFlowClass = dataMangementTools.CreateFeatureClass(
                out_path, out_name + "_FLOW", featuredataset_name, esriGeometryType.esriGeometryPolyline, originSpatialRef);

            // 复制合并前要素的字段
            var pID         = dataMangementTools.AddField((ITable)outObjectClass, "PID", esriFieldType.esriFieldTypeSmallInteger, true);
            var pType       = dataMangementTools.AddField((ITable)outObjectClass, "PTYPE", esriFieldType.esriFieldTypeString, true);
            var pGUID       = dataMangementTools.AddField((ITable)outObjectClass, "PGUID", esriFieldType.esriFieldTypeString, true, max_length);
            var pGCount     = dataMangementTools.AddField((ITable)outObjectClass, "PGCOUNT", esriFieldType.esriFieldTypeString, true, max_length);
            int pID_idx     = outObjectClass.FindField(pID);
            int pType_idx   = outObjectClass.FindField(pType);
            int pZUID_idx   = outObjectClass.FindField(pGUID);
            int pZCount_idx = outObjectClass.FindField(pGCount);

            // 复制同位流字段
            var flowFieldDict = dataMangementTools.CopyFields(patternTable, (ITable)outFlowClass, max_length);

            IFeatureBuffer outObjectBuffer = null;
            IFeatureCursor outObjectCursor = outObjectClass.Insert(true);

            IFeatureBuffer outFlowBuffer = null;
            IFeatureCursor outFlowCursor = outFlowClass.Insert(true);

            AddStepProgressor(patternTable.Rows.Count, "Creating spatiotemporal self-co-location flow features . . . ");
            for (int i = 0; i < patternTable.Rows.Count; i++)
            {
                if (!ContinueStepProgressor(new object[] { outObjectCursor, outFlowCursor }))
                {
                    return;
                }

                var dataRow = patternTable.Rows[i];
                var rowPID  = (int)dataRow["PID"];

                string[] originStrArr  = ((string)dataRow["Origins"]).Split(';');
                IPolygon originPolygon = DissolvePolygon(originSpatialRef, originPolygonDict, originStrArr);
                outObjectBuffer                    = outObjectClass.CreateFeatureBuffer();
                outObjectBuffer.Shape              = originPolygon;
                outObjectBuffer.Value[pID_idx]     = rowPID;
                outObjectBuffer.Value[pType_idx]   = "Origin";
                outObjectBuffer.Value[pZUID_idx]   = string.Join(";", originStrArr);
                outObjectBuffer.Value[pZCount_idx] = originStrArr.Length;
                outObjectCursor.InsertFeature(outObjectBuffer);

                IPoint originPoint = ((IArea)originPolygon).Centroid;

                string[] destStrArr  = ((string)dataRow["Dests"]).Split(';');
                IPolygon destPolygon = DissolvePolygon(destSpatialRef, destPolygonDict, destStrArr);
                outObjectBuffer                    = outObjectClass.CreateFeatureBuffer();
                outObjectBuffer.Shape              = destPolygon;
                outObjectBuffer.Value[pID_idx]     = rowPID;
                outObjectBuffer.Value[pType_idx]   = "Destination";
                outObjectBuffer.Value[pZUID_idx]   = string.Join(";", destStrArr);
                outObjectBuffer.Value[pZCount_idx] = destStrArr.Length;
                outObjectCursor.InsertFeature(outObjectBuffer);

                IPoint destPoint = ((IArea)destPolygon).Centroid;

                // 创建同位流要素
                outFlowBuffer       = outFlowClass.CreateFeatureBuffer();
                outFlowBuffer.Shape = CreateCirculeArc(originPoint, destPoint, 0.3);

                foreach (var item in flowFieldDict)
                {
                    outFlowBuffer.Value[item.Value] = dataRow[item.Key];
                }

                outFlowCursor.InsertFeature(outFlowBuffer);
            } // for (int i = 0; i < patternTable.Rows.Count; i++)
            outObjectCursor.Flush();
            outFlowCursor.Flush();

            Marshal.ReleaseComObject(outObjectCursor);
            Marshal.ReleaseComObject(outFlowCursor);
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        /// <summary>
        /// 构造小区覆盖网格
        /// </summary>
        /// <param name="cellname"></param>
        /// <param name="enodeb"></param>
        /// <param name="ci"></param>
        public bool constuctCellGrids(string cellname, int enodeb, int ci)
        {
            DataTable gridTable = new DataTable();
            Hashtable ht        = new Hashtable();

            ht["eNodeB"] = enodeb;
            ht["CI"]     = ci;
            gridTable    = IbatisHelper.ExecuteQueryForDataTable("GetSpecifiedCellGrids", ht);
            if (gridTable.Rows.Count < 1)
            {
                return(false);
            }

            IDataset       dataset       = (IDataset)pFeatureLayer.FeatureClass;
            IWorkspace     workspace     = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            int    gxid, gyid, level;
            double x1, y1, x2, y2, z;
            double recePower, pathLoss;
            double gheight = GridHelper.getInstance().getGHeight();
            //循环添加
            int cnt = 0;
            //初始化进度信息
            LoadInfo loadInfo = new LoadInfo();

            loadInfo.count = gridTable.Rows.Count;
            loadInfo.loadCreate();

            foreach (DataRow dataRow in gridTable.Rows)
            {
                if (cnt++ % 1000 == 0)
                {
                    loadInfo.cnt = cnt;
                    loadInfo.loadUpdate();
                    Console.WriteLine("已计算  " + cnt + "/" + gridTable.Rows.Count);
                }
                gxid  = int.Parse(dataRow["Gxid"].ToString());
                gyid  = int.Parse(dataRow["Gyid"].ToString());
                level = int.Parse(dataRow["Level"].ToString());

                Geometric.Point p   = GridHelper.getInstance().GridToGeo(gxid, gyid);
                double          lon = p.X;
                double          lat = p.Y;

                //if (!(float.TryParse(dataRow["MinX"].ToString(), out x1) && float.TryParse(dataRow["MinY"].ToString(), out y1) && float.TryParse(dataRow["MaxX"].ToString(), out x2) && float.TryParse(dataRow["MaxY"].ToString(), out y2) && float.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower) && float.TryParse(dataRow["PathLoss"].ToString(), out pathLoss)))
                //    continue;

                if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) && double.TryParse(dataRow["MinY"].ToString(), out y1)))
                {
                    continue;
                }
                if (!(double.TryParse(dataRow["MaxX"].ToString(), out x2) && double.TryParse(dataRow["MaxY"].ToString(), out y2)))
                {
                    continue;
                }
                if (!(double.TryParse(dataRow["ReceivedPowerdbm"].ToString(), out recePower) && double.TryParse(dataRow["PathLoss"].ToString(), out pathLoss)))
                {
                    continue;
                }
                z = gheight * level;

                IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z);
                IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z);
                IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z);
                IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z);

                IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD });
                GeometryUtilities.MakeZAware(pGeometryColl as IGeometry);

                pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
                pFeatureBuffer.Shape = pGeometryColl as IGeometry;
                pFeatureBuffer.set_Value(this.GXIDIndex, gxid);
                pFeatureBuffer.set_Value(this.GYIDIndex, gyid);
                pFeatureBuffer.set_Value(this.eNodeBIndex, enodeb);
                pFeatureBuffer.set_Value(this.CIIndex, ci);
                pFeatureBuffer.set_Value(this.cellNameIndex, cellname);
                pFeatureBuffer.set_Value(this.LevelIndex, level);
                pFeatureBuffer.set_Value(this.LongitudeIndex, lon);
                pFeatureBuffer.set_Value(this.LatitudeIndex, lat);


                if (recePower > -41)
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, -41);
                }
                //else if(recePower < -110)
                //    pFeatureBuffer.set_Value(this.RecePowerIndex, -110);
                else
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, recePower);
                }
                pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss);
                pFeatureCursor.InsertFeature(pFeatureBuffer);

                //释放AO对象
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureBuffer);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pGeometryColl);
            }

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;

            pFeatureClassManage.UpdateExtent();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureClassManage);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);

            //更新完成进度信息
            loadInfo.cnt = cnt;
            loadInfo.loadUpdate();
            //GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 构造 TIN
        /// </summary>
        public bool constuctTIN1()
        {
            double minX = 0, minY = 0, maxX = 0, maxY = 0;

            InternalInterference.Grid.GridHelper.getInstance().getMinXY(ref minX, ref minY);
            InternalInterference.Grid.GridHelper.getInstance().getMaxXY(ref maxX, ref maxY);

            Hashtable ht = new Hashtable();

            ht["minX"] = minX;
            ht["maxX"] = maxX;
            ht["minY"] = minY;
            ht["maxY"] = maxY;
            DataTable gridTable = IbatisHelper.ExecuteQueryForDataTable("GetTINVertexByArea", ht);

            if (gridTable.Rows.Count < 1)
            {
                return(false);
            }

            IDataset       dataset       = (IDataset)pFeatureLayer.FeatureClass;
            IWorkspace     workspace     = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            float         x, y, z;
            List <IPoint> pts = new List <IPoint>();
            //循环添加
            int cnt = 0;
            //初始化进度信息
            LoadInfo loadInfo = new LoadInfo();

            loadInfo.count = gridTable.Rows.Count;
            loadInfo.loadCreate();
            //循环添加
            foreach (DataRow dataRow in gridTable.Rows)
            {
                if (cnt++ % 1000 == 0)
                {
                    loadInfo.cnt = cnt;
                    loadInfo.loadUpdate();
                    Console.WriteLine("已计算  " + cnt + "/" + gridTable.Rows.Count);
                }
                if (!(float.TryParse(dataRow["VertexX"].ToString(), out x) && float.TryParse(dataRow["VertexY"].ToString(), out y) && float.TryParse(dataRow["VertexHeight"].ToString(), out z)))
                {
                    continue;
                }

                IPoint pointA = GeometryUtilities.ConstructPoint3D(x, y, z);
                pts.Add(pointA);

                if (pts.Count >= 3)
                {
                    IGeometryCollection pGeometryColl = GeometryUtilities.ConstructMultiPath(pts);
                    pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
                    pFeatureBuffer.Shape = pGeometryColl as IGeometry;
                    pFeatureCursor.InsertFeature(pFeatureBuffer);

                    pts.Clear();
                }
            }

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;

            pFeatureClassManage.UpdateExtent();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureClassManage);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);

            //更新完成进度信息
            loadInfo.cnt = cnt;
            loadInfo.loadUpdate();
            //GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            return(true);
        }
        /// <summary>
        /// 区域覆盖
        /// </summary>
        /// <param name="mingxid"></param>
        /// <param name="mingyid"></param>
        /// <param name="maxgxid"></param>
        /// <param name="maxgyid"></param>
        public bool constuctAreaGrids(int mingxid, int mingyid, int maxgxid, int maxgyid, string layerName)
        {
            DataTable gridTable = new DataTable();
            Hashtable ht        = new Hashtable();

            ht["MinGXID"] = mingxid;
            ht["MaxGXID"] = maxgxid;
            ht["MinGYID"] = mingyid;
            ht["MaxGYID"] = maxgyid;
            gridTable     = IbatisHelper.ExecuteQueryForDataTable("GetSpecifiedAreaGrids", ht);
            if (gridTable.Rows.Count < 1)
            {
                return(false);
            }

            /*
             *<select id="GetSpecifiedAreaGrids" parameterClass="Hashtable">
             *          select a.GXID, a.GYID, a.eNodeB, a.CI, d.MinLong, d.MinLat, d.MaxLong, d.MaxLat, a.ReceivedPowerdbm, a.PathLoss from tbGridPathloss a ,
             *          (select c.GXID, c.GYID, c.eNodeB, c.CI, max(c.ReceivedPowerdbm) ReceivedPowerdbm from tbGridPathloss c where c.GXID between '$MinGXID$' and '$MaxGXID$' and c.GYID between '$MinGYID$' and '$MaxGYID$'  group by c.gxid, c.gyid, c.eNodeB, c.ci having max(c.ReceivedPowerdbm) > -130 ) b,
             *          tbGridDem d
             *          where a.gxid = b.gxid and a.gyid = b.gyid and a.eNodeB = b.eNodeB and a.ci = b.ci and a.gxid = d.gxid and a.gyid = d.gyid
             *      </select>
             */
            IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();
            IFeatureClass     fclass           = featureWorkspace.OpenFeatureClass(layerName);

            //IFeatureLayer flayer = new FeatureLayer();
            pFeatureLayer.FeatureClass = pFeatureClass;

            //IFeatureLayer flayer = GISMapApplication.Instance.GetLayer(LayerNames.AreaCoverGrids) as IFeatureLayer;
            //FeatureUtilities.DeleteFeatureLayerFeatrues(flayer);

            //IFeatureClass fclass = flayer.FeatureClass;

            IDataset   dataset   = (IDataset)fclass;
            IWorkspace workspace = dataset.Workspace;
            //Cast for an IWorkspaceEdit
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            //start an edit session and operation
            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureCursor pFeatureCursor = fclass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            //int gxid, gyid, lac, ci;
            //float x1, y1, x2, y2;
            //float recePower, pathLoss;
            int    lac, ci, gxid, gyid, level;
            double x1, y1, x2, y2, z;
            double recePower, pathLoss;
            double gbaseheight = GridHelper.getInstance().getGBaseHeight();
            double gheight     = GridHelper.getInstance().getGHeight();

            //循环添加
            int cnt = 0;

            //循环添加
            foreach (DataRow dataRow in gridTable.Rows)
            {
                if (cnt++ % 1000 == 0)
                {
                    Console.WriteLine("已计算  " + cnt + "/" + gridTable.Rows.Count);
                }
                gxid  = int.Parse(dataRow["GXID"].ToString());
                gyid  = int.Parse(dataRow["GYID"].ToString());
                level = int.Parse(dataRow["Level"].ToString());
                Geometric.Point p   = GridHelper.getInstance().GridToGeo(gxid, gyid);
                double          lon = p.X;
                double          lat = p.Y;
                //lac = int.Parse(dataRow["eNodeB"].ToString());
                //ci = int.Parse(dataRow["CI"].ToString());
                recePower = double.Parse(dataRow["ReceivedPowerdbm"].ToString());
                pathLoss  = double.Parse(dataRow["PathLoss"].ToString());

                if (!(double.TryParse(dataRow["MinX"].ToString(), out x1) &&
                      double.TryParse(dataRow["MinY"].ToString(), out y1) &&
                      double.TryParse(dataRow["MaxX"].ToString(), out x2) &&
                      double.TryParse(dataRow["MaxY"].ToString(), out y2)))
                {
                    continue;
                }

                z = gheight * (level - 1) + gbaseheight;

                IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z);
                IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z);
                IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z);
                IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z);

                IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD });
                GeometryUtilities.MakeZAware(pGeometryColl as IGeometry);

                pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
                pFeatureBuffer.Shape = pGeometryColl as IGeometry;
                pFeatureBuffer.set_Value(this.GXIDIndex, gxid);
                pFeatureBuffer.set_Value(this.GYIDIndex, gyid);
                pFeatureBuffer.set_Value(this.eNodeBIndex, 0);
                pFeatureBuffer.set_Value(this.CIIndex, 0);
                pFeatureBuffer.set_Value(this.cellNameIndex, "");
                pFeatureBuffer.set_Value(this.LongitudeIndex, lon);
                pFeatureBuffer.set_Value(this.LatitudeIndex, lat);
                pFeatureBuffer.set_Value(this.LevelIndex, level);
                if (recePower > -41)
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, -41);
                }
                //else if(recePower < -110)
                //    pFeatureBuffer.set_Value(this.RecePowerIndex, -110);
                else
                {
                    pFeatureBuffer.set_Value(this.RecePowerIndex, recePower);
                }
                pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss);
                pFeatureCursor.InsertFeature(pFeatureBuffer);
            }

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;

            pFeatureClassManage.UpdateExtent();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureClassManage);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(dataset);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspace);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);

            //GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            return(true);
        }
Ejemplo n.º 20
0
        public void CopyFeatures(LoadTarget target)
        {
            IWorkspaceFactory sourceWsf;

            if (System.IO.Path.GetExtension(target.In_Directory).ToUpper().Equals(".GDB"))
            {
                sourceWsf = new FileGDBWorkspaceFactoryClass();
            }
            else
            {
                sourceWsf = new ShapefileWorkspaceFactoryClass();
            }
            IFeatureWorkspace sourceFeatWs       = sourceWsf.OpenFromFile(target.In_Directory, 0) as IFeatureWorkspace;
            IFeatureClass     sourceFeatureClass = sourceFeatWs.OpenFeatureClass(target.In_FileName);

            IWorkspaceFactory targetWsf;

            if (System.IO.Path.GetExtension(target.Out_Directory).ToUpper().Equals(".GDB"))
            {
                targetWsf = new FileGDBWorkspaceFactoryClass();
            }
            else
            {
                targetWsf = new ShapefileWorkspaceFactoryClass();
            }

            IWorkspace targetWs = targetWsf.OpenFromFile(target.Out_Directory, 0) as IWorkspace;

            string targetFileName;

            if (System.IO.Path.GetExtension(target.Out_Directory).ToUpper().Equals(".GDB"))
            {
                targetFileName = LoadHelper.GetNameGDB(target.Out_Directory, target.Out_FileName);
            }
            else
            {
                targetFileName = LoadHelper.GetNameShapeFile(target.Out_Directory, target.Out_FileName);
            }

            IFeatureWorkspace        targetFeatWs            = targetWs as IFeatureWorkspace;
            IFeatureClassDescription featureClassDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription  objectClassDescription  = featureClassDescription as IObjectClassDescription;

            IFields         pFields         = sourceFeatureClass.Fields;
            IFieldChecker   pFieldChecker   = new FieldCheckerClass();
            IEnumFieldError pEnumFieldError = null;
            IFields         vFields         = null;

            pFieldChecker.ValidateWorkspace = targetWs as IWorkspace;
            pFieldChecker.Validate(pFields, out pEnumFieldError, out vFields);

            IFeatureClass sdeFeatureClass = null;

            if (sdeFeatureClass == null)
            {
                sdeFeatureClass = targetFeatWs.CreateFeatureClass(targetFileName, vFields,
                                                                  objectClassDescription.InstanceCLSID, objectClassDescription.ClassExtensionCLSID,
                                                                  sourceFeatureClass.FeatureType, sourceFeatureClass.ShapeFieldName, "");
                IFeatureCursor featureCursor    = sourceFeatureClass.Search(null, true);
                IFeature       feature          = featureCursor.NextFeature();
                IFeatureCursor sdeFeatureCursor = sdeFeatureClass.Insert(true);
                IFeatureBuffer sdeFeatureBuffer;
                IQueryFilter   qf = new QueryFilterClass();
                target.Size = sourceFeatureClass.FeatureCount(qf);
                while (feature != null)
                {
                    sdeFeatureBuffer = sdeFeatureClass.CreateFeatureBuffer();
                    IField  shpField  = new FieldClass();
                    IFields shpFields = feature.Fields;
                    for (int i = 0; i < shpFields.FieldCount; i++)
                    {
                        shpField = shpFields.get_Field(i);
                        if (shpField.Name.ToLower().Contains("area") || shpField.Name.ToLower().Contains("leng") || shpField.Name.ToLower().Contains("fid") || shpField.Name.ToLower().Contains("objectid"))
                        {
                            continue;
                        }
                        int index = sdeFeatureBuffer.Fields.FindField(shpField.Name);
                        if (index != -1)
                        {
                            sdeFeatureBuffer.set_Value(index, feature.get_Value(i));
                        }
                    }
                    sdeFeatureCursor.InsertFeature(sdeFeatureBuffer);
                    sdeFeatureCursor.Flush();
                    feature = featureCursor.NextFeature();
                    target.Progress++;
                }
                featureCursor.Flush();
                target.IsFinished = true;
                target.IsBusy     = false;
            }
        }
Ejemplo n.º 21
0
        //不剪裁输出
        private void notcutExport(IFeatureCursor pCursor, IFeatureClass pToFeatureClass, int featurecount, out Exception error)
        {
            IFeature       pFeature       = pCursor.NextFeature();
            IFeatureCursor pFeatureCursor = pToFeatureClass.Insert(true);

            error = null;
            int iCount = 0;

            while (pFeature != null)
            {
                IFeatureBuffer pFeatureBuffer = pToFeatureClass.CreateFeatureBuffer();

                for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                {
                    string sFieldName = pFeature.Fields.get_Field(i).Name;

                    int iIndex = pFeatureBuffer.Fields.FindField(sFieldName);
                    try
                    {
                        if ((iIndex > -1) && (pFeatureBuffer.Fields.get_Field(iIndex).Editable == true))
                        {
                            pFeatureBuffer.set_Value(iIndex, pFeature.get_Value(i));
                        }
                    }
                    catch
                    { }
                }
                // 写入入库日期和入库人员
                int DateIndex  = pFeatureBuffer.Fields.FindField("PutInDate");
                int UserIndex  = pFeatureBuffer.Fields.FindField("USERNAME");
                int CheckIndex = pFeatureBuffer.Fields.FindField("CheckState");
                try
                {
                    if (DateIndex > -1 && UserIndex > -1 && CheckIndex > -1)
                    {
                        pFeatureBuffer.set_Value(DateIndex, DateTime.Today.ToString("yyyy - MM - dd"));
                        pFeatureBuffer.set_Value(CheckIndex, "未审核");
                        if (Plugin.LogTable.user != "")
                        {
                            pFeatureBuffer.set_Value(UserIndex, Plugin.LogTable.user);
                        }
                    }
                }
                catch {}

                try
                {
                    pFeatureBuffer.Shape = pFeature.ShapeCopy;
                    pFeatureCursor.InsertFeature(pFeatureBuffer);
                }
                catch (Exception ex)
                {
                    error = ex;
                }
                if (iCount == 500)
                {
                    pFeatureCursor.Flush();
                    iCount = 0;
                }
                iCount++;
                pFeature = pCursor.NextFeature();
            }
            if (iCount > 0)
            {
                pFeatureCursor.Flush();
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
            pFeatureCursor = null;
        }
Ejemplo n.º 22
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            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;

            int nFeature = m_pFClass.FeatureCount(null);

            IFeatureCursor pFCursor = m_pFClass.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 = m_pFClass.FindField(strVarNM1);
            int    intVarIdx2 = m_pFClass.FindField(strVarNM2);
            int    intFIDIdx  = m_pFClass.FindField(m_pFClass.OIDFieldName);

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

            int[] arrFID = new int[nFeature];

            int i = 0;

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

            pFCursor.Flush();

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

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

            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_LARRY.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_neighbor.R')");
            pEngine.Evaluate("source('" + pathr + "/ESDA_LEE/AllFunctions_SASbi.R')");

            //Get the file path and name to create spatial weight matrix
            string strNameR = m_pSnippet.FilePathinRfromLayer(m_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, queen=FALSE)");
            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 strNonZero = null;

            if (chkDiagZero.Checked)
            {
                strNonZero = "FALSE";
            }
            else
            {
                strNonZero = "TRUE";
            }

            string[] strSPQuadrants = null;

            double[]      adblVar1 = null;
            double[]      adblVar2 = null;
            NumericVector vecCoeff = null;

            if (cboMeasure.Text == "Lee's L")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.quadrant.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', diag.zero = " + strNonZero + ")");
                strSPQuadrants = pEngine.Evaluate("as.character(sample.result$quad)").AsCharacter().ToArray();
                if (chkScatterplot.Checked)
                {
                    adblVar1 = pEngine.Evaluate("as.numeric(sample.result$v.z.x)").AsNumeric().ToArray();
                    adblVar2 = pEngine.Evaluate("as.numeric(sample.result$v.z.y)").AsNumeric().ToArray();
                    vecCoeff = pEngine.Evaluate("lm(sample.result$v.z.y~sample.result$v.z.x)$coefficients").AsNumeric();
                }
            }
            else if (cboMeasure.Text == "Local Pearson")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.quadrant.pearson(sample.v1, sample.v2, 1:length(sample.nb))");
                strSPQuadrants = pEngine.Evaluate("as.character(sample.result$quad)").AsCharacter().ToArray();
                if (chkScatterplot.Checked)
                {
                    adblVar1 = pEngine.Evaluate("as.numeric(sample.result$z.x)").AsNumeric().ToArray();
                    adblVar2 = pEngine.Evaluate("as.numeric(sample.result$z.y)").AsNumeric().ToArray();
                    vecCoeff = pEngine.Evaluate("lm(sample.result$z.y~sample.result$z.x)$coefficients").AsNumeric();
                }
            }

            //Save Output on SHP
            //Add Target fields to store results in the shapefile // Keep loop
            for (int j = 0; j < 1; j++)
            {
                string strfldName = lvFields.Items[j].SubItems[1].Text;
                if (m_pFClass.FindField(strfldName) == -1)
                {
                    IField     newField  = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)newField;
                    fieldEdit.Name_2 = strfldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    m_pFClass.AddField(newField);
                }
            }

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

            string strSpQuadFldName = lvFields.Items[0].SubItems[1].Text;
            int    intSpQuadFldIdx  = m_pFClass.FindField(strSpQuadFldName);

            int featureIdx = 0;

            while (pFeature != null)
            {
                pFeature.set_Value(intSpQuadFldIdx, strSPQuadrants[featureIdx]);

                pFCursor.UpdateFeature(pFeature);

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

            if (chkMap.Checked)
            {
                ITable pTable = (ITable)m_pFClass;

                IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                pUniqueValueRenderer.FieldCount = 1;
                pUniqueValueRenderer.set_Field(0, strSpQuadFldName);

                if (cboMaptype.Text == "choropleth map")
                {
                    ISimpleFillSymbol pSymbol;
                    IQueryFilter      pQFilter = new QueryFilterClass();
                    int    intTotalCount       = 0;
                    string strLabel            = null;

                    for (int j = 0; j < 4; j++)
                    {
                        pSymbol       = new SimpleFillSymbolClass();
                        pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                        pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B);

                        pQFilter.WhereClause = strSpQuadFldName + " = '" + m_pQuadrantSymbols[j].Value + "'";

                        intTotalCount = pTable.RowCount(pQFilter);

                        strLabel = m_pQuadrantSymbols[j].Label + " (" + intTotalCount.ToString() + ")";
                        pUniqueValueRenderer.AddValue(m_pQuadrantSymbols[j].Value, null, (ISymbol)pSymbol);
                        pUniqueValueRenderer.set_Label(m_pQuadrantSymbols[j].Value, strLabel);
                    }
                    pUniqueValueRenderer.UseDefaultSymbol = false;
                }
                else if (cboMaptype.Text == "point map")
                {
                    ICharacterMarkerSymbol pSymbol;
                    stdole.IFontDisp       stdFontCls = ((stdole.IFontDisp)(new stdole.StdFont()));
                    stdFontCls.Name = "ESRI NIMA VMAP1&2 PT";
                    stdFontCls.Size = 10;

                    IQueryFilter pQFilter      = new QueryFilterClass();
                    int          intTotalCount = 0;
                    string       strLabel      = null;

                    for (int j = 0; j < 4; j++)
                    {
                        pSymbol = new CharacterMarkerSymbolClass();
                        pSymbol.CharacterIndex = 248;
                        //pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B);
                        pSymbol.Size = 10;
                        pSymbol.Font = stdFontCls;

                        pSymbol.Angle = m_pQuadrantSymbols[j].Angle;

                        //Create a Fill Symbol for the Mask
                        ISimpleFillSymbol smpFill = new SimpleFillSymbol();
                        smpFill.Color = m_pSnippet.getRGB(0, 0, 0);
                        smpFill.Style = esriSimpleFillStyle.esriSFSSolid;
                        //Create a MultiLayerMarkerSymbol
                        IMultiLayerMarkerSymbol multiLyrMrk = new MultiLayerMarkerSymbol();
                        //Add the simple marker to the MultiLayer
                        multiLyrMrk.AddLayer(pSymbol);
                        //Create a Mask for the MultiLayerMarkerSymbol
                        IMask mrkMask = (IMask)multiLyrMrk;
                        mrkMask.MaskSymbol = smpFill;
                        mrkMask.MaskStyle  = esriMaskStyle.esriMSHalo;
                        mrkMask.MaskSize   = 0.5;

                        pQFilter.WhereClause = strSpQuadFldName + " = '" + m_pQuadrantSymbols[j].Value + "'";

                        intTotalCount = pTable.RowCount(pQFilter);

                        strLabel = m_pQuadrantSymbols[j].Label + " (" + intTotalCount.ToString() + ")";
                        pUniqueValueRenderer.AddValue(m_pQuadrantSymbols[j].Value, null, (ISymbol)multiLyrMrk);
                        pUniqueValueRenderer.set_Label(m_pQuadrantSymbols[j].Value, strLabel);
                    }
                    pUniqueValueRenderer.UseDefaultSymbol = false;
                }
                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = m_pFClass;
                pNewFLayer.Name         = "Bivariate Spatial Quadrants";
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                m_pActiveView.FocusMap.AddLayer(pGFLayer);
                m_pActiveView.Refresh();
                m_pForm.axTOCControl1.Update();
            }

            if (chkScatterplot.Checked)
            {
                frmMScatterResults pfrmMScatterResult = new frmMScatterResults();
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsStartedFromZero = false;
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsMarginVisible   = true;

                pfrmMScatterResult.pChart.ChartAreas[0].AxisY.IsStartedFromZero = false;

                pfrmMScatterResult.Text = cboMeasure.Text + " Scatter Plot of " + m_pFLayer.Name;
                pfrmMScatterResult.pChart.Series.Clear();
                System.Drawing.Color pMarkerColor = System.Drawing.Color.Blue;
                var seriesPts = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name              = "Points",
                    Color             = pMarkerColor,
                    BorderColor       = pMarkerColor,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                    MarkerStyle       = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle
                };

                pfrmMScatterResult.pChart.Series.Add(seriesPts);

                for (int j = 0; j < adblVar1.Length; j++)
                {
                    seriesPts.Points.AddXY(adblVar1[j], adblVar2[j]);
                }

                var VLine = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name            = "VLine",
                    Color           = System.Drawing.Color.Black,
                    BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash,
                    //BorderColor = System.Drawing.Color.Black,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                };
                pfrmMScatterResult.pChart.Series.Add(VLine);

                VLine.Points.AddXY(adblVar1.Average(), adblVar2.Min());
                VLine.Points.AddXY(adblVar1.Average(), adblVar2.Max());

                var HLine = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name            = "HLine",
                    Color           = System.Drawing.Color.Black,
                    BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash,
                    //BorderColor = System.Drawing.Color.Black,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                };
                pfrmMScatterResult.pChart.Series.Add(HLine);

                HLine.Points.AddXY(adblVar1.Min(), adblVar2.Average());
                HLine.Points.AddXY(adblVar1.Max(), adblVar2.Average());

                var seriesLine = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name  = "RegLine",
                    Color = System.Drawing.Color.Red,
                    //BorderColor = System.Drawing.Color.Black,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                };

                pfrmMScatterResult.pChart.Series.Add(seriesLine);

                seriesLine.Points.AddXY(adblVar1.Min(), adblVar1.Min() * vecCoeff[1] + vecCoeff[0]);
                seriesLine.Points.AddXY(adblVar1.Max(), adblVar1.Max() * vecCoeff[1] + vecCoeff[0]);

                if (cboMeasure.Text == "Local Pearson")
                {
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.Title = "z-transformed " + cboFldnm1.Text;
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisY.Title = "z-transformed " + cboFldnm2.Text;
                    pfrmMScatterResult.lblRegression.Text = string.Empty;
                }
                else
                {
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.Title = "z-transformed SMA of " + cboFldnm1.Text;
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisY.Title = "z-transformed SMA of " + cboFldnm2.Text;
                    pfrmMScatterResult.lblRegression.Text = string.Empty;
                }

                pfrmMScatterResult.m_pForm       = m_pForm;
                pfrmMScatterResult.m_pFLayer     = m_pFLayer;
                pfrmMScatterResult.m_pActiveView = m_pActiveView;
                pfrmMScatterResult.arrVar        = adblVar1;
                pfrmMScatterResult.arrFID        = arrFID;
                pfrmMScatterResult.strFIDNM      = m_pFClass.OIDFieldName;
                //pfrmMScatterResult.arrWeightVar = arrWeightVar;
                pfrmMScatterResult.pMakerColor = pMarkerColor;
                pfrmMScatterResult.strVarNM    = cboFldnm1.Text;

                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false;
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.CustomLabels.Clear();
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.TickMarkStyle = System.Windows.Forms.DataVisualization.Charting.TickMarkStyle.None;
                //pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.Interval = 1;
                //pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.IntervalOffset = -2;

                int intMin = Convert.ToInt32(Math.Floor(adblVar1.Min()));
                int intMax = Convert.ToInt32(Math.Ceiling(adblVar1.Max()));
                for (int n = intMin; n < intMax; n++)
                {
                    System.Windows.Forms.DataVisualization.Charting.CustomLabel pcutsomLabel = new System.Windows.Forms.DataVisualization.Charting.CustomLabel();
                    pcutsomLabel.FromPosition = n - 0.5;
                    pcutsomLabel.ToPosition   = n + 0.5;
                    pcutsomLabel.Text         = n.ToString();
                    pfrmMScatterResult.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel);
                }

                pfrmMScatterResult.Show();
            }
            pfrmProgress.Close();
        }
Ejemplo n.º 23
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            ProgressDialog pd = null;

            try
            {
                ItemClass item = this.comboBox1.SelectedItem as ItemClass;
                if (item == null)
                {
                    MessageBox.Show("请先选择要更新的图层", "提示");
                    return;
                }
                ItemClass fd_item = this.comboBox2.SelectedItem as ItemClass;
                if (fd_item == null)
                {
                    MessageBox.Show("请先选择要更新的字段", "提示");
                    return;
                }
                int totalWidth = 0;
                int.TryParse(this.fd_totalWidth.Text, out totalWidth);
                //
                ILayer        layer     = item.Value as ILayer;
                IFeatureLayer featLayer = layer as IFeatureLayer;
                IFeatureClass fc        = featLayer.FeatureClass;
                //
                string fdName = fd_item.Caption;
                //
                int fCount = fc.FeatureCount(null);
                if (fCount > 0)
                {
                    pd         = new ProgressDialog();
                    pd.Text    = "进度";
                    pd.Message = "自动补零前缀长度中......";
                    pd.Minimum = 0;
                    pd.Maximum = fCount;
                    pd.Show(this);
                    //
                    Application.DoEvents();
                    //
                    IFeatureCursor pcursor = fc.Update(null, false);
                    IFeature       pf      = pcursor.NextFeature();
                    int            index   = fc.FindField(fdName);
                    //
                    int n = 0;
                    while (pf != null)
                    {
                        n = n + 1;
                        if (n % 200 == 0)
                        {
                            pd.Value   = n;
                            pd.Message = "自动补零前缀长度中......" + pd.Value.ToString() + "/" + pd.Maximum.ToString();
                            Application.DoEvents();
                            pcursor.Flush();
                        }
                        object v = pf.get_Value(index);
                        if (v != null)
                        {
                            string prex = v.ToString();
                            if (cb_IsPreAdd0.Checked == true)
                            {   //是向前补0     10->00010
                                prex = prex.PadLeft(totalWidth, '0');
                            }
                            else
                            {   //是向后补0     10->10000
                                prex = prex.PadRight(totalWidth, '0');
                            }
                            pf.set_Value(index, prex);
                            pcursor.UpdateFeature(pf);
                            //
                        }
                        pf = pcursor.NextFeature();
                    }
                    pcursor.Flush();
                    if (pcursor != null)
                    {
                        TokayWorkspace.ComRelease(pcursor);
                        pcursor = null;
                    }
                    if (pd != null)
                    {
                        pd.Dispose();
                        pd = null;
                    }
                    MessageBox.Show("更新完毕!", "提示");
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.StackTrace, "提示");
            }
            finally
            {
                if (pd != null)
                {
                    pd.Dispose();
                    pd = null;
                }
            }
        }
Ejemplo n.º 24
0
        //public static void CreateFishNet(string inTemplate, int width, int height, string outFishNet)
        //{
        //    IFeatureClass inFeatureClass = null;
        //    IFeatureClass outFeatureClass = null;
        //    ISpatialReference spatialReference = null;
        //    IEnvelope extent = null;
        //    try
        //    {
        //        inFeatureClass = EngineAPI.OpenFeatureClass(inTemplate);
        //        spatialReference = (inFeatureClass as IGeoDataset).SpatialReference;
        //        if (!CreateShpFile(outFishNet, spatialReference))
        //        {
        //            throw new Exception("创建矢量文件失败!");
        //        }
        //        outFeatureClass = EngineAPI.OpenFeatureClass(outFishNet);

        //        extent = (inFeatureClass as IGeoDataset).Extent;
        //        double extentW = extent.Width;
        //        double extentH = extent.Height;
        //        double extenXmin = extent.XMin;
        //        double extenYmin = extent.YMin;

        //        int columCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(extentW / width)));
        //        int rowCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(extentH / height)));
        //        for (int j = 0; j < rowCount * columCount; j++)
        //        {
        //            int row = j / columCount;
        //            int col = j % columCount;

        //            IEnvelope rect = new EnvelopeClass();
        //            rect.SpatialReference = spatialReference;
        //            rect.XMin = extenXmin + col * width;
        //            rect.XMax = rect.XMin + width;
        //            rect.YMin = extenYmin + row * height;
        //            rect.YMax = rect.YMin + height;
        //            IElement ele = new RectangleElementClass
        //            {
        //                Geometry = rect
        //            };

        //            IFeature pFeature = outFeatureClass.CreateFeature();
        //            pFeature.Shape = ele.Geometry;
        //            pFeature.Store();
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    finally
        //    {
        //        if (spatialReference != null)
        //            Marshal.ReleaseComObject(spatialReference);
        //        if (extent != null)
        //            Marshal.ReleaseComObject(extent);
        //        if (inFeatureClass != null)
        //            Marshal.ReleaseComObject(inFeatureClass);
        //        if (outFeatureClass != null)
        //            Marshal.ReleaseComObject(outFeatureClass);
        //    }

        //}

        public static void Sampling(string inFirstUnit, string firstUnit_Name, string layer, string inSecondUnit, string inCultivation, SamplePara para, string outSample)
        {
            IFeatureClass     inFirstF         = null;
            IFeatureClass     inSecondF        = null;
            IFeatureClass     inCultivationF   = null;
            IFeatureClass     outFeatureClass  = null;
            ISpatialReference spatialReference = null;

            try
            {
                //耕地和一级抽样单元相交处理
                string instert = System.IO.Path.Combine(ConstDef.PATH_TEMP, DateTime.Now.ToFileTime().ToString() + ".shp");
                string msg     = string.Empty;
                if (!EnviVars.instance.GpExecutor.Intersect(inFirstUnit + ";" + inCultivation, instert, out msg))
                {
                    throw new Exception(msg);
                }
                //读取一级抽样单元
                inFirstF = EngineAPI.OpenFeatureClass(inFirstUnit);
                //读取二级渔网
                inSecondF        = EngineAPI.OpenFeatureClass(inSecondUnit);
                spatialReference = (inFirstF as IGeoDataset).SpatialReference;
                //创建二级抽样单元矢量
                if (!CreateShpFile(outSample, spatialReference, firstUnit_Name, layer))
                {
                    throw new Exception("创建二级抽样单元矢量文件失败!");
                }
                outFeatureClass = EngineAPI.OpenFeatureClass(outSample);
                //读取一级抽样单元与耕地相交结果
                inCultivationF = EngineAPI.OpenFeatureClass(instert);
                //一级单元抽样个数
                int            firstUnitCount = inFirstF.FeatureCount(null);
                int            nameIndex      = inFirstF.FindField(firstUnit_Name);
                int            layerIndex     = inFirstF.FindField(layer);
                IFeature       pFFirst        = null;
                IFeatureCursor pFCFirst       = inFirstF.Search(null, false);
                IFeatureBuffer pFeatureBuffer = outFeatureClass.CreateFeatureBuffer();
                IFeatureCursor pInsertCursor  = outFeatureClass.Insert(true);
                while ((pFFirst = pFCFirst.NextFeature()) != null)
                {
                    string       fUnitName    = pFFirst.get_Value(nameIndex).ToString();
                    IQueryFilter pQFIntersect = new QueryFilterClass();
                    pQFIntersect.WhereClause = "\"" + firstUnit_Name + "\"" + " = '" + fUnitName + "'";
                    IFeatureCursor pFeatureCursor = inCultivationF.Search(pQFIntersect, false);
                    //指定一级抽样单元内耕地geometry合并
                    IFeature unionFeature = inCultivationF.CreateFeature();
                    IFeature pFeature     = null;
                    while ((pFeature = pFeatureCursor.NextFeature()) != null)
                    {
                        IGeometry             geometry  = unionFeature.Shape;
                        ITopologicalOperator2 unionTopo = geometry as ITopologicalOperator2;
                        unionFeature.Shape = unionTopo.Union(pFeature.ShapeCopy);
                    }
                    //Marshal.ReleaseComObject(pFeatureCursor);
                    //获取与耕地合并geometry相交的二级格网
                    ISpatialFilter pSFSecond = new SpatialFilterClass();
                    pSFSecond.Geometry   = unionFeature.Shape;
                    pSFSecond.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    pFeatureCursor       = inSecondF.Search(pSFSecond, false);
                    List <IFeature> sUnitFList = new List <IFeature>();
                    while ((pFeature = pFeatureCursor.NextFeature()) != null)
                    {
                        sUnitFList.Add(pFeature);
                    }
                    if (pFeatureCursor != null)
                    {
                        Marshal.ReleaseComObject(pFeatureCursor);
                    }
                    int sampleNum = 0;
                    if (para.isNum)
                    {
                        sampleNum = para.sampleNum;
                    }
                    else
                    {
                        sampleNum = Convert.ToInt32(sUnitFList.Count * para.sampleRate);
                    }

                    if (sUnitFList.Count > sampleNum)
                    {
                        //从相交的二级格网中随机抽样指定个数,并存出
                        Random ran = new Random();
                        for (int j = 0; j < sampleNum; j++)
                        {
                            //System.Threading.Thread.Sleep(100);
                            int range    = sUnitFList.Count - 1;
                            int selected = ran.Next(0, range);
                            pFeatureBuffer.Shape = sUnitFList[selected].ShapeCopy;
                            pFeatureBuffer.set_Value(2, j);
                            pFeatureBuffer.set_Value(3, fUnitName);
                            pFeatureBuffer.set_Value(4, pFFirst.get_Value(layerIndex));
                            pInsertCursor.InsertFeature(pFeatureBuffer);
                            sUnitFList.RemoveAt(selected);
                        }
                    }
                    else
                    {
                        //throw new Exception("选择的样本数大于样本总量!");

                        for (int j = 0; j < sUnitFList.Count; j++)
                        {
                            pFeatureBuffer.Shape = sUnitFList[j].ShapeCopy;
                            pFeatureBuffer.set_Value(2, j);
                            pFeatureBuffer.set_Value(3, fUnitName);
                            pFeatureBuffer.set_Value(4, pFFirst.get_Value(layerIndex));
                            pInsertCursor.InsertFeature(pFeatureBuffer);
                            //pFeature = outFeatureClass.CreateFeature();
                            //pFeature.Shape = sUnitFList[j].ShapeCopy;
                            ////secondUnitCount++;
                            //pFeature.set_Value(2, j);
                            //pFeature.set_Value(3, fUnitName);
                            //pFeature.set_Value(4, pFFirst.get_Value(layerIndex));
                            //pFeature.Store();
                        }
                    }
                }
                pInsertCursor.Flush();
                if (pFeatureBuffer != null)
                {
                    Marshal.ReleaseComObject(pFeatureBuffer);
                }
                if (pInsertCursor != null)
                {
                    Marshal.ReleaseComObject(pInsertCursor);
                }
                if (pFCFirst != null)
                {
                    Marshal.ReleaseComObject(pFCFirst);
                }
                //for (int i = 0; i < firstUnitCount; i++)
                //{
                //    IFeature pFeature = inFirstF.GetFeature(i);
                //    string fUnitName = pFeature.Table.GetRow(i).get_Value(nameIndex).ToString();
                //    IQueryFilter pQueryFilter = new QueryFilterClass();
                //    pQueryFilter.WhereClause = "\"" + firstUnit_Name + "\"" + " = '" +  fUnitName + "'";
                //    IFeatureCursor pFeatureCursor = inCultivationF.Search(pQueryFilter, false);
                //    //ISelectionSet pSelectionSet = inCultivationF.Select(pQueryFilter, esriSelectionType.esriSelectionTypeSnapshot, esriSelectionOption.esriSelectionOptionNormal, null);
                //    //IPolygon polygon =(pSelectionSet as IPolygon);
                //    //指定一级抽样单元内耕地geometry合并
                //    IFeature unionFeature = inCultivationF.CreateFeature();
                //    while ((pFeature = pFeatureCursor.NextFeature()) != null)
                //    {
                //        IGeometry geometry = unionFeature.Shape;
                //        ITopologicalOperator2 unionTopo = geometry as ITopologicalOperator2;
                //        unionFeature.Shape = unionTopo.Union(pFeature.ShapeCopy);
                //    }
                //    //获取与耕地合并geometry相交的二级格网
                //    ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                //    pSpatialFilter.Geometry = unionFeature.Shape;
                //    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                //    pFeatureCursor = inSecondF.Search(pSpatialFilter, false);
                //    List<IFeature> sUnitFList = new List<IFeature>();
                //    while ((pFeature = pFeatureCursor.NextFeature()) != null)
                //    {
                //        sUnitFList.Add(pFeature);
                //    }
                //    if (sUnitFList.Count < sampleNum)
                //    {
                //        throw new Exception("选择的样本数大于样本总量!");
                //    }
                //    //从相交的二级格网中随机抽样指定个数,并存出
                //    for (int j = 0; j < sampleNum; j++)
                //    {
                //        System.Threading.Thread.Sleep(100);
                //        Random ran = new Random();
                //        int range = sUnitFList.Count - 1;
                //        int selected = ran.Next(0, range);
                //        pFeature = outFeatureClass.CreateFeature();
                //        pFeature.Shape = sUnitFList[selected].ShapeCopy;
                //        secondUnitCount++;
                //        pFeature.set_Value(2,secondUnitCount);
                //        pFeature.Store();
                //        sUnitFList.RemoveAt(selected);
                //    }
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (spatialReference != null)
                {
                    Marshal.ReleaseComObject(spatialReference);
                }
                if (outFeatureClass != null)
                {
                    Marshal.ReleaseComObject(outFeatureClass);
                }
                if (inCultivationF != null)
                {
                    Marshal.ReleaseComObject(inCultivationF);
                }
                if (inSecondF != null)
                {
                    Marshal.ReleaseComObject(inSecondF);
                }
                if (inFirstF != null)
                {
                    Marshal.ReleaseComObject(inFirstF);
                }
            }
        }
Ejemplo n.º 25
0
        private void btnBoxplot_Click(object sender, EventArgs e)
        {
            try
            {
                #region Combined Chart

                string strTargetLayerName = cboTargetLayer.Text;
                string strFieldName       = cboFieldName.Text;
                string strGroupFieldName  = cboGroupField.Text;

                int intTargetIndex   = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strTargetLayerName);
                int intNFeatureCount = 0;

                ILayer pTargetLayer = m_pForm.axMapControl1.get_Layer(intTargetIndex);

                IFeatureLayer pTargetFLayer = (IFeatureLayer)pTargetLayer;

                //Extract geometry from selected feature
                IFeatureCursor pFCursor = null;
                pFCursor         = pTargetFLayer.Search(null, true);
                intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(null);

                int intFieldIdx = pTargetFLayer.FeatureClass.Fields.FindField(strFieldName);
                int intGroupIdx = pTargetFLayer.FeatureClass.Fields.FindField(strGroupFieldName);

                System.Collections.Generic.List <object> uvList = new System.Collections.Generic.List <object>();
                ICursor ipCursor = pFCursor as ICursor;
                IRow    ipRow    = ipCursor.NextRow();
                while (ipRow != null)
                {
                    object curValue = ipRow.get_Value(intGroupIdx);

                    if (!uvList.Contains(curValue))
                    {
                        uvList.Add(curValue);
                    }

                    ipRow = ipCursor.NextRow();
                }
                uvList.Sort();

                //Add exeption for sorting //0421 HK
                //1. H L M
                if (uvList.Count == 3)
                {
                    if (uvList[0].ToString() == "H" && uvList[1].ToString() == "L" && uvList[2].ToString() == "M")
                    {
                        uvList.Clear();
                        uvList.Add("L");
                        uvList.Add("M");
                        uvList.Add("H");
                    }
                    if (uvList[0].ToString() == "High" && uvList[1].ToString() == "Low" && uvList[2].ToString() == "Medium")
                    {
                        uvList.Clear();
                        uvList.Add("Low");
                        uvList.Add("Medium");
                        uvList.Add("High");
                    }
                }

                ipCursor.Flush();

                int intNGroups = uvList.Count;
                double[,] adbBPStats   = new double[5, uvList.Count];
                double[,] adbQuantiles = new double[5, uvList.Count];

                IQueryFilter pQfilter    = new QueryFilterClass();
                double[][]   adblTarget  = new double[intNGroups][];
                double[][]   adblDiff    = new double[intNGroups][];
                int[]        aintNCounts = new int[intNGroups];
                int          i           = 0;

                foreach (string uvValue in uvList)
                {
                    pQfilter.WhereClause = strGroupFieldName + " = '" + uvValue + "'";
                    pFCursor             = pTargetFLayer.Search(pQfilter, true);
                    IFeature pFeature = pFCursor.NextFeature();
                    intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(pQfilter);
                    aintNCounts[i]   = intNFeatureCount;
                    adblTarget[i]    = new double[intNFeatureCount];
                    adblDiff[i]      = new double[intNFeatureCount];

                    int j = 0;
                    while (pFeature != null)
                    {
                        adblTarget[i][j] = Convert.ToDouble(pFeature.get_Value(intFieldIdx));
                        j++;
                        pFeature = pFCursor.NextFeature();
                    }
                    pFCursor.Flush();

                    double[] dblQuantiles = new double[5];
                    dblQuantiles = BoxPlotStats(adblTarget[i]);
                    adblDiff[i]  = GetStatsForStackedBarChart(adblTarget[i]);

                    for (int k = 0; k < 5; k++) // Needs to be modified 010716 HK
                    {
                        adbQuantiles[k, i] = dblQuantiles[k];
                    }
                    i++;
                }


                frmBoxPlotResults pfrmBoxplotResults = new frmBoxPlotResults();
                pfrmBoxplotResults.Text = "BoxPlot of " + pTargetFLayer.Name;
                pfrmBoxplotResults.pChart.Series.Clear();
                ChartArea area = pfrmBoxplotResults.pChart.ChartAreas[0];
                int       intMaxFeatureNCount = aintNCounts.Max();

                //Draw Lines
                for (int k = 0; k < intNGroups; k++)
                {
                    int intXvalue = k * 2 + 1;

                    double dblXmin    = Convert.ToDouble(intXvalue) - 0.6;
                    double dblXmax    = Convert.ToDouble(intXvalue) + 0.6;
                    double dblXBoxMin = Convert.ToDouble(intXvalue) - 0.8;
                    double dblXBoxMax = Convert.ToDouble(intXvalue) + 0.8;

                    AddLineSeries(pfrmBoxplotResults, "min_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[0, k], adbQuantiles[0, k]);
                    AddLineSeries(pfrmBoxplotResults, "BoxBottom_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[1, k], adbQuantiles[1, k]);
                    AddLineSeries(pfrmBoxplotResults, "BoxLeft_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMin, adbQuantiles[1, k], adbQuantiles[3, k]);
                    AddLineSeries(pfrmBoxplotResults, "BoxRight_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMax, dblXBoxMax, adbQuantiles[1, k], adbQuantiles[3, k]);
                    AddLineSeries(pfrmBoxplotResults, "Boxup_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[3, k], adbQuantiles[3, k]);
                    AddLineSeries(pfrmBoxplotResults, "median_" + k.ToString(), Color.Black, 2, ChartDashStyle.Solid, dblXBoxMin, dblXBoxMax, adbQuantiles[2, k], adbQuantiles[2, k]);
                    AddLineSeries(pfrmBoxplotResults, "max_" + k.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adbQuantiles[4, k], adbQuantiles[4, k]);
                    AddLineSeries(pfrmBoxplotResults, "verDown_" + k.ToString(), Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[0, k], adbQuantiles[1, k]);
                    AddLineSeries(pfrmBoxplotResults, "verUp_" + k.ToString(), Color.Black, 1, ChartDashStyle.Dash, intXvalue, intXvalue, adbQuantiles[3, k], adbQuantiles[4, k]);
                }

                //Add Points
                System.Drawing.Color pMarkerColor = System.Drawing.Color.Blue;
                var seriesOutPts = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name              = "Points",
                    Color             = pMarkerColor,
                    BorderColor       = pMarkerColor,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                    MarkerStyle       = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle
                };

                pfrmBoxplotResults.pChart.Series.Add(seriesOutPts);

                for (int k = 0; k < intNGroups; k++)
                {
                    int intXvalue = k * 2 + 1;
                    foreach (double dblValue in adblTarget[k])
                    {
                        //if (dblValue < adbQuantiles[1, k] || dblValue > adbQuantiles[3, k])
                        seriesOutPts.Points.AddXY(intXvalue, dblValue);
                    }
                }

                pMarkerColor = System.Drawing.Color.Black;
                var seriesInPts = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name              = "InPoints",
                    Color             = pMarkerColor,
                    BorderColor       = pMarkerColor,
                    IsVisibleInLegend = false,
                    IsXValueIndexed   = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                    MarkerStyle       = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle
                };

                pfrmBoxplotResults.pChart.Series.Add(seriesInPts);

                for (int k = 0; k < intNGroups; k++)
                {
                    int intXvalue = k * 2 + 1;
                    foreach (double dblValue in adblTarget[k])
                    {
                        if (dblValue >= adbQuantiles[1, k] && dblValue <= adbQuantiles[3, k])
                        {
                            seriesInPts.Points.AddXY(intXvalue, dblValue);
                        }
                    }
                }

                //Store variables in frmBoxPlotResults
                pfrmBoxplotResults.mForm             = m_pForm;
                pfrmBoxplotResults.pActiveView       = m_pActiveView;
                pfrmBoxplotResults.pFLayer           = pTargetFLayer;
                pfrmBoxplotResults.Text              = "Boxplot of " + pTargetFLayer.Name;
                pfrmBoxplotResults.strFieldName      = strFieldName;
                pfrmBoxplotResults.strGroupFieldName = strGroupFieldName;
                pfrmBoxplotResults.uvList            = uvList;
                //pfrmBoxplotResults.pFillColor = pFillColor;
                pfrmBoxplotResults.adbQuantiles = adbQuantiles;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Title             = strGroupFieldName;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisY.Title             = strFieldName;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisY.IsStartedFromZero = false;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Maximum           = intNGroups * 2;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Interval          = 2;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.Minimum           = 0;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IntervalOffset    = -1;
                pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IsLabelAutoFit    = false;
                for (int n = 0; n < uvList.Count; n++)
                {
                    int intXvalue = n * 2 + 1;

                    double dblXmin = Convert.ToDouble(intXvalue) - 0.6;
                    double dblXmax = Convert.ToDouble(intXvalue) + 0.6;

                    CustomLabel pcutsomLabel = new CustomLabel();
                    pcutsomLabel.FromPosition = dblXmin;
                    pcutsomLabel.ToPosition   = dblXmax;
                    pcutsomLabel.Text         = uvList[n].ToString();

                    pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel);
                }

                #endregion
                pfrmBoxplotResults.Show();
                #region Previous Method (ChartType = SeriesChartType.BoxPlot)
                //Previous Method using Boxplot Chart Type (01/07/16)
                //string strTargetLayerName = cboTargetLayer.Text;
                //string strFieldName = cboFieldName.Text;
                //string strGroupFieldName = cboGroupField.Text;

                //int intTargetIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName);
                //int intNFeatureCount = 0;

                //ILayer pTargetLayer = mForm.axMapControl1.get_Layer(intTargetIndex);

                //IFeatureLayer pTargetFLayer = (IFeatureLayer)pTargetLayer;

                ////Extract geometry from selected feature
                //IFeatureCursor pFCursor = null;
                //pFCursor = pTargetFLayer.Search(null, true);
                //intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(null);

                //int intFieldIdx = pTargetFLayer.FeatureClass.Fields.FindField(strFieldName);
                //int intGroupIdx = pTargetFLayer.FeatureClass.Fields.FindField(strGroupFieldName);

                //System.Collections.Generic.List<object> uvList = new System.Collections.Generic.List<object>();
                //ICursor ipCursor = pFCursor as ICursor;
                //IRow ipRow = ipCursor.NextRow();
                //while (ipRow != null)
                //{
                //    object curValue = ipRow.get_Value(intGroupIdx);

                //    if (!uvList.Contains(curValue))
                //    {
                //        uvList.Add(curValue);
                //    }

                //    ipRow = ipCursor.NextRow();
                //}
                //uvList.Sort();

                //double[] adblTarget = new double[intNFeatureCount];
                //string[] astrGroup = new string[intNFeatureCount];
                //IQueryFilter pQfilter = new QueryFilterClass();

                //frmBoxPlotResults pfrmBoxplotResults = new frmBoxPlotResults();
                //pfrmBoxplotResults.pChart.Series.Clear();
                //ChartArea area = pfrmBoxplotResults.pChart.ChartAreas[0];

                //Series DataSeries = new Series();

                //foreach (string uvValue in uvList)
                //{
                //    pQfilter.WhereClause = strGroupFieldName + " = '" + uvValue + "'";
                //    pFCursor = pTargetFLayer.Search(pQfilter, true);
                //    IFeature pFeature = pFCursor.NextFeature();
                //    intNFeatureCount = pTargetFLayer.FeatureClass.FeatureCount(pQfilter);
                //    adblTarget = new double[intNFeatureCount];

                //    int j = 0;
                //    while (pFeature != null)
                //    {
                //        adblTarget[j] = Convert.ToDouble(pFeature.get_Value(intFieldIdx));
                //        j++;
                //        pFeature = pFCursor.NextFeature();
                //    }
                //    DataSeries = new Series(uvValue);
                //    DataSeries.ChartArea = area.Name;
                //    DataSeries.Color = Color.Transparent;
                //    DataSeries.Points.DataBindY(adblTarget);
                //    DataSeries.XValueType = ChartValueType.String;
                //    //DataSeries.IsXValueIndexed = true;
                //    pfrmBoxplotResults.pChart.Series.Add(DataSeries);

                //}

                //Series BoxPlotSeries = new Series()
                //{
                //    Name = "BoxPlotSeries",
                //    ChartArea = area.Name,
                //    ChartType = SeriesChartType.BoxPlot,
                //    Color = Color.White,
                //    BorderColor = Color.Black,
                //   // IsXValueIndexed = true,
                //XValueType = ChartValueType.String,
                //};
                //pfrmBoxplotResults.pChart.Series.Add(BoxPlotSeries);
                //pfrmBoxplotResults.pChart.Series["BoxPlotSeries"]["BoxPlotSeries"] = string.Join(";", uvList);
                //pfrmBoxplotResults.pChart.ChartAreas[0].AxisX.IsMarksNextToAxis = false;
                ////Manually Change the labels for Boxplot -- Needs to be modified 011117 HK
                //for (int n = 0; n <= uvList.Count; n++)
                //{
                //    //pfrmBoxplotResults.pChart.Series["BoxPlotSeries"].Points[n].AxisLabel = uvList[n].ToString();

                //    if (n == uvList.Count)
                //        pfrmBoxplotResults.pChart.Series[0].Points[n].AxisLabel = " ";
                //    else
                //        pfrmBoxplotResults.pChart.Series[0].Points[n].AxisLabel = uvList[n].ToString();
                //    //area.AxisX.CustomLabels[n].Text = uvList[n].ToString();
                //}

                //area.AxisX.Maximum = uvList.Count + 1;


                //area.AxisX.Minimum = 0;


                //pfrmBoxplotResults.Show();

                #endregion
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ProgressDialog pd = null;

            try
            {
                CommonComboBoxItem item = this.comboBox1.SelectedItem as CommonComboBoxItem;
                if (item == null)
                {
                    MessageBox.Show("请先选择要计算的图层", "提示");
                    return;
                }
                string fd_item = this.CB_Fields.Text;
                if (fd_item == "")
                {
                    MessageBox.Show("请先选择要计算的字段", "提示");
                    return;
                }
                //ILayer layer = item.Tag as ILayer;
                //IFeatureLayer featLayer = layer as IFeatureLayer;
                IFeatureClass fc = item.Tag as IFeatureClass;
                //
                string fdName = this.CB_Fields.Text;
                //
                int fCount = fc.FeatureCount(null);
                if (fCount > 0)
                {
                    IFeatureCursor pcursor = fc.Update(null, false);
                    IFeature       pf      = pcursor.NextFeature();
                    int            index   = fc.FindField(fdName);
                    pd         = new ProgressDialog();
                    pd.Text    = "进度";
                    pd.Message = "计算字段图形面积中......";
                    pd.Minimum = 0;
                    pd.Maximum = fCount;
                    pd.Show(this);
                    //
                    Application.DoEvents();
                    double t_area = 0.0;
                    int    n      = 0;
                    while (pf != null)
                    {
                        n = n + 1;
                        if (n % 200 == 0)
                        {
                            pd.Value   = n;
                            pd.Message = "计算字段图形面积中......" + pd.Value.ToString() + "/" + pd.Maximum.ToString();
                            Application.DoEvents();
                            pcursor.Flush();
                        }
                        IArea area = (pf.Shape as IArea);
                        if (area != null)
                        {
                            t_area = area.Area;
                            pf.set_Value(index, t_area);
                            //
                            pcursor.UpdateFeature(pf);
                        }
                        //
                        pf = pcursor.NextFeature();
                    }
                    pcursor.Flush();
                    if (pcursor != null)
                    {
                        TokayWorkspace.ComRelease(pcursor);
                        pcursor = null;
                    }
                    if (pd != null)
                    {
                        pd.Dispose();
                        pd = null;
                    }
                    MessageBox.Show("计算完毕!", "提示");
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.StackTrace, "提示");
            }
            finally
            {
                if (pd != null)
                {
                    pd.Dispose();
                    pd = null;
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 创建shp文件
        /// </summary>
        /// <param name="shpPath">入样总体文件</param>
        /// <param name="SampleTable">抽样样本表</param>
        /// <param name="sampleFile">生成样本shp</param>
        /// <returns>是否创建成功</returns>
        public bool CreateShpFile(string shpPath, DataTable SampleTable, string sampleFile)
        {
            bool result = true;
            IWorkspaceFactory2 workspaceFactory = null;
            IWorkspace         workspace        = null;
            IFeatureClass      allVillage       = null;
            ISpatialReference  spatialReference = null;
            IFeatureClass      sampleClass      = null;

            try
            {
                //获取入样总体的坐标信息
                allVillage       = EngineAPI.OpenFeatureClass(shpPath);
                spatialReference = (allVillage as IGeoDataset).SpatialReference;

                //ISpatialReference spatialReference = pGeoDataset.SpatialReference;

                FileInfo info      = new FileInfo(sampleFile);
                string   directory = info.DirectoryName;
                string   name      = info.Name.Substring(0, info.Name.Length - info.Extension.Length);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                workspaceFactory = new ShapefileWorkspaceFactoryClass();
                workspace        = workspaceFactory.OpenFromFile(directory, 0);

                if (workspace == null)
                {
                    result = false;
                }
                else
                {
                    if (EngineAPI.IsNameExist(workspace, name, esriDatasetType.esriDTFeatureClass))
                    {
                        EngineAPI.DeleteDataset(workspace, name, esriDatasetType.esriDTFeatureClass);
                    }

                    IFields requiredFields = allVillage.Fields;
                    if (requiredFields == null)
                    {
                        result = false;
                    }
                    sampleClass = CreateFeatureClass(workspace, name, requiredFields, spatialReference);
                    //添加字段
                    AddFields(sampleClass, _expand);
                    if (sampleClass == null)
                    {
                        result = false;
                    }

                    //添加要素
                    IFeatureCursor pFeaCur  = sampleClass.Insert(true);
                    IFeatureBuffer pFeaBuf  = null;
                    IFeature       pFeature = null;
                    for (int i = 0; i < SampleTable.Rows.Count; i++)
                    {
                        pFeature      = allVillage.GetFeature(Convert.ToInt32(SampleTable.Rows[i][0]));
                        pFeaBuf       = sampleClass.CreateFeatureBuffer();
                        pFeaBuf.Shape = pFeature.ShapeCopy;

                        //添加字段值
                        for (int j = 2; j < requiredFields.FieldCount; j++)
                        {
                            pFeaBuf.set_Value(j, SampleTable.Rows[i][j]);
                            //IField pField = requiredFields.get_Field(j);
                            //int iIndex = pFeaBuf.Fields.FindField(pField.Name);
                            //if (iIndex != -1)
                            //{
                            //    pFeaBuf.set_Value(iIndex, SampleTable.Rows [i][j]);
                            //}
                        }
                        int fIndex = pFeaBuf.Fields.FindField(_expand);
                        if (fIndex > 0 && SampleTable.Columns.Contains(_expand))
                        {
                            pFeaBuf.set_Value(fIndex, SampleTable.Rows[i][_expand]);
                        }

                        pFeaCur.InsertFeature(pFeaBuf);
                    }

                    //保存要素
                    pFeaCur.Flush();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaCur);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaBuf);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeature);
                }
                ////删除添加的字段
                //IFields fields = allVillage.Fields;
                //IField field = fields.get_Field(fields.FindField(_expand));
                //allVillage.DeleteField(field);
                return(result);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                Log.WriteLog(typeof(SampleSimulation), ex);
                return(result);
            }
            finally
            {
                if (sampleClass != null)
                {
                    Marshal.ReleaseComObject(sampleClass);
                }
                if (spatialReference != null)
                {
                    Marshal.ReleaseComObject(spatialReference);
                }
                if (allVillage != null)
                {
                    Marshal.ReleaseComObject(allVillage);
                }
                if (workspace != null)
                {
                    Marshal.ReleaseComObject(workspace);
                }
                if (workspaceFactory != null)
                {
                    Marshal.ReleaseComObject(workspaceFactory);
                }
            }
        }
Ejemplo n.º 28
0
        public void Calculate(string sShorelineLayer, string sDepthPointsLayer, double dblInterval, string strShoreDepthField, string strDepthPointDepthField)
        {
            try
            {
                IMxDocument pmxdoc = ArcMap.Document as IMxDocument;
                IMap        pmap   = pmxdoc.FocusMap;

                IFeatureLayer pDepthSoundings = FindLayer(pmap, sDepthPointsLayer) as IFeatureLayer;
                IFeatureLayer pShorelineLayer = FindLayer(pmap, sShorelineLayer) as IFeatureLayer;

                //IFeatureLayer pOutpoints = FindLayer(pmap, sOutpoints) as IFeatureLayer;
                IFeatureLayer pOutpoints = new FeatureLayerClass();
                pOutpoints.FeatureClass = MakePointFC();
                pOutpoints.Name         = "Output Points";
                ArcMap.Document.ActiveView.FocusMap.AddLayer(pOutpoints);

                IFeatureLayer pConnectingLines = FindLayer(pmap, "ConnectingLines") as IFeatureLayer;
                IFeatureLayer pShorePoints     = FindLayer(pmap, "ShorePoints") as IFeatureLayer;



                ////Add fields if necessary
                //AddField(pOutpoints, "Distance");
                //AddField(pOutpoints, "Elevation");


                //Set up the Outpoints cursor
                IFeatureCursor pFCurOutPoints = pOutpoints.Search(null, false);
                pFCurOutPoints = pOutpoints.FeatureClass.Insert(true);
                IFeatureBuffer pFOutPointsBuffer = pOutpoints.FeatureClass.CreateFeatureBuffer();


                //Set up the LineLayer Cursor (now using selected lines)
                IFeatureSelection pShoreLineSelection = pShorelineLayer as IFeatureSelection;

                if (pShoreLineSelection.SelectionSet.Count == 0)
                {
                    MessageBox.Show("You must have at least one shoreline feature selected");
                    return;
                }
                ICursor        pShorelineCursor;
                IFeatureCursor pSelShoreFeatCur;
                pShoreLineSelection.SelectionSet.Search(null, false, out pShorelineCursor);
                pSelShoreFeatCur = pShorelineCursor as IFeatureCursor;
                IFeature pShoreLineFeature = pSelShoreFeatCur.NextFeature();
                //IFeatureCursor pFCur = pShorelineLayer.Search(null, false);
                //IFeature pShoreLineFeature = pFCur.NextFeature();

                //Set up the pConnectingLines cursor
                IFeatureCursor pFCurOutLines = pConnectingLines.Search(null, false);
                pFCurOutLines = pConnectingLines.FeatureClass.Insert(true);
                IFeatureBuffer pFBuffer = pConnectingLines.FeatureClass.CreateFeatureBuffer();

                //Set up the pShorePoints cursor
                IFeatureCursor pShorePointsCursor = pShorePoints.Search(null, false);
                IFeature       pShorePointFeature = pShorePointsCursor.NextFeature();



                IFeature         pNewLineFeature   = null;
                IPointCollection pNewLinePointColl = null;


                double dblDistance = 0;
                double dblTotalDistanceCalculated = 0;
                int    iNumIntervals        = 0;
                double dblElevationDiff     = 0;
                double dblElevationInterval = 0;
                double dblElevation         = 0;
                double dlbStartElevation    = 0;
                double dblEndElevation      = 0;

                int iLineProgressCount           = 0;
                IProgressDialog2 pProgressDialog = ShowProgressIndicator("Calculating points for shoreline vertex: ", 0, 1);
                pProgressDialog.ShowDialog();



                IEnvelope pCombinedEnvelope = CombineExtents(pDepthSoundings.FeatureClass, pShorelineLayer.FeatureClass);
                while (pShoreLineFeature != null)
                {
                    //IPointCollection4 pPointColl = pShoreLineFeature.Shape as IPointCollection4;

                    IPoint ppoint = new PointClass();



                    //for (int i = 0; i <= pPointColl.PointCount - 1; i++)
                    while (pShorePointFeature != null)
                    {
                        ppoint = pShorePointFeature.ShapeCopy as IPoint;
                        System.Diagnostics.Debug.WriteLine("ppoint: " + ppoint.X.ToString());
                        System.Diagnostics.Debug.WriteLine("shorepoint: " + pShorePointFeature.OID.ToString());

                        ////try walking line at set intervals instead of just at vertices
                        //IPoint pLineVertex = new PointClass();
                        //pLineVertex = pPointColl.get_Point(i);

                        IFeatureCursor pDepthCursor = pDepthSoundings.Search(null, false);
                        IFeatureIndex2 pFtrInd      = new FeatureIndexClass();
                        pFtrInd.FeatureClass  = pDepthSoundings.FeatureClass;
                        pFtrInd.FeatureCursor = pDepthCursor;
                        pFtrInd.Index(null, pCombinedEnvelope);
                        IIndexQuery2 pIndQry = pFtrInd as IIndexQuery2;

                        int    FtdID     = 0;
                        double dDist2Ftr = 0;
                        pIndQry.NearestFeature(ppoint, out FtdID, out dDist2Ftr);

                        IFeature pCloseFeature = pDepthSoundings.FeatureClass.GetFeature(FtdID);

                        IPoint pEndPoint = new PointClass();
                        pEndPoint = pCloseFeature.Shape as IPoint;


                        //Make the line here
                        pNewLineFeature   = pConnectingLines.FeatureClass.CreateFeature();
                        pNewLinePointColl = new PolylineClass();

                        object missing = Type.Missing;
                        pNewLinePointColl.AddPoint(pEndPoint, ref missing, ref missing);
                        pNewLinePointColl.AddPoint(ppoint, ref missing, ref missing);
                        pNewLineFeature.Shape = pNewLinePointColl as PolylineClass;

                        //Check to see if new line crosses land, if not, process it.
                        //bool bLineIntersectsShore = FeatureIntersects(pShorelineLayer, pConnectingLines, pNewLineFeature);
                        bool bLineIntersectsShore = false;
                        if (bLineIntersectsShore == false)
                        {
                            pNewLineFeature.Store();



                            ICurve pCurve = pNewLineFeature.Shape as ICurve;
                            pCurve.Project(pmap.SpatialReference);

                            //Get the Starting Elevation from the closest depth point
                            dlbStartElevation = GetStartElevation(pDepthSoundings, pConnectingLines, pNewLineFeature, strDepthPointDepthField);
                            //The Elevation for the first run IS the start elevation
                            dblElevation = dlbStartElevation;
                            //////Get the ending elevation from the shoreline
                            dblEndElevation = GetEndElevation(pShorelineLayer, pConnectingLines, pNewLineFeature, strShoreDepthField);

                            //number of line segments based on the user's interval
                            iNumIntervals    = Convert.ToInt32(pCurve.Length / dblInterval);
                            dblElevationDiff = Math.Abs(dblEndElevation - dlbStartElevation);
                            //The calculated elevation interval to step up each time
                            dblElevationInterval = dblElevationDiff / iNumIntervals;


                            ppoint = new PointClass();

                            while (dblTotalDistanceCalculated <= pCurve.Length)
                            {
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("LineOID"), pNewLineFeature.OID);
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Distance"), dblDistance);
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Elevation"), dblElevation);


                                //this code set the point on the line at a distance
                                pCurve.QueryPoint(0, dblDistance, false, ppoint);

                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("X"), ppoint.X);
                                pFOutPointsBuffer.set_Value(pFOutPointsBuffer.Fields.FindField("Y"), ppoint.Y);


                                //reCalc the new distance and elevation values for the next iteration
                                dblDistance = dblDistance + dblInterval;

                                //add or subtract elevation depending on whether dblElevationDiff is positve or negative
                                if (dblElevationDiff > 0)
                                {
                                    dblElevation = dblElevation - dblElevationInterval;
                                }
                                else
                                {
                                    dblElevation = dblElevation + dblElevationInterval;
                                }
                                dblTotalDistanceCalculated = dblTotalDistanceCalculated + dblInterval;



                                //Insert the feature into the featureclass
                                pFOutPointsBuffer.Shape = ppoint;
                                pFCurOutPoints.InsertFeature(pFOutPointsBuffer);
                            }



                            //Reset the distance values back to 0 for the next feature
                            dblDistance = 0;
                            dblTotalDistanceCalculated = 0;
                            pFCurOutPoints.Flush();


                            pStepProgressor.Step();
                            pProgressDialog.Description = "Calculating points for shoreline vertex: " + pShorePointFeature.OID.ToString();
                            iLineProgressCount++;
                        }

                        pShorePointFeature = pShorePointsCursor.NextFeature();
                    }

                    pShoreLineFeature = pSelShoreFeatCur.NextFeature();
                }
                //cleanup
                pFCurOutLines.Flush();
                pSelShoreFeatCur.Flush();
                pProgressDialog.HideDialog();
                pmxdoc.ActiveView.Refresh();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.StackTrace);
            }
        }
Ejemplo n.º 29
0
        public IFeatureLayer CreateShapefile(string sNewLayerName, IArray pOldFeatures, IArray pNewGeometries, esriGeometryType nNewGeometryType)
        //增加一个新图层(如用于缓冲区等)
        {
            if (m_axMapControl == null || pOldFeatures.Count == 0 || pNewGeometries.Count == 0)
            {
                return(null);
            }
            //public static string GetWorkspacePath()
            //{
            string sPath = "\\WSData";

            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }
            //return sPath;
            //}
            string MapPath      = sPath; //改
            bool   bFileExisted = System.IO.File.Exists(MapPath + "\\" + sNewLayerName + ".shp");

            if (bFileExisted && MessageBox.Show("The file is already existed, and do you want to create new one?", "Select one", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                System.IO.File.Delete(MapPath + "\\" + sNewLayerName + ".shp");
                System.IO.File.Delete(MapPath + "\\" + sNewLayerName + ".dbf");
                System.IO.File.Delete(MapPath + "\\" + sNewLayerName + ".shx");
                RemoveLayer(sNewLayerName);
            }
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
            IFeatureWorkspace pFWS          = pWorkspaceFactory.OpenFromFile(MapPath, 0) as IFeatureWorkspace;
            IFeatureLayer     pFeatureLayer = new FeatureLayerClass();

            //If file existed, directly load
            if (System.IO.File.Exists(MapPath + "\\" + sNewLayerName + ".shp"))
            {
                pFeatureLayer.FeatureClass = pFWS.OpenFeatureClass(sNewLayerName);
                pFeatureLayer.Name         = pFeatureLayer.FeatureClass.AliasName;
                if (!IsLayerExisted(sNewLayerName))
                {
                    m_axMapControl.AddLayer(pFeatureLayer);
                    m_axMapControl.Refresh();
                }
                return(pFeatureLayer);
            }
            //Find fields from old feature
            IFeature pTmpFt     = pOldFeatures.get_Element(0) as IFeature;
            IFields  pTmpFields = pTmpFt.Fields;

            try
            {
                IFields     fields     = new FieldsClass();
                IFieldsEdit fieldsEdit = fields as IFieldsEdit;

                //Shape field
                IField     fd1     = new FieldClass();
                IFieldEdit fiEdit1 = fd1 as IFieldEdit;
                fiEdit1.Name_2 = "Shape";
                fiEdit1.Type_2 = esriFieldType.esriFieldTypeGeometry;
                IGeometryDef             pGeomDef                 = new GeometryDefClass();
                IGeometryDefEdit         pGeomDefEdit             = pGeomDef as IGeometryDefEdit;
                ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment();
                pGeomDefEdit.GeometryType_2 = nNewGeometryType;
                //pGeomDefEdit.SpatialReference_2 = pSpatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;
                fiEdit1.GeometryDef_2 = pGeomDef;
                fieldsEdit.AddField(fd1);

                for (int index = 0; index < pTmpFields.FieldCount; index++)
                {
                    IField pField = pTmpFields.get_Field(index);
                    if (IsSysField(pField.Name))
                    {
                        continue;
                    }
                    IField     fd      = new FieldClass();
                    IFieldEdit fiEdit2 = fd as IFieldEdit;
                    fiEdit2.Name_2      = pField.Name;
                    fiEdit2.Type_2      = pField.Type;
                    fiEdit2.Length_2    = pField.Length;
                    fiEdit2.AliasName_2 = pField.AliasName;
                    fieldsEdit.AddField(fd);
                }

                //Create feature class
                pFeatureLayer.FeatureClass = pFWS.CreateFeatureClass(sNewLayerName, fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
                pFeatureLayer.Name         = sNewLayerName;
                //start editing
                IFeatureClass  fc = pFeatureLayer.FeatureClass;
                IWorkspaceEdit w  = (fc as IDataset).Workspace as IWorkspaceEdit;
                //w.StartEditing(true);
                //w.StartEditOperation();
                IFeatureBuffer f   = fc.CreateFeatureBuffer();
                IFeatureCursor cur = fc.Insert(true);

                pTmpFields = fc.Fields;
                for (int i = 0; i < pOldFeatures.Count; i++)
                {
                    IFeature pOldFeature = pOldFeatures.get_Element(0) as IFeature;
                    f.Shape = pNewGeometries.get_Element(i) as IGeometry;
                    for (int index = 0; index < pTmpFields.FieldCount; index++)
                    {
                        IField pField = pTmpFields.get_Field(index);
                        if (IsSysField(pField.Name))
                        {
                            continue;
                        }
                        int nOldIdx = pOldFeature.Fields.FindField(pField.Name);
                        if (nOldIdx != -1)
                        {
                            object obj = pOldFeature.get_Value(nOldIdx);
                            f.set_Value(index, obj);
                        }
                    }
                    cur.InsertFeature(f);
                    //flush per 1000 loops
                    if (i % 1000 == 0)
                    {
                        cur.Flush();
                    }
                }
                cur.Flush();
                //w.StopEditOperation();
                //w.StopEditing(true);
                m_axMapControl.AddShapeFile(MapPath, sNewLayerName + ".shp");
                m_axMapControl.Refresh();
            }
            catch (Exception exception)
            {
                MessageBox.Show("Create" + sNewLayerName + " shapefile error:" + exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            return(pFeatureLayer);
        }
Ejemplo n.º 30
0
 private void FlushCursor(bool noFlush, ref IFeatureCursor cursor)
 {
     try
     {
         if (!noFlush && !IsHluWorkspaceSDE && (cursor != null))
         {
             cursor.Flush();
         }
     }
     finally
     {
         Marshal.ReleaseComObject(cursor);
         cursor = null;
     }
 }
Ejemplo n.º 31
0
        public static IFeatureClass exportDataToMemery(List <Dictionary <string, object> > dicExportData, IFeatureClass memoryFeaClsOfIntersect, ISpatialReference pSpatialReference,
                                                       out string msg)
        {
            msg = string.Empty;
            IWorkspaceEdit pWorkapceEdit        = null;
            IFeatureBuffer pTargetFeatureBuffer = null;
            IFeatureCursor pTargetFeatureCursor = null;

            try
            {
                IDataset dataset = memoryFeaClsOfIntersect as IDataset;
                pWorkapceEdit = dataset.Workspace as IWorkspaceEdit;
                pWorkapceEdit.StartEditing(false);
                pWorkapceEdit.StartEditOperation();
                pTargetFeatureBuffer = memoryFeaClsOfIntersect.CreateFeatureBuffer();
                pTargetFeatureCursor = memoryFeaClsOfIntersect.Insert(true);
                IFields fieldsSource = memoryFeaClsOfIntersect.Fields; //插入
                                                                       // fieldsSource.
                foreach (var item in dicExportData)
                {
                    foreach (var key in item.Keys)
                    {
                        int i = fieldsSource.FindField(key);

                        if (string.Equals(key, "geometry"))
                        {
                            pTargetFeatureBuffer.Shape = (IGeometry)item[key];
                        }

                        if (i > -1)
                        {
                            if (fieldsSource.Field[i].Type == esriFieldType.esriFieldTypeOID || fieldsSource.Field[i].Type == esriFieldType.esriFieldTypeGeometry)
                            {
                                continue;
                            }
                            if (item[key] != null)
                            {
                                pTargetFeatureBuffer.Value[i] = item[key];
                            }
                        }
                    }
                    pTargetFeatureCursor.InsertFeature(pTargetFeatureBuffer);
                }
                pTargetFeatureCursor.Flush();
                pWorkapceEdit.StopEditOperation();
                pWorkapceEdit.StopEditing(true);
            }
            catch (Exception e)
            {
                msg = e.Data + e.HelpLink + e.HResult + e.InnerException + e.Message + e.Source;
            }
            finally
            {
                if (pWorkapceEdit != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pWorkapceEdit);
                }
                if (pTargetFeatureBuffer != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pTargetFeatureBuffer);
                }
                if (pTargetFeatureCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pTargetFeatureCursor);
                }
            }
            return(memoryFeaClsOfIntersect);
        }