Ejemplo n.º 1
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                //Checking
                if (cboFieldName.Text == "")
                {
                    MessageBox.Show("Please select target field");
                    return;
                }

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

                int nFeature = m_pFClass.FeatureCount(null);

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

                //Get index for independent and dependent variables
                //Get variable index
                string strVarNM  = (string)cboFieldName.SelectedItem;
                int    intVarIdx = m_pFClass.FindField(strVarNM);

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

                int i = 0;

                while (pFeature != null)
                {
                    arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx));
                    i++;
                    pFeature = pFCursor.NextFeature();
                }

                //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;
                    }
                }

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

                if (cboSAM.Text == "Local Moran")
                {
                    #region Local Moran
                    plotCommmand.Append("localmoran(" + strVarNM + ", sample.listw, alternative = 'two.sided', ");

                    //select multiple correction method (only Bonferroni.. 100915 HK)
                    if (cboAdjustment.Text == "None")
                    {
                        plotCommmand.Append(", zero.policy=TRUE)");
                    }
                    else if (cboAdjustment.Text == "Bonferroni correction")
                    {
                        plotCommmand.Append("p.adjust.method='bonferroni', zero.policy=TRUE)");
                    }

                    NumericMatrix nmResults = m_pEngine.Evaluate(plotCommmand.ToString()).AsNumericMatrix();

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


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

                    int intStatFldIdx = m_pFClass.FindField(lvFields.Items[0].SubItems[1].Text);
                    int intZFldIdx    = m_pFClass.FindField(lvFields.Items[1].SubItems[1].Text);
                    int intPrFldIdx   = m_pFClass.FindField(lvFields.Items[2].SubItems[1].Text);
                    int intFlgFldIdx  = m_pFClass.FindField(strFlgFldNam);

                    double dblValue = 0, dblPvalue = 0, dblZvalue = 0;
                    double dblValueMean = arrVar.Average();
                    double dblPrCri     = Convert.ToDouble(nudConfLevel.Value);

                    int featureIdx = 0;
                    while (pFeature != null)
                    {
                        dblValue  = arrVar[featureIdx] - dblValueMean;
                        dblZvalue = nmResults[featureIdx, 3];
                        dblPvalue = nmResults[featureIdx, 4];
                        pFeature.set_Value(intStatFldIdx, (object)nmResults[featureIdx, 0]);
                        pFeature.set_Value(intZFldIdx, dblZvalue);
                        pFeature.set_Value(intPrFldIdx, dblPvalue);

                        if (dblPvalue < dblPrCri)
                        {
                            if (dblZvalue > 0)
                            {
                                if (dblValue > 0)
                                {
                                    pFeature.set_Value(intFlgFldIdx, "HH");
                                }
                                else
                                {
                                    pFeature.set_Value(intFlgFldIdx, "LL");
                                }
                            }
                            else
                            {
                                if (dblValue > 0)
                                {
                                    pFeature.set_Value(intFlgFldIdx, "HL");
                                }
                                else
                                {
                                    pFeature.set_Value(intFlgFldIdx, "LH");
                                }
                            }
                        }
                        //else
                        //    pFeature.set_Value(intFlgFldIdx, "");
                        pFCursor.UpdateFeature(pFeature);

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

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

                        IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                        pUniqueValueRenderer.FieldCount = 1;
                        pUniqueValueRenderer.set_Field(0, strFlgFldNam);
                        IDataStatistics    pDataStat;
                        IStatisticsResults pStatResults;

                        ICursor pCursor;

                        if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            ISimpleFillSymbol pSymbol;
                            IQueryFilter      pQFilter = new QueryFilterClass();
                            pQFilter.WhereClause = strFlgFldNam + " = 'HH'";

                            int intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 0] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 0] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(255, 80, 80);
                            pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol);
                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")");
                            }



                            pQFilter.WhereClause = strFlgFldNam + " = 'LL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 1] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 1] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(50, 157, 194);
                            pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'HL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 2] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 2] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(244, 199, 0);
                            pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'LH'";
                            intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 3] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 3] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(173, 255, 179);
                            pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")");
                            }



                            pSymbol       = new SimpleFillSymbolClass();
                            pSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
                            pSymbol.Color = m_pSnippet.getRGB(200, 200, 200);
                            //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol);
                            //pUniqueValueRenderer.set_Label("", "Not significant");
                            pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol;
                            pUniqueValueRenderer.DefaultLabel  = "Not significant";

                            pUniqueValueRenderer.UseDefaultSymbol = true;
                        }
                        else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            ISimpleMarkerSymbol pSymbol;
                            IQueryFilter        pQFilter = new QueryFilterClass();
                            pQFilter.WhereClause = strFlgFldNam + " = 'HH'";

                            int intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 0] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 0] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(255, 80, 80);
                            pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol);
                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")");
                            }



                            pQFilter.WhereClause = strFlgFldNam + " = 'LL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 1] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 1] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(50, 157, 194);
                            pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'HL'";
                            intCnt = pTable.RowCount(pQFilter);


                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 2] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 2] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(244, 199, 0);
                            pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")");
                            }


                            pQFilter.WhereClause = strFlgFldNam + " = 'LH'";
                            intCnt = pTable.RowCount(pQFilter);

                            pCursor                  = pTable.Search(pQFilter, true);
                            pDataStat                = new DataStatisticsClass();
                            pDataStat.Field          = lvFields.Items[1].SubItems[1].Text;
                            pDataStat.Cursor         = pCursor;
                            pStatResults             = pDataStat.Statistics;
                            adblMinMaxForLabel[0, 3] = pStatResults.Minimum;
                            adblMinMaxForLabel[1, 3] = pStatResults.Maximum;
                            pCursor.Flush();

                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(173, 255, 179);
                            pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol);

                            if (intCnt == 1)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")");
                            }
                            else if (intCnt == 0)
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (no obs)");
                            }
                            else
                            {
                                pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")");
                            }



                            pSymbol       = new SimpleMarkerSymbolClass();
                            pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
                            pSymbol.Color = m_pSnippet.getRGB(200, 200, 200);
                            //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol);
                            //pUniqueValueRenderer.set_Label("", "Not significant");
                            pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol;
                            pUniqueValueRenderer.DefaultLabel  = "Not significant";

                            pUniqueValueRenderer.UseDefaultSymbol = true;
                        }



                        IFeatureLayer pNewFLayer = new FeatureLayerClass();
                        pNewFLayer.FeatureClass = m_pFClass;
                        pNewFLayer.Name         = cboSAM.Text + " of " + m_pFLayer.Name;
                        IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                        pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                        m_pActiveView.FocusMap.AddLayer(pGFLayer);
                        m_pActiveView.Refresh();
                        m_pForm.axTOCControl1.Update();
                    }
                    else
                    {
                        MessageBox.Show("Complete. The results are stored in the shape file");
                    }
                    #endregion
                }
                else if (cboSAM.Text == "Gi*")
                {
                    #region Gi*
                    m_pEngine.Evaluate("sample.lg <- localG(" + strVarNM + ", sample.listw, zero.policy=TRUE)");
                    m_pEngine.Evaluate("sample.p <- 2*pnorm(-abs(sample.lg))");

                    if (cboAdjustment.Text == "Bonferroni correction")
                    {
                        m_pEngine.Evaluate("sample.p <- p.adjust(sample.p, method = 'bonferroni', n = length(sample.p))");
                    }

                    double[] dblGValues = m_pEngine.Evaluate("sample.lg").AsNumeric().ToArray();
                    double[] dblPvalues = m_pEngine.Evaluate("sample.p").AsNumeric().ToArray();

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

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

                    int intStatFldIdx = m_pFClass.FindField(lvFields.Items[0].SubItems[1].Text);
                    int intPrFldIdx   = m_pFClass.FindField(lvFields.Items[1].SubItems[1].Text);

                    int featureIdx = 0;
                    while (pFeature != null)
                    {
                        pFeature.set_Value(intStatFldIdx, dblGValues[featureIdx]);
                        pFeature.set_Value(intPrFldIdx, dblPvalues[featureIdx]);

                        pFCursor.UpdateFeature(pFeature);

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

                    pfrmProgress.Close();

                    if (chkMap.Checked)
                    {
                        string strStaticFldName = lvFields.Items[0].SubItems[1].Text;

                        m_pEngine.Evaluate("p.vals <- c(0.1, 0.05, 0.01)");
                        if (cboAdjustment.Text == "Bonferroni correction")
                        {
                            m_pEngine.Evaluate("sample.n <- length(sample.p)");
                            m_pEngine.Evaluate("p.vals <- p.vals/sample.n");
                        }
                        m_pEngine.Evaluate("zc <- qnorm(1 - (p.vals/2))");
                        double[] dblZBrks = m_pEngine.Evaluate("sort(cbind(zc, -zc))").AsNumeric().ToArray();

                        pFCursor = m_pFClass.Search(null, false);
                        IDataStatistics pDataStat = new DataStatisticsClass();
                        pDataStat.Field  = strStaticFldName;
                        pDataStat.Cursor = (ICursor)pFCursor;
                        IStatisticsResults pStatResults = pDataStat.Statistics;
                        double             dblMax       = pStatResults.Maximum;
                        double             dblMin       = pStatResults.Minimum;
                        int      intBreaksCount         = dblZBrks.Length + 2;
                        double[] cb = new double[intBreaksCount];

                        //Assign Min and Max values for class breaks
                        if (dblMin < dblZBrks[0])
                        {
                            cb[0] = dblMin;
                        }
                        else
                        {
                            cb[0] = dblZBrks[0] - 1; //Manually Assigned minimum value
                        }
                        if (dblMax > dblZBrks[dblZBrks.Length - 1])
                        {
                            cb[intBreaksCount - 1] = dblMax;
                        }
                        else
                        {
                            cb[intBreaksCount - 1] = dblZBrks[dblZBrks.Length - 1] + 1;//Manually Assigned minimum value
                        }
                        for (int k = 0; k < intBreaksCount - 2; k++)
                        {
                            cb[k + 1] = dblZBrks[k];
                        }

                        IClassBreaksRenderer pCBRenderer = new ClassBreaksRenderer();
                        pCBRenderer.Field        = strStaticFldName;
                        pCBRenderer.BreakCount   = intBreaksCount - 1;
                        pCBRenderer.MinimumBreak = cb[0];

                        //' use this interface to set dialog properties
                        IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pCBRenderer;
                        pUIProperties.ColorRamp = "Custom";
                        if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            ISimpleFillSymbol pSimpleFillSym;

                            int[,] arrColors = CreateColorRamp();

                            //Add Probability Value Manually
                            string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" };
                            //' be careful, indices are different for the diff lists
                            for (int j = 0; j < intBreaksCount - 1; j++)
                            {
                                pCBRenderer.Break[j] = cb[j + 1];
                                if (j == 0)
                                {
                                    pCBRenderer.Label[j] = " <= " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                else if (j == intBreaksCount - 2)
                                {
                                    pCBRenderer.Label[j] = " > " + Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1];
                                }
                                else
                                {
                                    pCBRenderer.Label[j] = Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1] + " ~ " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                pUIProperties.LowBreak[j] = cb[j];
                                pSimpleFillSym            = new SimpleFillSymbolClass();
                                IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]);
                                pSimpleFillSym.Color  = (IColor)pRGBColor;
                                pCBRenderer.Symbol[j] = (ISymbol)pSimpleFillSym;
                            }
                        }
                        else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            ISimpleMarkerSymbol pSimpleMarkerSym;

                            int[,] arrColors = CreateColorRamp();

                            //Add Probability Value Manually
                            string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" };
                            //' be careful, indices are different for the diff lists
                            for (int j = 0; j < intBreaksCount - 1; j++)
                            {
                                pCBRenderer.Break[j] = cb[j + 1];
                                if (j == 0)
                                {
                                    pCBRenderer.Label[j] = " <= " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                else if (j == intBreaksCount - 2)
                                {
                                    pCBRenderer.Label[j] = " > " + Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1];
                                }
                                else
                                {
                                    pCBRenderer.Label[j] = Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1] + " ~ " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j];
                                }
                                pUIProperties.LowBreak[j] = cb[j];
                                pSimpleMarkerSym          = new SimpleMarkerSymbolClass();
                                IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]);
                                pSimpleMarkerSym.Color = (IColor)pRGBColor;
                                pCBRenderer.Symbol[j]  = (ISymbol)pSimpleMarkerSym;
                            }
                        }


                        IFeatureLayer pNewFLayer = new FeatureLayerClass();
                        pNewFLayer.FeatureClass = m_pFClass;
                        pNewFLayer.Name         = cboSAM.Text + " of " + m_pFLayer.Name;
                        IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                        pGFLayer.Renderer = (IFeatureRenderer)pCBRenderer;
                        m_pActiveView.FocusMap.AddLayer(pGFLayer);
                        m_pActiveView.Refresh();
                        m_pForm.axTOCControl1.Update();
                    }
                    else
                    {
                        MessageBox.Show("Complete. The results are stored in the shape file");
                    }
                    #endregion
                }

                this.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 2
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);

            //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(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";
            }

            double[] dblLoclLisa = null;

            if (cboMeasure.Text == "Lee's L")
            {
                //pEngine.Evaluate("sample.result <- LARRY.bivariate.probability.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', sig.level=c(0.05), method='total', alternative='two.sided', diag.zero = " + strNonZero + ")");

                pEngine.Evaluate("sample.result <- LARRY.bivariate.probability.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', sig.level=c(0.05), method='" + cboMethod.Text + "', alternative='" + txtAlternative.Text + "', diag.zero = " + strNonZero + ")");
                dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$p.value)").AsNumeric().ToArray();
            }
            else if (cboMeasure.Text == "Local Pearson")
            {
                //pEngine.Evaluate("sample.result <- LARRY.bivariate.probability.pearson(sample.v1, sample.v2, 1:length(sample.nb), sig.levels=c(0.05), method='randomization', alternative='two.sided')");
                pEngine.Evaluate("sample.result <- LARRY.bivariate.probability.pearson(sample.v1, sample.v2, 1:length(sample.nb), sig.levels=c(0.05), method='" + cboMethod.Text + "', alternative='" + txtAlternative.Text + "')");
                dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$p.value)").AsNumeric().ToArray();
            }

            //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.esriFieldTypeDouble;
                    m_pFClass.AddField(newField);
                }
            }

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

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

            int featureIdx = 0;

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

                pFCursor.UpdateFeature(pFeature);

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

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

                pFCursor = m_pFClass.Search(null, false);
                IDataStatistics pDataStat = new DataStatisticsClass();
                pDataStat.Field  = strLocalLISAFldName;
                pDataStat.Cursor = (ICursor)pFCursor;

                IStatisticsResults pStatResults = pDataStat.Statistics;
                double             dblMax       = pStatResults.Maximum;
                double             dblMin       = pStatResults.Minimum;

                int      intBreaksCount = m_pBiLISASym.Length + 1;
                double[] cb             = new double[intBreaksCount];

                //Assign Min and Max values for class breaks

                for (int k = 0; k < intBreaksCount; k++)
                {
                    cb[k] = k * 0.1;
                }

                IClassBreaksRenderer pCBRenderer = new ClassBreaksRenderer();
                pCBRenderer.Field        = strLocalLISAFldName;
                pCBRenderer.BreakCount   = intBreaksCount - 1;
                pCBRenderer.MinimumBreak = cb[0];

                //' use this interface to set dialog properties
                IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pCBRenderer;
                pUIProperties.ColorRamp = "Custom";
                ISimpleFillSymbol pSimpleFillSym;

                for (int j = 0; j < intBreaksCount - 1; j++)
                {
                    pCBRenderer.Break[j] = cb[j + 1];
                    pCBRenderer.Label[j] = m_pBiLISASym[j].Label;

                    pUIProperties.LowBreak[j] = cb[j];
                    pSimpleFillSym            = new SimpleFillSymbolClass();
                    IRgbColor pRGBColor = m_pSnippet.getRGB(m_pBiLISASym[j].R, m_pBiLISASym[j].G, m_pBiLISASym[j].B);
                    pSimpleFillSym.Color  = (IColor)pRGBColor;
                    pCBRenderer.Symbol[j] = (ISymbol)pSimpleFillSym;
                }

                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = m_pFClass;
                pNewFLayer.Name         = lvFields.Items[0].SubItems[0].Text + " of " + m_pFLayer.Name;
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pCBRenderer;
                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");
            }
        }
Ejemplo n.º 3
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (clistFields.CheckedItems.Count == 0)
                {
                    MessageBox.Show("EV is not selected.");
                    return;
                }


                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Saving EVs:";;
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                pfrmProgress.lblStatus.Text = "Saving residuals and spatial filter:";

                for (int k = 0; k < clistFields.CheckedItems.Count; k++)
                {
                    int    i = clistFields.CheckedIndices[k];
                    string strEVfieldName = arrSelectedEvsNM[i];
                    pfrmProgress.lblStatus.Text = "Saving EV (" + strEVfieldName + ")";

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

                        if (dialogResult == DialogResult.No)
                        {
                            return;
                        }
                    }
                    IFeatureCursor pFCursor = m_pFClass.Update(null, false);
                    IFeature       pFeature = pFCursor.NextFeature();

                    int featureIdx  = 0;
                    int intValueIdx = m_pFClass.FindField(strEVfieldName);

                    while (pFeature != null)
                    {
                        //Update Residuals
                        pFeature.set_Value(intValueIdx, (object)arrSelectedEVs[featureIdx, i]);

                        pFCursor.UpdateFeature(pFeature);

                        pFeature = pFCursor.NextFeature();
                        featureIdx++;
                    }
                }
                pfrmProgress.Close();
                MessageBox.Show("Complete. The results are stored in the shape file");
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 4
0
        public void SaveOtherPolys()
        {
            int idFld     = m_OtherPolysFC.FindField("OtherPolys_ID");
            int unitFld   = m_OtherPolysFC.FindField("MapUnit");
            int idConfFld = m_OtherPolysFC.FindField("IdentityConfidence");
            int lblFld    = m_OtherPolysFC.FindField("Label");
            int notesFld  = m_OtherPolysFC.FindField("Notes");
            int dsFld     = m_OtherPolysFC.FindField("DataSourceID");
            int symFld    = m_OtherPolysFC.FindField("Symbol");

            IEditor theEditor = ArcMap.Editor;

            if (theEditor.EditState == esriEditState.esriStateNotEditing)
            {
                theEditor.StartEditing(m_theWorkspace);
            }
            theEditor.StartOperation();

            try
            {
                string         updateWhereClause = "OtherPolys_ID = '";
                IFeatureCursor insertCursor      = m_OtherPolysFC.Insert(true);

                foreach (KeyValuePair <string, OtherPoly> aDictionaryEntry in m_OtherPolysDictionary)
                {
                    OtherPoly thisOtherPoly = (OtherPoly)aDictionaryEntry.Value;
                    switch (thisOtherPoly.RequiresUpdate)
                    {
                    case true:
                        updateWhereClause += thisOtherPoly.OtherPolys_ID + "' OR OtherPolys_ID = '";
                        break;

                    case false:
                        IFeatureBuffer theFeatureBuffer = m_OtherPolysFC.CreateFeatureBuffer();
                        theFeatureBuffer.set_Value(idFld, thisOtherPoly.OtherPolys_ID);
                        theFeatureBuffer.set_Value(unitFld, thisOtherPoly.MapUnit);
                        theFeatureBuffer.set_Value(idConfFld, thisOtherPoly.IdentityConfidence);
                        theFeatureBuffer.set_Value(lblFld, thisOtherPoly.Label);
                        theFeatureBuffer.set_Value(notesFld, thisOtherPoly.Notes);
                        theFeatureBuffer.set_Value(dsFld, thisOtherPoly.DataSourceID);
                        theFeatureBuffer.set_Value(symFld, thisOtherPoly.Symbol);
                        theFeatureBuffer.Shape = thisOtherPoly.Shape;

                        insertCursor.InsertFeature(theFeatureBuffer);
                        break;
                    }
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(insertCursor);
                theEditor.StopOperation("Insert OtherPolys");

                if (updateWhereClause == "OtherPolys_ID = '")
                {
                    return;
                }

                theEditor.StartOperation();
                updateWhereClause = updateWhereClause.Remove(updateWhereClause.Length - 23);

                IQueryFilter QF = new QueryFilterClass();
                QF.WhereClause = updateWhereClause;

                IFeatureCursor updateCursor = m_OtherPolysFC.Update(QF, false);
                IFeature       theFeature   = updateCursor.NextFeature();

                while (theFeature != null)
                {
                    string theID = theFeature.get_Value(idFld).ToString();

                    OtherPoly thisOtherPoly = m_OtherPolysDictionary[theID];
                    theFeature.set_Value(unitFld, thisOtherPoly.MapUnit);
                    theFeature.set_Value(idConfFld, thisOtherPoly.IdentityConfidence);
                    theFeature.set_Value(lblFld, thisOtherPoly.Label);
                    theFeature.set_Value(notesFld, thisOtherPoly.Notes);
                    theFeature.set_Value(dsFld, thisOtherPoly.DataSourceID);
                    theFeature.set_Value(symFld, thisOtherPoly.Symbol);
                    theFeature.Shape = thisOtherPoly.Shape;
                    updateCursor.UpdateFeature(theFeature);

                    theFeature = updateCursor.NextFeature();
                }

                theEditor.StopOperation("Update OtherPolys");
            }
            catch { theEditor.StopOperation("OtherPolys Management Failure"); }
        }
Ejemplo n.º 5
0
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                //保存应急处置空间位置应急资源调度后
                IFeatureClass pFeatureClassDeptResult = pFeatureLayerDept.FeatureClass;
                IQueryFilter  pQueryFilterDeptResult  = new QueryFilterClass();
                pQueryFilterDeptResult.WhereClause = "FID=" + Convert.ToString(Convert.ToInt32(comboBox4.Text) - 1);
                IFeatureCursor pFeatureCursorDeptResult = pFeatureClassDeptResult.Update(pQueryFilterDeptResult, false);
                IFeature       pFeatureDeptResult       = pFeatureCursorDeptResult.NextFeature();

                //保存应急处置空间位置的图层
                List <IPoint> DeptpointList = new List <IPoint>();
                DeptpointList.Add(pFeatureDeptResult.Shape as IPoint);
                SaveVector.pointtoFeatureLayer(comboBox6.Text, DeptpointList, pFeatureLayerDept);

                //保存应急处置空间位置应急资源调度后
                while (pFeatureDeptResult != null)
                {
                    for (int i = 0; i < pEmergencyDeptResource.Count; i++)
                    {
                        pFeatureDeptResult.set_Value(pFeatureDeptResult.Fields.FindField(pEmergencyDeptResource[i].EmergencyDemandResourceName), pEmergencyDeptResource[i].EmergencyDemandResourceNumber);
                    }
                    pFeatureCursorDeptResult.UpdateFeature(pFeatureDeptResult);
                    pFeatureDeptResult = pFeatureCursorDeptResult.NextFeature();
                }

                //保存应急资源仓库应急资源数量
                IFeatureClass pFeatureClassDepotResult = pFeatureLayerDepot.FeatureClass;

                //定义应急资源仓库点的List
                List <IPoint> DepotpointList = new List <IPoint>();

                for (int j = 0; j < pEmergencyDepotResource.Count; j++)
                {
                    if (pEmergencyDepotResource[j].EmergencyDepotBool == true)
                    {
                        IQueryFilter pQueryFilterDepotResult = new QueryFilterClass();
                        pQueryFilterDepotResult.WhereClause = "Name=" + "'" + Convert.ToString(pEmergencyDepotResource[j].DepotName) + "'";
                        IFeatureCursor pFeatureCursorDepotResult = pFeatureClassDepotResult.Update(pQueryFilterDepotResult, false);
                        IFeature       pFeauteDepotResult        = pFeatureCursorDepotResult.NextFeature();

                        //将调度出的应急资源仓库点加载到List中
                        DepotpointList.Add(pFeauteDepotResult.Shape as IPoint);

                        while (pFeauteDepotResult != null)
                        {
                            for (int k = 0; k < pEmergencyDepotResource[j].EmergencyVarietyName.Length; k++)
                            {
                                pFeauteDepotResult.set_Value(pFeauteDepotResult.Fields.FindField(pEmergencyDepotResource[j].EmergencyVarietyName[k]), pEmergencyDepotResource[j].EmergencyVarietyNameNumber[k]);
                            }
                            pFeatureCursorDepotResult.UpdateFeature(pFeauteDepotResult);
                            pFeauteDepotResult = pFeatureCursorDepotResult.NextFeature();
                        }
                    }
                }
                //保存应急资源仓库数据
                SaveVector.pointtoFeatureLayer(comboBox5.Text, DepotpointList, pFeatureLayerDepot);
                MessageBox.Show("运行结束!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.ToString(), "异常");
            }
        }
Ejemplo n.º 6
0
        private static void calcStandMeans(IFeatureClass strataFtr, IFeatureClass standsFtr, int[] meanStrataFldIndex, int[] varStrataFldIndex, int[] countFldStrataIndex, IField[] fldsToSummarize, geoDatabaseUtility geoUtil)
        {
            int cnt = 0;

            int[] ptFldIndex   = new int[fldsToSummarize.Length];
            int[] meanFldIndex = new int[fldsToSummarize.Length];
            int[] varFldIndex  = new int[fldsToSummarize.Length];
            int[] cntFldIndex  = new int[fldsToSummarize.Length];
            foreach (IField fld in fldsToSummarize)
            {
                string sName = geoUtil.createField(standsFtr, "v_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                varFldIndex[cnt] = standsFtr.FindField(sName);
                string mName = geoUtil.createField(standsFtr, "m_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                meanFldIndex[cnt] = standsFtr.FindField(mName);
                string cName = geoUtil.createField(standsFtr, "n_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                cntFldIndex[cnt] = standsFtr.FindField(cName);
                cnt++;
            }
            IFeatureCursor uCur = standsFtr.Update(null, true);
            IFeature       uFtr = uCur.NextFeature();

            while (uFtr != null)
            {
                ESRI.ArcGIS.Geometry.IGeometry geo = uFtr.Shape;
                ISpatialFilter spFlt = new SpatialFilter();
                spFlt.Geometry   = geo;
                spFlt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                double         totalArea = 0;
                IFeatureCursor sCur      = strataFtr.Search(spFlt, true);
                IFeature       sFtr      = sCur.NextFeature();
                double[][]     vlArr     = new double[meanFldIndex.Length][];
                for (int i = 0; i < meanFldIndex.Length; i++)
                {
                    vlArr[i] = new double[3];
                }
                while (sFtr != null)
                {
                    ESRI.ArcGIS.Geometry.IGeometry             sgeo  = sFtr.Shape;
                    ESRI.ArcGIS.Geometry.ITopologicalOperator4 topo  = (ESRI.ArcGIS.Geometry.ITopologicalOperator4)sgeo;
                    ESRI.ArcGIS.Geometry.IGeometry             sgeo2 = topo.Intersect(geo, ESRI.ArcGIS.Geometry.esriGeometryDimension.esriGeometry2Dimension);
                    double subArea = (((ESRI.ArcGIS.Geometry.IArea)sgeo2).Area);
                    totalArea += subArea;
                    for (int i = 0; i < meanFldIndex.Length; i++)
                    {
                        vlArr[i][0] += System.Convert.ToDouble(sFtr.get_Value(meanStrataFldIndex[i])) * subArea;
                        vlArr[i][1] += System.Convert.ToDouble(sFtr.get_Value(varStrataFldIndex[i])) * subArea;
                        vlArr[i][2] += System.Convert.ToDouble(sFtr.get_Value(countFldStrataIndex[i]));
                    }
                    sFtr = sCur.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(sCur);
                if (totalArea != 0)
                {
                    for (int i = 0; i < meanFldIndex.Length; i++)
                    {
                        uFtr.set_Value(meanFldIndex[i], vlArr[i][0] / totalArea);
                        uFtr.set_Value(varFldIndex[i], vlArr[i][1] / totalArea);
                        uFtr.set_Value(cntFldIndex[i], vlArr[i][2]);
                    }
                    uCur.UpdateFeature(uFtr);
                }
                uFtr = uCur.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(uCur);
        }
Ejemplo n.º 7
0
        public void summarizeBiomass()
        {
            try
            {
                if (SubPlotField == null)
                {
                    SubPlotField = "";
                }
                //Console.WriteLine("Creating FIlling Plots Table");
                createAndFillPlotsTable();
                //Console.WriteLine("Creating And Filling Tree Ref Table");
                createAndFillTreesRef();
                //Console.WriteLine("Adding fields");
                //need to add in groups and update unSp
                addFields();
                if (regen)
                {
                    createAndFillRegenRef();
                    //System.Windows.Forms.MessageBox.Show(String.Join(", ", rgDic.Keys.ToArray()));
                    addRegenFields();
                }
                if (less5)
                {
                    addFields("s");
                }
                IQueryFilter   qryFlt   = new QueryFilterClass();
                string         nFldNm   = "";
                string         fldNm    = "";
                IFeatureCursor ftrCur   = SampleFeatureClass.Update(null, true);
                IFeature       ftr      = ftrCur.NextFeature();
                int            cnIndex  = ftrCur.FindField(PlotCnField);
                int            subIndex = ftrCur.FindField(SubPlotField);
                double         divs     = (43560 / (Math.PI * Math.Pow(24, 2)));
                double         rdivs    = (43560 / (Math.PI * Math.Pow(6.8, 2)));
                if (SubPlotField == "" || SubPlotField == null)
                {
                    divs  = divs / 4;
                    rdivs = rdivs / 4;
                }
                List <string> allEstFld = Enum.GetNames(typeof(biomassTypes)).ToList();
                while (ftr != null)
                {
                    string pCn = ftr.get_Value(cnIndex).ToString();
                    int    sPl = 0;
                    if (subIndex > -1)
                    {
                        sPl = System.Convert.ToInt32(ftr.get_Value(subIndex));
                    }
                    if (regen)
                    {
                        foreach (string rt in rUnSp)
                        {
                            string ky = pCn + "_" + sPl + "_" + rt;
                            int    rgCnt;
                            double cnt = 0;
                            if (rgDic.TryGetValue(ky, out rgCnt))
                            {
                                cnt = rdivs * rgCnt;
                            }
                            else
                            {
                                cnt = 0;
                            }
                            int rgIndex = ftr.Fields.FindField("RTPA_" + rt);
                            ftr.set_Value(rgIndex, cnt);
                        }
                    }
                    if (less5)
                    {
                        foreach (string t in sUnSp)                  //(biomassTypes s in fldArr)
                        {
                            string   ky = pCn + "_" + sPl + "_" + t; //CN_SubPlot_species
                            object[] vls;
                            if (sVlDic.TryGetValue(ky, out vls))
                            {
                            }
                            else
                            {
                                vls     = new object[12];
                                vls[0]  = pCn;
                                vls[1]  = sPl;
                                vls[2]  = t;
                                vls[3]  = 0; //MDBH
                                vls[4]  = 0; //AGB
                                vls[5]  = 0; //StemAGB
                                vls[6]  = 0; //ButtAGB
                                vls[7]  = 0; //FoliageAGB
                                vls[8]  = 0; //TopAGB
                                vls[9]  = 0; //BAA
                                vls[10] = 0; //TPA
                                vls[11] = 0; //MHT
                            }
                            foreach (biomassTypes s in fldArr)
                            {
                                string btStr      = s.ToString();
                                int    arrayIndex = allEstFld.IndexOf(btStr);
                                double sdivs2     = rdivs;
                                if (arrayIndex <= 1)
                                {
                                    arrayIndex = 9 + arrayIndex;
                                }
                                else
                                {
                                    if (arrayIndex <= 6)
                                    {
                                        arrayIndex = 2 + arrayIndex;
                                        sdivs2     = rdivs / 2000;//tons
                                    }
                                    else if (arrayIndex == 7)
                                    {
                                        arrayIndex = 3;
                                        double d = System.Convert.ToDouble(vls[10]);
                                        if (d < 1)
                                        {
                                            sdivs2 = 1;
                                        }
                                        else
                                        {
                                            sdivs2 = 1 / d;
                                        }
                                    }
                                    else
                                    {
                                        arrayIndex = 11;
                                        double d = System.Convert.ToDouble(vls[10]);
                                        if (d < 1)
                                        {
                                            sdivs2 = 1;
                                        }
                                        else
                                        {
                                            sdivs2 = 1 / d;
                                        }
                                    }
                                }

                                string spCd = vls[2].ToString();
                                fldNm = "s" + s + "_" + spCd;
                                //Console.WriteLine(fldNm);
                                int fldIndex = ftrCur.FindField(fldNm);
                                if (fldIndex == -1)
                                {
                                    fldIndex = ftrCur.FindField(nFldNm.Substring(0, 10));
                                }
                                object vl = (System.Convert.ToDouble(vls[arrayIndex])) * sdivs2;
                                ftr.set_Value(fldIndex, vl);
                            }
                        }
                    }

                    foreach (string t in unSp)                   //(biomassTypes s in fldArr)
                    {
                        string   ky = pCn + "_" + sPl + "_" + t; //CN_SubPlot_species
                        object[] vls;
                        if (vlDic.TryGetValue(ky, out vls))
                        {
                        }
                        else
                        {
                            vls     = new object[12];
                            vls[0]  = pCn;
                            vls[1]  = sPl;
                            vls[2]  = t;
                            vls[3]  = 0; //MDBH
                            vls[4]  = 0; //AGB
                            vls[5]  = 0; //StemAGB
                            vls[6]  = 0; //ButtAGB
                            vls[7]  = 0; //FoliageAGB
                            vls[8]  = 0; //TopAGB
                            vls[9]  = 0; //BAA
                            vls[10] = 0; //TPA
                            vls[11] = 0; //MHT
                        }
                        foreach (biomassTypes s in fldArr)
                        {
                            string btStr      = s.ToString();
                            int    arrayIndex = allEstFld.IndexOf(btStr);
                            double divs2      = divs;
                            if (arrayIndex <= 1)
                            {
                                arrayIndex = 9 + arrayIndex;
                            }
                            else
                            {
                                if (arrayIndex <= 6)
                                {
                                    arrayIndex = 2 + arrayIndex;
                                    divs2      = divs / 2000;//tons
                                }
                                else if (arrayIndex == 7)
                                {
                                    arrayIndex = 3;
                                    double d = System.Convert.ToDouble(vls[10]);
                                    if (d < 1)
                                    {
                                        divs2 = 1;
                                    }
                                    else
                                    {
                                        divs2 = 1 / d;
                                    }
                                }
                                else
                                {
                                    arrayIndex = 11;
                                    double d = System.Convert.ToDouble(vls[10]);
                                    if (d < 1)
                                    {
                                        divs2 = 1;
                                    }
                                    else
                                    {
                                        divs2 = 1 / d;
                                    }
                                }
                            }

                            string spCd = vls[2].ToString();
                            fldNm = s + "_" + spCd;
                            //Console.WriteLine(fldNm);
                            int fldIndex = ftrCur.FindField(fldNm);
                            if (fldIndex == -1)
                            {
                                fldIndex = ftrCur.FindField(nFldNm.Substring(0, 10));
                            }
                            object vl = (System.Convert.ToDouble(vls[arrayIndex])) * divs2;
                            ftr.set_Value(fldIndex, vl);
                        }
                    }
                    ftrCur.UpdateFeature(ftr);
                    ftr = ftrCur.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ftrCur);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                //System.Environment.OSVersion.
                if (av == "0.0" || ev == "0.0")
                {
                    System.Windows.Forms.MessageBox.Show("You do not have OleDB 12.0 installed. Please download and install Office 2007 data provider from:\nhttp://www.microsoft.com/en-us/download/confirmation.aspx?id=23734", "No data provider found", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                }
                else
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
Ejemplo n.º 8
0
        public static void summarizeBiomassPolygon(IFeatureClass pointFtr, IField[] fldsToSummarize, IFeatureClass strataFtr, IFeatureClass standsFtr = null, geoDatabaseUtility geoUtil = null)
        {
            if (geoUtil == null)
            {
                geoUtil = new geoDatabaseUtility();
            }
            int cnt = 0;

            int[] ptFldIndex   = new int[fldsToSummarize.Length];
            int[] meanFldIndex = new int[fldsToSummarize.Length];
            int[] varFldIndex  = new int[fldsToSummarize.Length];
            int[] cntFldIndex  = new int[fldsToSummarize.Length];
            foreach (IField fld in fldsToSummarize)
            {
                ptFldIndex[cnt] = pointFtr.FindField(fld.Name);
                string sName = geoUtil.createField(strataFtr, "v_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                varFldIndex[cnt] = strataFtr.FindField(sName);
                string mName = geoUtil.createField(strataFtr, "m_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                meanFldIndex[cnt] = strataFtr.FindField(mName);
                string cntName = geoUtil.createField(strataFtr, "n_" + fld.Name, esriFieldType.esriFieldTypeInteger, false);
                cntFldIndex[cnt] = strataFtr.FindField(cntName);
                cnt++;
            }
            IFeatureCursor uCur = strataFtr.Update(null, true);
            IFeature       uFtr = uCur.NextFeature();

            while (uFtr != null)
            {
                ISpatialFilter sFilt = new SpatialFilter();
                sFilt.Geometry   = uFtr.Shape;
                sFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                double[][] fldVlsArr = new double[fldsToSummarize.Length][];
                for (int i = 0; i < fldsToSummarize.Length; i++)
                {
                    fldVlsArr[i] = new double[3];
                }
                IFeatureCursor psCur = pointFtr.Search(sFilt, true);
                IFeature       psFtr = psCur.NextFeature();

                while (psFtr != null)
                {
                    for (int i = 0; i < ptFldIndex.Length; i++)
                    {
                        int    indexVl = ptFldIndex[i];
                        object objVl   = psFtr.get_Value(indexVl);
                        if (objVl != null)
                        {
                            double vl  = System.Convert.ToDouble(objVl);
                            double vl2 = vl * vl;
                            fldVlsArr[i][0] += vl;
                            fldVlsArr[i][1] += vl2;
                            fldVlsArr[i][2] += 1;
                        }
                    }
                    psFtr = psCur.NextFeature();
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(psCur);
                for (int i = 0; i < ptFldIndex.Length; i++)
                {
                    double s        = fldVlsArr[i][0];
                    double s2       = fldVlsArr[i][1];
                    double n        = fldVlsArr[i][2];
                    double mean     = s / n;                                 //mean
                    double var      = (s2 - (Math.Pow(s, 2) / n)) / (n - 1); //variance
                    int    mIndex   = meanFldIndex[i];
                    int    vIndex   = varFldIndex[i];
                    int    cntIndex = cntFldIndex[i];
                    uFtr.set_Value(mIndex, mean);
                    uFtr.set_Value(vIndex, var);
                    uFtr.set_Value(cntIndex, n);
                }
                uCur.UpdateFeature(uFtr);
                uFtr = uCur.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(uCur);
            if (standsFtr != null)
            {
                calcStandMeans(strataFtr, standsFtr, meanFldIndex, varFldIndex, cntFldIndex, fldsToSummarize, geoUtil);
            }
        }
Ejemplo n.º 9
0
        public static void summarizeBiomassPolygon(IFeatureClass pointFtr, IField[] fldsToSummarize, IFunctionRasterDataset strataRaster, IFeatureClass standsFtr, geoDatabaseUtility geoUtil = null, rasterUtil rsUtil = null)
        {
            if (geoUtil == null)
            {
                geoUtil = new geoDatabaseUtility();
            }
            if (rsUtil == null)
            {
                rsUtil = new rasterUtil();
            }
            int cnt = 0;
            //need to work on calculating N
            Dictionary <string, double[][]> vlDic = getDictionaryValues(pointFtr, fldsToSummarize, strataRaster, geoUtil, rsUtil); //Strata: SummaryFields [{sum,sum2,cnt},...]

            int[] meanFldIndex = new int[fldsToSummarize.Length];
            int[] varFldIndex  = new int[fldsToSummarize.Length];
            int[] cntFldIndex  = new int[fldsToSummarize.Length];
            //string cntName = geoUtil.createField(standsFtr, "n", esriFieldType.esriFieldTypeInteger, false);
            //int cntIndex = standsFtr.FindField(cntName);
            foreach (IField fld in fldsToSummarize)
            {
                string sName = geoUtil.createField(standsFtr, "v_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                varFldIndex[cnt] = standsFtr.FindField(sName);
                string mName = geoUtil.createField(standsFtr, "m_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                meanFldIndex[cnt] = standsFtr.FindField(mName);
                string cntName = geoUtil.createField(standsFtr, "n_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                cntFldIndex[cnt] = standsFtr.FindField(cntName);
                cnt++;
            }
            IFeatureCursor uCur = standsFtr.Update(null, true);
            IFeature       uFtr = uCur.NextFeature();

            while (uFtr != null)
            {
                ESRI.ArcGIS.Geometry.IGeometry geo = uFtr.Shape;
                IFunctionRasterDataset         cRs = rsUtil.clipRasterFunction(strataRaster, geo, esriRasterClippingType.esriRasterClippingOutside);
                //Console.WriteLine("Clipping raster");
                Dictionary <string, double> rsStrataPropDic = getStrataProportion(cRs, rsUtil); //Strata: proportion of area
                //int tn = 0;
                //double[] tn = new double[meanFldIndex.Length];
                double[][] updateValuesArr = new double[meanFldIndex.Length][];
                for (int i = 0; i < meanFldIndex.Length; i++)
                {
                    updateValuesArr[i] = new double[3];
                }
                foreach (KeyValuePair <string, double> kvp in rsStrataPropDic)
                {
                    string stratum    = kvp.Key;
                    double proportion = kvp.Value;
                    //Console.WriteLine(stratum + " = " + proportion.ToString());
                    double[][] vlDicArr;
                    if (vlDic.TryGetValue(stratum, out vlDicArr))
                    {
                        //double n = vlDicArr[0][2];
                        //tn += System.Convert.ToInt32(n);
                        for (int i = 0; i < meanFldIndex.Length; i++)
                        {
                            double[] dArr = vlDicArr[i];
                            double   n    = dArr[2];
                            //tn[i] += n;
                            double s  = dArr[0];
                            double s2 = dArr[1];
                            updateValuesArr[i][0] += (s / n) * proportion;                             //mean
                            updateValuesArr[i][1] += (s2 - Math.Pow(s, 2) / n) / (n - 1) * proportion; //variance
                            updateValuesArr[i][2] += n;
                        }
                    }
                }
                //uFtr.set_Value(cntIndex, tn);
                for (int i = 0; i < meanFldIndex.Length; i++)
                {
                    uFtr.set_Value(meanFldIndex[i], updateValuesArr[i][0]);
                    uFtr.set_Value(varFldIndex[i], updateValuesArr[i][1]);
                    uFtr.set_Value(cntFldIndex[i], updateValuesArr[i][2]);
                }
                uCur.UpdateFeature(uFtr);
                uFtr = uCur.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(uCur);
        }
Ejemplo n.º 10
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            frmProgress pfrmProgress = new frmProgress();
            pfrmProgress.lblStatus.Text = "Collecting Data:";
            pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
            pfrmProgress.Show();

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

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


            clsSnippet pSnippet = new clsSnippet();

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

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

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

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

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

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

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

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

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

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

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

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

            pfrmProgress.lblStatus.Text = "Finding Clusters";

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

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

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

            //Save Outputs in SHP

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

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

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

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


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

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

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

                    pFCursor.UpdateFeature(pFeature);

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

                MessageBox.Show("Residuals are stored in the shape file");
            }
        private void RecalDistance(IFeatureCursor ThisCursor, ref int UpdateCount, ref string ErrorMessage)
        {
            IFeature ThisFeature, TransectFFeature;
            string TransectID, SurveyID;
            IFeatureClass TransLinesFC;
            IFeatureCursor TransectFCursor;
            int TransectIDIndex = 0, DistanceFieldIndex = 0, SurveyIDIndex = 0;
            IQueryFilter qFilter;
            ICurve ThisCurve;
            IPoint ThisPoint, pOutPoint = null;
            double DistanceAlongCurve = 0, DistanceFromCurve = 0, ClosestDistance = 0;
            bool RightSide = false, FirstRecord = false;

            UpdateCount = 0;

            //make sure we got the  transect lines featureclass
            TransLinesFC = Util.GetFeatureClass(m_NPS.LYR_TRACKLOG, m_NPS.Workspace, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false)
                return;

            //get first record
            ThisFeature = ThisCursor.NextFeature();

            //if we have no feature here then the recordset is empty
            if (ThisFeature == null)
            {
                ThisCursor = null;
                return;
            }

            //make sure we have the transect field
            if (string.IsNullOrEmpty(ErrorMessage))
            {
                TransectIDIndex = ThisFeature.Fields.FindField("TransectID");
                if (TransectIDIndex < 0) ErrorMessage = "No transect id field found.";

            }

            //make sure we have the transect field
            if (string.IsNullOrEmpty(ErrorMessage))
            {
                SurveyIDIndex = ThisFeature.Fields.FindField("SurveyID");
                if (SurveyIDIndex < 0) ErrorMessage = "No survey id field found.";

            }

            //make sure we have a distance field
            if (string.IsNullOrEmpty(ErrorMessage))
            {
                DistanceFieldIndex = ThisFeature.Fields.FindField("DIST2TRANS");
                if (DistanceFieldIndex < 0) DistanceFieldIndex = ThisFeature.Fields.FindField("DistToSeg");
                if (DistanceFieldIndex < 0) ErrorMessage = "No distance field found.";
            }

            //things not okay so abort
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ThisCursor = null;
                return;
            }

            //loop through each feature, get it's transect segments and find the nearest one
            do
            {

                //get transect id for feature
                TransectID = (string)Util.SafeConvert(ThisFeature.get_Value(TransectIDIndex), typeof(string));
                if (string.IsNullOrEmpty(TransectID)) continue;

                //get survey id for feature
                SurveyID = (string)Util.SafeConvert(ThisFeature.get_Value(SurveyIDIndex), typeof(string));
                if (string.IsNullOrEmpty(SurveyID)) continue;

                //get point shape
                ThisPoint = ThisFeature.ShapeCopy as IPoint;

                //get all segments on transect
                qFilter = new QueryFilterClass();
                qFilter.WhereClause = "TransectID=" + TransectID + " and SurveyID=" + SurveyID
                    + " and SegType='OnTransect'";
                TransectFCursor = TransLinesFC.Search(qFilter, false);

                ClosestDistance = 0;
                FirstRecord = true;

                //check the distance of all segments and get the one nearest to the feature
                while ((TransectFFeature = TransectFCursor.NextFeature()) != null)
                {

                    ThisCurve = TransectFFeature.ShapeCopy as ICurve;

                    int segID = (int)Util.SafeConvert(TransectFFeature.get_Value(
                        TransectFFeature.Fields.FindField("SegmentID")),typeof(int));

                    //determine the distance between the two
                    if (ThisCurve != null && ThisPoint != null)
                    {
                        ThisCurve.QueryPointAndDistance(esriSegmentExtension.esriNoExtension, ThisPoint, false, pOutPoint,
                            ref DistanceAlongCurve, ref DistanceFromCurve, ref RightSide);
                    }

                    //if this is the first record then the first distance is the currently closest distance
                    if (FirstRecord == true)
                    {
                        ClosestDistance = DistanceFromCurve;
                        FirstRecord = false;
                    }

                    //if the current distance is less than the last distance, it now becomes the closest distance
                    if (DistanceFromCurve < ClosestDistance)
                        ClosestDistance = DistanceFromCurve;

                }

                //release transect cursor
                TransectFCursor = null;

                //if first record is still true then there were no transects to check for distance so don't update
                if (FirstRecord == false)
                {

                    UpdateCount = UpdateCount + 1;

                    //update the feature with the closest distance
                    ThisFeature.set_Value(DistanceFieldIndex, ClosestDistance);

                    //save new distance value
                    ThisCursor.UpdateFeature(ThisFeature);

                }

            } while ((ThisFeature = ThisCursor.NextFeature()) != null);
        }
        public void SaveDataSourcePolys()
        {
            int idFld    = m_DataSourcePolysFC.FindField("DataSourcePolys_ID");
            int notesFld = m_DataSourcePolysFC.FindField("Notes");
            int dsFld    = m_DataSourcePolysFC.FindField("DataSourceID");

            IEditor theEditor = ArcMap.Editor;

            if (theEditor.EditState == esriEditState.esriStateNotEditing)
            {
                theEditor.StartEditing(m_theWorkspace);
            }
            theEditor.StartOperation();

            try
            {
                string         updateWhereClause = "DataSourcePolys_ID = '";
                IFeatureCursor insertCursor      = m_DataSourcePolysFC.Insert(true);

                foreach (KeyValuePair <string, DataSourcePoly> aDictionaryEntry in m_DataSourcePolysDictionary)
                {
                    DataSourcePoly thisDataSourcePoly = (DataSourcePoly)aDictionaryEntry.Value;
                    switch (thisDataSourcePoly.RequiresUpdate)
                    {
                    case true:
                        updateWhereClause += thisDataSourcePoly.DataSourcePolys_ID + "' OR DataSourcePolys_ID = '";
                        break;

                    case false:
                        IFeatureBuffer theFeatureBuffer = m_DataSourcePolysFC.CreateFeatureBuffer();
                        theFeatureBuffer.set_Value(idFld, thisDataSourcePoly.DataSourcePolys_ID);
                        theFeatureBuffer.set_Value(notesFld, thisDataSourcePoly.Notes);
                        theFeatureBuffer.set_Value(dsFld, thisDataSourcePoly.DataSourceID);
                        theFeatureBuffer.Shape = thisDataSourcePoly.Shape;

                        insertCursor.InsertFeature(theFeatureBuffer);
                        break;
                    }
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(insertCursor);
                theEditor.StopOperation("Insert DataSourcePolys");

                if (updateWhereClause == "DataSourcePolys_ID = '")
                {
                    return;
                }

                theEditor.StartOperation();
                updateWhereClause = updateWhereClause.Remove(updateWhereClause.Length - 25);

                IQueryFilter QF = new QueryFilterClass();
                QF.WhereClause = updateWhereClause;

                IFeatureCursor updateCursor = m_DataSourcePolysFC.Update(QF, false);
                IFeature       theFeature   = updateCursor.NextFeature();

                while (theFeature != null)
                {
                    string theID = theFeature.get_Value(idFld).ToString();

                    DataSourcePoly thisDataSourcePoly = m_DataSourcePolysDictionary[theID];
                    theFeature.set_Value(notesFld, thisDataSourcePoly.Notes);
                    theFeature.set_Value(dsFld, thisDataSourcePoly.DataSourceID);
                    //theFeature.Shape = thisDataSourcePoly.Shape; Adjusting the shape of the feature triggers annotations to be re-placed. No me gusta.
                    updateCursor.UpdateFeature(theFeature);

                    theFeature = updateCursor.NextFeature();
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor);
                theEditor.StopOperation("Update DataSourcePolys");
            }
            catch { theEditor.StopOperation("DataSourcePolys Management Failure"); }
        }