Ejemplo n.º 1
0
        private void frmSaveESFFull_Load(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Creating EVs:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                m_pEngine.Evaluate("sample.n <- length(sample.nb)");
                m_pEngine.Evaluate("sample.listb <- nb2listw(sample.nb, style='B')");
                m_pEngine.Evaluate("B <- listw2mat(sample.listb); M <- diag(sample.n) - matrix(1/sample.n, sample.n, sample.n); MBM <- M%*%B%*%M");
                m_pEngine.Evaluate("eig <- eigen(MBM)");

                nmEVs    = m_pEngine.Evaluate("eig$vectors").AsNumericMatrix();
                cvEVName = m_pEngine.Evaluate("paste('EV', 1:sample.n, sep='')").AsCharacter();
                nvEValue = m_pEngine.Evaluate("eig$values").AsNumeric();

                intNEVs = nmEVs.RowCount;


                for (int i = 0; i < intNEVs; i++)
                {
                    string strItemName = cvEVName[i] + " (" + Math.Round(nvEValue[i], 3).ToString() + ")";
                    clistFields.Items.Add(strItemName);
                }
                //m_pEngine.Evaluate("rm(list = ls(all = TRUE))"); //Remove all items from memory.
                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 2
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            frmProgress pfrmProgress = new frmProgress();

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

            pFlayer.FeatureClass = m_pFClass;

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

            if (strNameR == null)
            {
                return;
            }

            int intSuccess = 0;

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

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

            if (intSuccess == 0)
            {
                return;
            }

            blnSWMCreation = true;
            pfrmProgress.Close();
            this.Close();
        }
Ejemplo n.º 3
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

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

            REngine pEngine = m_pForm.pEngine;

            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 strRSigLv = nudRsigLv.Value.ToString();
            //string strLSigLv = nudLsigLv.Value.ToString();
            //string strLSig = cboLocalL.Text;
            //string strRsig = cboLocalPearson.Text;
            //string strRowStd = cboRowStandardization.Text;
            //string strMaxRanges = nudMaxRange.Value.ToString();
            //string strHigherOrder = cboHigherOrder.Text;
            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.LISA.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', diag.zero = " + strNonZero + ")");
                dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$local.L)").AsNumeric().ToArray();
            }
            else if (cboMeasure.Text == "Local Pearson")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.LISA.pearson(sample.v1, sample.v2, 1:length(sample.nb))");

                if (cboMapOption.Text == "Local Pearson")
                {
                    dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$local.pearson)").AsNumeric().ToArray();
                }
                else if (cboMapOption.Text == "z-score of variable 1")
                {
                    dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$z.x)").AsNumeric().ToArray();
                }
                else if (cboMapOption.Text == "z-score of variable 2")
                {
                    dblLoclLisa = pEngine.Evaluate("as.numeric(sample.result$z.y)").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
                cb[0] = dblMin;
                cb[intBreaksCount - 1] = dblMax;

                for (int k = 0; k < intBreaksCount - 2; k++)
                {
                    cb[k + 1] = m_pBiLISASym[k].UValue;
                }

                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;

                //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];
                    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.º 4
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                if (cboFieldName.Text == "")
                {
                    MessageBox.Show("Please select the dependent input variables to be used in the regression model.",
                                    "Please choose at least one input variable");
                }
                if (lstIndeVar.Items.Count == 0)
                {
                    MessageBox.Show("Please select independents input variables to be used in the regression model.",
                                    "Please choose at least one input variable");
                }
                //Decimal places
                int intDeciPlaces = 5;

                //Get number of Independent variables
                int nIndevarlistCnt = lstIndeVar.Items.Count;
                //Indicate an intercept only model (2) or a non-intercept model (1) or not (0)
                int intInterceptModel = 1;
                for (int j = 0; j < nIndevarlistCnt; j++)
                {
                    if ((string)lstIndeVar.Items[j] == "Intercept")
                    {
                        intInterceptModel = 0;
                    }
                }
                if (nIndevarlistCnt == 1 && intInterceptModel == 0)
                {
                    intInterceptModel = 2;
                }

                int nIDepen = 0;
                if (intInterceptModel == 0)
                {
                    nIDepen = nIndevarlistCnt - 1;
                }
                else if (intInterceptModel == 1)
                {
                    nIDepen = nIndevarlistCnt;
                }

                // Gets the column of the dependent variable
                String dependentName = (string)cboFieldName.SelectedItem;
                //sourceTable.AcceptChanges();
                //DataTable dependent = sourceTable.DefaultView.ToTable(false, dependentName);

                // Gets the columns of the independent variables
                String[] independentNames   = new string[nIDepen];
                int      intIdices          = 0;
                string   strIndependentName = "";
                for (int j = 0; j < nIndevarlistCnt; j++)
                {
                    strIndependentName = (string)lstIndeVar.Items[j];
                    if (strIndependentName != "Intercept")
                    {
                        independentNames[intIdices] = strIndependentName;
                        intIdices++;
                    }
                }

                int nFeature = m_pFClass.FeatureCount(null);

                //Warning for method
                if (rbtEigen.Checked)
                {
                    if (nFeature > m_pForm.intWarningCount)
                    {
                        DialogResult dialogResult = MessageBox.Show("It might take a lot of time. Do you want to continue?", "Warning", MessageBoxButtons.YesNo);

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

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

                //Get index for independent and dependent variables
                int   intDepenIdx = m_pFLayer.FeatureClass.Fields.FindField(dependentName);
                int[] idxes       = new int[nIDepen];

                for (int j = 0; j < nIDepen; j++)
                {
                    idxes[j] = m_pFLayer.FeatureClass.Fields.FindField(independentNames[j]);
                }


                //Store independent values at Array
                double[]   arrDepen   = new double[nFeature];
                double[][] arrInDepen = new double[nIDepen][]; //Zigzaged Array needs to be define

                for (int j = 0; j < nIDepen; j++)
                {
                    arrInDepen[j] = new double[nFeature];
                }

                int i = 0;
                while (pFeature != null)
                {
                    arrDepen[i] = Convert.ToDouble(pFeature.get_Value(intDepenIdx));

                    for (int j = 0; j < nIDepen; j++)
                    {
                        arrInDepen[j][i] = Convert.ToDouble(pFeature.get_Value(idxes[j]));
                    }

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

                //Dependent variable to R vector
                NumericVector vecDepen = m_pEngine.CreateNumericVector(arrDepen);
                m_pEngine.SetSymbol(dependentName, vecDepen);
                if (rbtError.Checked)
                {
                    plotCommmand.Append("errorsarlm(" + dependentName + "~");
                }
                else if (rbtLag.Checked || rbtDurbin.Checked)
                {
                    plotCommmand.Append("lagsarlm(" + dependentName + "~");
                }
                else
                {
                    plotCommmand.Append("spautolm(" + dependentName + "~");
                }

                if (intInterceptModel == 2)
                {
                    plotCommmand.Append("1");
                }
                else
                {
                    for (int j = 0; j < nIDepen; j++)
                    {
                        //double[] arrVector = arrInDepen.GetColumn<double>(j);
                        NumericVector vecIndepen = m_pEngine.CreateNumericVector(arrInDepen[j]);
                        m_pEngine.SetSymbol(independentNames[j], vecIndepen);
                        plotCommmand.Append(independentNames[j] + "+");
                    }
                    plotCommmand.Remove(plotCommmand.Length - 1, 1);

                    if (intInterceptModel == 1)
                    {
                        plotCommmand.Append("-1");
                    }
                }

                //Select Method
                if (rbtEigen.Checked)
                {
                    plotCommmand.Append(", method='eigen'");
                }
                else if (rbtMatrix.Checked)
                {
                    plotCommmand.Append(", method='Matrix'");
                }
                else if (rbtMatrixJ.Checked)
                {
                    plotCommmand.Append(", method='Matrix_J'");
                }
                else if (rbtLU.Checked)
                {
                    plotCommmand.Append(", method='LU'");
                }
                else if (rbtChebyshev.Checked)
                {
                    plotCommmand.Append(", method='Chebyshev'");
                }
                else if (rbtMC.Checked)
                {
                    plotCommmand.Append(", method='MC'");
                }
                else
                {
                    plotCommmand.Append(", method='eigen'");
                }

                if (rbtError.Checked)
                {
                    plotCommmand.Append(", listw=sample.listw,  tol.solve=1.0e-20, zero.policy=TRUE)");
                }
                else if (rbtLag.Checked)
                {
                    plotCommmand.Append(", listw=sample.listw,  tol.solve=1.0e-20, zero.policy=TRUE)");
                }
                else if (rbtCAR.Checked)
                {
                    plotCommmand.Append(", listw=sample.listw, family='CAR', verbose=TRUE, zero.policy=TRUE)");
                }
                else if (rbtSMA.Checked)
                {
                    plotCommmand.Append(", listw=sample.listw, family='SMA', verbose=TRUE, zero.policy=TRUE)");
                }
                else if (rbtDurbin.Checked)
                {
                    plotCommmand.Append(", type='mixed', listw=sample.listw,  tol.solve=1.0e-20, zero.policy=TRUE)");
                }
                else
                {
                    return;
                }

                try
                {
                    m_pEngine.Evaluate("sum.lm <- summary(" + plotCommmand.ToString() + ", Nagelkerke=T)");
                }
                catch
                {
                    MessageBox.Show("Cannot solve the regression. Try again with different variables.");
                    pfrmProgress.Close();
                    return;
                }

                //Collect results from R
                NumericMatrix matCoe = m_pEngine.Evaluate("as.matrix(sum.lm$Coef)").AsNumericMatrix();

                double dblLRLambda = m_pEngine.Evaluate("as.numeric(sum.lm$LR1$statistic)").AsNumeric().First();
                double dblpLambda  = m_pEngine.Evaluate("as.numeric(sum.lm$LR1$p.value)").AsNumeric().First();

                double dblLRErrorModel = m_pEngine.Evaluate("as.numeric(sum.lm$LR1$estimate)").AsNumeric().First();

                double dblSigmasquared = 0;
                double dblAIC          = 0;
                double dblWald         = 0;
                double dblpWald        = 0;

                if (rbtLag.Checked || rbtError.Checked || rbtDurbin.Checked)
                {
                    dblSigmasquared = m_pEngine.Evaluate("as.numeric(sum.lm$s2)").AsNumeric().First();
                    //dblAIC = pEngine.Evaluate("as.numeric(sum.lm$AIC_lm.model)").AsNumeric().First();
                    dblWald  = m_pEngine.Evaluate("as.numeric(sum.lm$Wald1$statistic)").AsNumeric().First();
                    dblpWald = m_pEngine.Evaluate("as.numeric(sum.lm$Wald1$p.value)").AsNumeric().First();

                    double dblParaCnt = m_pEngine.Evaluate("as.numeric(sum.lm$parameters)").AsNumeric().First();
                    dblAIC = (2 * dblParaCnt) - (2 * dblLRErrorModel);
                }
                else
                {
                    dblSigmasquared = m_pEngine.Evaluate("as.numeric(sum.lm$fit$s2)").AsNumeric().First();
                    double dblParaCnt = m_pEngine.Evaluate("as.numeric(sum.lm$parameters)").AsNumeric().First();
                    dblAIC = (2 * dblParaCnt) - (2 * dblLRErrorModel);
                }

                double dblLambda    = 0;
                double dblSELambda  = 0;
                double dblResiAuto  = 0;
                double dblResiAutoP = 0;

                if (rbtLag.Checked || rbtDurbin.Checked)
                {
                    dblLambda    = m_pEngine.Evaluate("as.numeric(sum.lm$rho)").AsNumeric().First();
                    dblSELambda  = m_pEngine.Evaluate("as.numeric(sum.lm$rho.se)").AsNumeric().First();
                    dblResiAuto  = m_pEngine.Evaluate("as.numeric(sum.lm$LMtest)").AsNumeric().First();
                    dblResiAutoP = m_pEngine.Evaluate("as.numeric(sum.lm$rho.se)").AsNumeric().First();
                }
                else
                {
                    dblLambda   = m_pEngine.Evaluate("as.numeric(sum.lm$lambda)").AsNumeric().First();
                    dblSELambda = m_pEngine.Evaluate("as.numeric(sum.lm$lambda.se)").AsNumeric().First();
                }

                double dblRsquared = 0;
                //Previous method
                //if(intInterceptModel != 1)
                //    dblRsquared = m_pEngine.Evaluate("as.numeric(sum.lm$NK)").AsNumeric().First();

                //New pseduo R squared calculation
                if (rbtError.Checked || rbtLag.Checked || rbtDurbin.Checked)
                {
                    dblRsquared = m_pEngine.Evaluate("summary(lm(sum.lm$y~sum.lm$fitted.values))$r.squared").AsNumeric().First();
                }
                else
                {
                    dblRsquared = m_pEngine.Evaluate("summary(lm(sum.lm$Y~sum.lm$fit$fitted.values))$r.squared").AsNumeric().First();
                }


                //Open Ouput form
                frmRegResult pfrmRegResult = new frmRegResult();
                if (rbtError.Checked)
                {
                    pfrmRegResult.Text = "Spatial Autoregressive Model Summary (Error Model)";
                }
                else if (rbtLag.Checked)
                {
                    pfrmRegResult.Text = "Spatial Autoregressive Model Summary (Lag Model)";
                }
                else if (rbtCAR.Checked)
                {
                    pfrmRegResult.Text = "Spatial Autoregressive Model Summary (CAR Model)";
                }
                else if (rbtDurbin.Checked)
                {
                    pfrmRegResult.Text = "Spatial Autoregressive Model Summary (Spatial Durbin Model)";
                }
                else
                {
                    pfrmRegResult.Text = "Spatial Autoregressive Model Summary (SMA Model)";
                }

                //pfrmRegResult.panel2.Visible = true;
                //Create DataTable to store Result
                System.Data.DataTable tblRegResult = new DataTable("SRResult");

                //Assign DataTable
                DataColumn dColName = new DataColumn();
                dColName.DataType   = System.Type.GetType("System.String");
                dColName.ColumnName = "Name";
                tblRegResult.Columns.Add(dColName);

                DataColumn dColValue = new DataColumn();
                dColValue.DataType   = System.Type.GetType("System.Double");
                dColValue.ColumnName = "Estimate";
                tblRegResult.Columns.Add(dColValue);

                DataColumn dColSE = new DataColumn();
                dColSE.DataType   = System.Type.GetType("System.Double");
                dColSE.ColumnName = "Std. Error";
                tblRegResult.Columns.Add(dColSE);
                String.Format("{0:0.##}", tblRegResult.Columns["Std. Error"]);

                DataColumn dColTValue = new DataColumn();
                dColTValue.DataType   = System.Type.GetType("System.Double");
                dColTValue.ColumnName = "z value";
                tblRegResult.Columns.Add(dColTValue);

                DataColumn dColPvT = new DataColumn();
                dColPvT.DataType   = System.Type.GetType("System.Double");
                dColPvT.ColumnName = "Pr(>|z|)";
                tblRegResult.Columns.Add(dColPvT);

                //if (rbtDurbin.Checked)
                //    nIDepen = nIDepen * 2;

                int intNCoeff = matCoe.RowCount;

                //Store Data Table by R result
                for (int j = 0; j < intNCoeff; j++)
                {
                    DataRow pDataRow = tblRegResult.NewRow();
                    if (j == 0 && intInterceptModel != 1)
                    {
                        pDataRow["Name"] = "(Intercept)";
                    }
                    else if (intInterceptModel == 1)
                    {
                        if (rbtDurbin.Checked)
                        {
                            if (j <= intNCoeff / 2)
                            {
                                pDataRow["Name"] = independentNames[j];
                            }
                            else
                            {
                                pDataRow["Name"] = "lag." + independentNames[j - (intNCoeff / 2)];
                            }
                        }
                        else
                        {
                            pDataRow["Name"] = independentNames[j];
                        }
                    }
                    else
                    {
                        if (rbtDurbin.Checked)
                        {
                            if (j <= intNCoeff / 2)
                            {
                                pDataRow["Name"] = independentNames[j - 1];
                            }
                            else
                            {
                                pDataRow["Name"] = "lag." + independentNames[j - (intNCoeff / 2) - 1];
                            }
                        }
                        else
                        {
                            pDataRow["Name"] = independentNames[j - 1];
                        }
                    }
                    pDataRow["Estimate"]   = Math.Round(matCoe[j, 0], intDeciPlaces);
                    pDataRow["Std. Error"] = Math.Round(matCoe[j, 1], intDeciPlaces);
                    pDataRow["z value"]    = Math.Round(matCoe[j, 2], intDeciPlaces);
                    pDataRow["Pr(>|z|)"]   = Math.Round(matCoe[j, 3], intDeciPlaces);


                    tblRegResult.Rows.Add(pDataRow);
                }

                //Assign Datagridview to Data Table
                pfrmRegResult.dgvResults.DataSource = tblRegResult;

                //Assign values at Textbox
                string   strDecimalPlaces = "N" + intDeciPlaces.ToString();
                string[] strResults       = new string[5];
                if (rbtLag.Checked || rbtDurbin.Checked)
                {
                    if (dblpLambda < 0.001)
                    {
                        strResults[0] = "rho: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value < 0.001";
                    }
                    else if (dblpLambda > 0.999)
                    {
                        strResults[0] = "rho: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value > 0.999";
                    }
                    else
                    {
                        strResults[0] = "rho: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces);
                    }

                    if (dblpWald < 0.001)
                    {
                        strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                                        ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value < 0.001";
                    }
                    else if (dblpWald > 0.999)
                    {
                        strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                                        ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value > 0.999";
                    }
                    else
                    {
                        strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                                        ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value: " + dblpWald.ToString(strDecimalPlaces);
                    }


                    strResults[2] = "Log likelihood: " + dblLRErrorModel.ToString(strDecimalPlaces) +
                                    ", Sigma-squared: " + dblSigmasquared.ToString(strDecimalPlaces);
                    strResults[3] = "AIC: " + dblAIC.ToString(strDecimalPlaces) + ", LM test for residuals autocorrelation: " + dblResiAuto.ToString(strDecimalPlaces);
                }
                else if (rbtError.Checked)
                {
                    if (dblpLambda < 0.001)
                    {
                        strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value < 0.001";
                    }
                    else if (dblpLambda > 0.999)
                    {
                        strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value > 0.999";
                    }
                    else
                    {
                        strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces);
                    }

                    if (dblpWald < 0.001)
                    {
                        strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                                        ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value < 0.001";
                    }
                    else if (dblpWald > 0.999)
                    {
                        strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                                        ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value > 0.999";
                    }
                    else
                    {
                        strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                                        ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value: " + dblpWald.ToString(strDecimalPlaces);
                    }

                    //strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                    //    ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces);
                    //strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) +
                    //    ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value: " + dblpWald.ToString(strDecimalPlaces);
                    strResults[2] = "Log likelihood: " + dblLRErrorModel.ToString(strDecimalPlaces) +
                                    ", Sigma-squared: " + dblSigmasquared.ToString(strDecimalPlaces);
                    strResults[3] = "AIC: " + dblAIC.ToString(strDecimalPlaces);
                }
                else
                {
                    if (dblpLambda < 0.001)
                    {
                        strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value < 0.001";
                    }
                    else if (dblpLambda > 0.999)
                    {
                        strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value > 0.999";
                    }
                    else
                    {
                        strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) +
                                        ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces);
                    }

                    strResults[1] = "Numerical Hessian S.E of lambda: " + dblSELambda.ToString(strDecimalPlaces);
                    strResults[2] = "Log likelihood: " + dblLRErrorModel.ToString(strDecimalPlaces) +
                                    ", Sigma-squared: " + dblSigmasquared.ToString(strDecimalPlaces);
                    strResults[3] = "AIC: " + dblAIC.ToString(strDecimalPlaces);
                }
                //if (intInterceptModel != 1)
                //    strResults[4] = "Pseudo-R-squared: " + dblRsquared.ToString(strDecimalPlaces);
                //else
                //    strResults[4] = "";

                strResults[4] = "Pseudo-R-squared: " + dblRsquared.ToString(strDecimalPlaces);

                pfrmRegResult.txtOutput.Lines = strResults;

                //Save Outputs in SHP
                if (chkSave.Checked)
                {
                    pfrmProgress.lblStatus.Text = "Saving residuals:";
                    //The field names are related with string[] DeterminedName in clsSnippet
                    string strResiFldName = lstSave.Items[0].SubItems[1].Text;

                    //Get EVs and residuals
                    NumericVector nvResiduals = m_pEngine.Evaluate("as.numeric(sum.lm$residuals)").AsNumeric();
                    if (rbtCAR.Checked || rbtSMA.Checked)
                    {
                        nvResiduals = m_pEngine.Evaluate("as.numeric(sum.lm$fit$residuals)").AsNumeric();
                    }

                    // Create field, if there isn't
                    if (m_pFClass.FindField(strResiFldName) == -1)
                    {
                        //Add fields
                        IField     newField  = new FieldClass();
                        IFieldEdit fieldEdit = (IFieldEdit)newField;
                        fieldEdit.Name_2 = strResiFldName;
                        fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                        m_pFClass.AddField(newField);
                    }
                    else
                    {
                        DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " 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(strResiFldName);

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

                        pFCursor.UpdateFeature(pFeature);

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

                pfrmProgress.Close();
                pfrmRegResult.Show();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 5
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text = "Processing:";
                pfrmProgress.Show();

                int intProgress = 0;


                REngine pEngine = mForm.pEngine;

                //Declare constants
                double dblDistError   = Convert.ToDouble(txtDistance.Text);
                double dblDirection   = Convert.ToDouble(txtDirections.Text);
                int    intNSimulation = Convert.ToInt32(txtNSimulation.Text);
                string strX           = cboX.Text;
                string strY           = cboY.Text;
                mForm.strValue = cboFieldName.Text;

                //Load Source Layer
                string strLayerName = cboSourceLayer.Text;

                int    intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName);
                ILayer pLayer    = mForm.axMapControl1.get_Layer(intLIndex);

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

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

                //Load Target Layer
                mForm.strTargetLayerName = cboTargetLayer.Text;

                int    intTargetIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, mForm.strTargetLayerName);
                ILayer pTargetLayer   = mForm.axMapControl1.get_Layer(intTargetIndex);

                IFeatureLayer pFTargetLayer  = pTargetLayer as IFeatureLayer;
                IFeatureClass pFTargetClass  = pFTargetLayer.FeatureClass;
                int           nTargetFeature = pFTargetClass.FeatureCount(null);

                //Store X, Y and Value to array
                double[] vecValue = new double[nFeature];
                double[,] arrXY = new double[nFeature, 2];

                int intXIdx = pFClass.FindField(strX);
                int intYIdx = pFClass.FindField(strY);
                int intVIdx = pFClass.FindField(mForm.strValue);

                int i = 0;
                while (pFeature != null)
                {
                    vecValue[i] = Convert.ToDouble(pFeature.get_Value(intVIdx));
                    arrXY[i, 0] = Convert.ToDouble(pFeature.get_Value(intXIdx));
                    arrXY[i, 1] = Convert.ToDouble(pFeature.get_Value(intYIdx));
                    i++;
                    pFeature = pFCursor.NextFeature();
                }
                pFCursor.Flush();

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

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

                if (strNameR == null)
                {
                    return;
                }


                //Load Library and Data
                pEngine.Evaluate("library(maptools);library(foreign);library(sp);library(circular);");
                pEngine.Evaluate("ct.shp <- readShapePoly('" + strNameR + "')");

                //Create Shapepointdataframe in R
                NumericMatrix nmXY = pEngine.CreateNumericMatrix(arrXY);
                pEngine.SetSymbol("xy.coord.old", nmXY);
                NumericVector nvValue = pEngine.CreateNumericVector(vecValue);
                pEngine.SetSymbol("LEAD", nvValue);
                pEngine.Evaluate("v.bll <- as.data.frame(LEAD)");
                pEngine.Evaluate("old.points <- SpatialPointsDataFrame(xy.coord.old, v.bll)");

                string strOverMethod = "";

                if (cboStat.Text == "Mean")
                {
                    strOverMethod = ", fn=mean";
                }


                //Save Original value
                pEngine.Evaluate("n.obs <- nrow(v.bll)");
                pEngine.Evaluate("ori.value <- as.matrix(over(ct.shp, old.points" + strOverMethod + "))");
                NumericVector nvOriValue = pEngine.Evaluate("ori.value").AsNumeric();
                mForm.arrOrivalue = new double[nTargetFeature];
                nvOriValue.CopyTo(mForm.arrOrivalue, nTargetFeature);

                //Create Matrix to store simulation results
                pEngine.Evaluate("results.matrix <- matrix(NA, nrow=nrow(ct.shp), ncol=" + intNSimulation.ToString() + ")");



                //Simulation
                for (int j = 1; j <= intNSimulation; j++)
                {
                    //Progress bar
                    intProgress = j * 100 / intNSimulation;
                    pfrmProgress.pgbProgress.Value = intProgress;
                    //pfrmProgress.pgbProgress.Refresh();
                    pfrmProgress.lblStatus.Text = "Processing (" + intProgress.ToString() + "%)";
                    //pfrmProgress.lblStatus.Refresh();
                    pfrmProgress.Invalidate();

                    //Create Direction from vonmises distribution
                    pEngine.Evaluate("dir.new <- as.numeric(rvonmises(n.obs, mu=circular(" + txtDirections.Text + ", units='degrees'), kappa=" + txtConcetration.Text + "))");

                    //Add distance error
                    if (rbtRandom.Checked == true)
                    {
                        pEngine.Evaluate("dist.error <- runif(n.obs, 0, " + txtDistance.Text + ")");
                    }
                    else
                    {
                        pEngine.Evaluate("dist.error <- " + txtDistance.Text);
                    }

                    //Create New points and save to SpatialPointsDataFrame
                    pEngine.Evaluate("x.new <- xy.coord.old[,1] + cos(dir.new)*dist.error; y.new <- xy.coord.old[,2]+ sin(dir.new)*dist.error");
                    pEngine.Evaluate("xy.coord <- cbind(x.new, y.new)");
                    pEngine.Evaluate("new.points <- SpatialPointsDataFrame(xy.coord, v.bll)");

                    //Save results <- have to insert options for summary statistics, (only possilbe by Mean) 1/29/15
                    pEngine.Evaluate("results.matrix[," + j.ToString() + "] <- as.matrix(over(ct.shp, new.points" + strOverMethod + "))");
                }
                //Save Simulation results to Array
                NumericMatrix nmResults = pEngine.Evaluate("results.matrix").AsNumericMatrix();
                mForm.arrSimuResults = new double[nTargetFeature, intNSimulation];
                nmResults.CopyTo(mForm.arrSimuResults, nTargetFeature, intNSimulation);

                //Create matrix to save summary results(mean, var, mean/var)
                pfrmProgress.lblStatus.Text = "Creating Summary";
                pfrmProgress.Invalidate();
                pEngine.Evaluate("sum.mat <- matrix(NA,nrow=nrow(ct.shp), ncol=6)");

                //Calculate mean and variance of simulation
                for (int j = 1; j <= nTargetFeature; j++)
                {
                    pEngine.Evaluate("sum.mat[" + j.ToString() + ",1] <- mean(results.matrix[" + j.ToString() + ",])");
                    pEngine.Evaluate("sum.mat[" + j.ToString() + ",2] <- var(results.matrix[" + j.ToString() + ",])");
                    pEngine.Evaluate("sum.mat[" + j.ToString() + ",5] <- min(results.matrix[" + j.ToString() + ",])");
                    pEngine.Evaluate("sum.mat[" + j.ToString() + ",6] <- max(results.matrix[" + j.ToString() + ",])");

                    pEngine.Evaluate("diff.ori <- (results.matrix[" + j.ToString() + ",]- ori.value[" + j.ToString() + "])^2"); //Needs to be changed
                    pEngine.Evaluate("sum.mat[" + j.ToString() + ",4] <- sum(diff.ori)/" + intNSimulation.ToString());
                }
                //Calculate mean/variance
                pEngine.Evaluate("sum.mat[,3] <- sum.mat[,2]/sum.mat[,1]");

                //Save summary results to array
                NumericMatrix nmSummary = pEngine.Evaluate("sum.mat").AsNumericMatrix();
                arrSummary = new double[nTargetFeature, 6];
                nmSummary.CopyTo(arrSummary, nTargetFeature, 6);

                //Remove all memory
                pEngine.Evaluate("rm(list=ls(all=TRUE))");

                //Enable to the histogram identify tool for simulation results
                if (mForm.arrSimuResults != null)
                {
                    chkEnable.Enabled = true;
                }



                //Add Summary data to Target feature Class

                //Create filed to store results
                if (pFTargetClass.FindField("Ori_Mean") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "Ori_Mean";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                if (pFTargetClass.FindField("Mean_val") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "Mean_val";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                if (pFTargetClass.FindField("Var_val") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "Var_val";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                if (pFTargetClass.FindField("Mean_Var") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "Mean_Var";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                if (pFTargetClass.FindField("Var_Ori") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "Var_Ori";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                if (pFTargetClass.FindField("MIN") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "MIN";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                if (pFTargetClass.FindField("MAX") == -1)
                {
                    IFieldEdit addField = new FieldClass();
                    addField.Name_2 = "MAX";
                    addField.Type_2 = esriFieldType.esriFieldTypeDouble;
                    pFTargetClass.AddField(addField);
                }
                //Save summary results to Target shapefile
                int intOriMeanIdx = pFTargetClass.FindField("Ori_Mean");
                int intMeanIdx    = pFTargetClass.FindField("Mean_val");
                int intVarIdx     = pFTargetClass.FindField("Var_val");
                int intMVIdx      = pFTargetClass.FindField("Mean_Var");
                int intVOIdx      = pFTargetClass.FindField("Var_Ori");
                int intMaxIdx     = pFTargetClass.FindField("MAX");
                int intMinIdx     = pFTargetClass.FindField("MIN");

                IFeatureCursor pTFUCursor = pFTargetClass.Update(null, false);
                IFeature       pTFeature  = pTFUCursor.NextFeature();

                i = 0;
                while (pTFeature != null)
                {
                    pTFeature.set_Value(intOriMeanIdx, mForm.arrOrivalue[i]);
                    pTFeature.set_Value(intMeanIdx, arrSummary[i, 0]);
                    pTFeature.set_Value(intVarIdx, arrSummary[i, 1]);
                    pTFeature.set_Value(intMVIdx, arrSummary[i, 2]);
                    pTFeature.set_Value(intVOIdx, arrSummary[i, 3]);
                    pTFeature.set_Value(intMinIdx, arrSummary[i, 4]);
                    pTFeature.set_Value(intMaxIdx, arrSummary[i, 5]);
                    pTFeature.Store();

                    i++;
                    pTFeature = pTFUCursor.NextFeature();
                }



                pfrmProgress.Close();
                MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show(this.Handle.ToString() + " Error:" + ex.Message);
                return;
            }
        }
Ejemplo n.º 6
0
        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.bgWorker.ReportProgress(0);
                pfrmProgress.lblStatus.Text = "Create Flow Lines";
                pfrmProgress.Show();

                string            strOutput     = txtOutput.Text;
                string            strOutputPath = System.IO.Path.GetDirectoryName(strOutput);
                string            strOutputName = System.IO.Path.GetFileName(strOutput);
                ISpatialReference pSpatialRef   = null;
                if (cboSpatialInfo.Text == "From ShapeFile")
                {
                    IGeoDataset geoDataset = m_pFClass as IGeoDataset;
                    pSpatialRef = geoDataset.SpatialReference;
                }

                //Create New FeatureClass
                IFeatureClass pFCOutput = CreateShapeFile(strOutputPath, strOutputName, pSpatialRef, esriGeometryType.esriGeometryPolyline);

                //Add Fld Ids to added in new FC
                int[] intAddFldIdsInTable = null;
                int   intCheckedFldCnt    = clistFields.CheckedItems.Count;
                if (intCheckedFldCnt > 0)
                {
                    intAddFldIdsInTable = new int[intCheckedFldCnt];
                    for (int i = 0; i < intCheckedFldCnt; i++)
                    {
                        intAddFldIdsInTable[i] = m_tblFlow.FindField((string)clistFields.CheckedItems[i]);
                    }
                }
                AddFldsFromTable(pFCOutput, m_tblFlow, intAddFldIdsInTable);
                //Get Ids from FeatureClass
                int[] intAddFldIdsInFC = null;

                if (intCheckedFldCnt > 0)
                {
                    intAddFldIdsInFC = new int[intCheckedFldCnt];
                    for (int i = 0; i < intCheckedFldCnt; i++)
                    {
                        intAddFldIdsInFC[i] = pFCOutput.FindField((string)clistFields.CheckedItems[i]);
                    }
                }
                var watch = Stopwatch.StartNew();


                if (cboSpatialInfo.Text == "From Table")
                {
                    //First Method, it takes some times, require better algorithm. 0714 HK
                    string strFromXFld = cbo1.Text;
                    string strFromYFld = cbo2.Text;
                    string strToXFld   = cbo3.Text;
                    string strToYFld   = cbo4.Text;

                    int intFromXIdx = m_tblFlow.FindField(strFromXFld);
                    int intFromYIdx = m_tblFlow.FindField(strFromYFld);
                    int intToXIdx   = m_tblFlow.FindField(strToXFld);
                    int intToYIdx   = m_tblFlow.FindField(strToYFld);

                    int     intTotalFlowCnt = m_tblFlow.RowCount(null);
                    ICursor pCursor         = m_tblFlow.Search(null, false);
                    IRow    pRow            = pCursor.NextRow();
                    //IPoint pFromPt = new ESRI.ArcGIS.Geometry.Point();
                    //IPoint pToPts = new ESRI.ArcGIS.Geometry.Point();
                    IPoint pFromPt = null;
                    IPoint pToPt = null;
                    double dblFromX = 0, dblFromY = 0, dblToX = 0, dblToY = 0;

                    IPolyline pPolyline = new PolylineClass();

                    int cnt = 0;
                    if (intCheckedFldCnt > 0)
                    {
                        while (pRow != null)
                        {
                            int intProgress = cnt * 100 / intTotalFlowCnt;
                            pfrmProgress.bgWorker.ReportProgress(intProgress);

                            dblFromX = Convert.ToDouble(pRow.get_Value(intFromXIdx));
                            dblFromY = Convert.ToDouble(pRow.get_Value(intFromYIdx));
                            dblToX   = Convert.ToDouble(pRow.get_Value(intToXIdx));
                            dblToY   = Convert.ToDouble(pRow.get_Value(intToYIdx));

                            pFromPt = new PointClass();
                            pToPt   = new PointClass();
                            pFromPt.PutCoords(dblFromX, dblFromY);
                            pToPt.PutCoords(dblToX, dblToY);

                            pPolyline           = new PolylineClass();
                            pPolyline.FromPoint = pFromPt;
                            pPolyline.ToPoint   = pToPt;
                            IFeature pFeature = pFCOutput.CreateFeature();
                            pFeature.Shape = pPolyline;

                            for (int i = 0; i < intCheckedFldCnt; i++)
                            {
                                pFeature.set_Value(intAddFldIdsInFC[i], pRow.get_Value(intAddFldIdsInTable[i]));
                            }

                            pFeature.Store();
                            pRow = pCursor.NextRow();
                            cnt++;
                        }
                    }
                    else
                    {
                        int intProgress = cnt * 100 / intTotalFlowCnt;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        dblFromX = Convert.ToDouble(pRow.get_Value(intFromXIdx));
                        dblFromY = Convert.ToDouble(pRow.get_Value(intFromYIdx));
                        dblToX   = Convert.ToDouble(pRow.get_Value(intToXIdx));
                        dblToY   = Convert.ToDouble(pRow.get_Value(intToYIdx));

                        pFromPt = new PointClass();
                        pToPt   = new PointClass();
                        pFromPt.PutCoords(dblFromX, dblFromY);
                        pToPt.PutCoords(dblToX, dblToY);

                        pPolyline           = new PolylineClass();
                        pPolyline.FromPoint = pFromPt;
                        pPolyline.ToPoint   = pToPt;
                        IFeature pFeature = pFCOutput.CreateFeature();
                        pFeature.Shape = pPolyline;

                        pFeature.Store();
                        pRow = pCursor.NextRow();
                        cnt++;
                    }
                    #region deprecated 101917 HK
                    //    //Second Method, it takes similar calculation time. 0714 HK
                    //    string strFromXFld = cbo1.Text;
                    //    string strFromYFld = cbo2.Text;
                    //    string strToXFld = cbo3.Text;
                    //    string strToYFld = cbo4.Text;

                    //    int intFromXIdx = m_tblFlow.FindField(strFromXFld);
                    //    int intFromYIdx = m_tblFlow.FindField(strFromYFld);
                    //    int intToXIdx = m_tblFlow.FindField(strToXFld);
                    //    int intToYIdx = m_tblFlow.FindField(strToYFld);

                    //    int intTotalFlowCnt = m_tblFlow.RowCount(null);
                    //    ICursor pCursor = m_tblFlow.Search(null, false);
                    //    IRow pRow = pCursor.NextRow();
                    //    //IPoint pFromPt = new ESRI.ArcGIS.Geometry.Point();
                    //    //IPoint pToPts = new ESRI.ArcGIS.Geometry.Point();
                    //    IPoint pFromPt = null;
                    //    IPoint pToPt = null;

                    //    IPolyline pPolyline = new PolylineClass();

                    //    double[][] dblValues = new double[intTotalFlowCnt][];
                    //    int cnt = 0;
                    //    while (pRow != null)
                    //    {
                    //        pfrmProgress.lblStatus.Text = "Collect data";
                    //        int intProgress = cnt * 100 / intTotalFlowCnt;
                    //        pfrmProgress.bgWorker.ReportProgress(intProgress);


                    //        dblValues[cnt] = new double[4 + intCheckedFldCnt];

                    //        dblValues[cnt][0] = Convert.ToDouble(pRow.get_Value(intFromXIdx));
                    //        dblValues[cnt][1] = Convert.ToDouble(pRow.get_Value(intFromYIdx));
                    //        dblValues[cnt][2] = Convert.ToDouble(pRow.get_Value(intToXIdx));
                    //        dblValues[cnt][3] = Convert.ToDouble(pRow.get_Value(intToYIdx));

                    //        if (intCheckedFldCnt > 0)
                    //            for (int i = 0; i < intCheckedFldCnt; i++)
                    //                dblValues[cnt][3+i] = Convert.ToDouble(pRow.get_Value(intAddFldIdsInTable[i]));

                    //        pRow = pCursor.NextRow();
                    //        cnt++;
                    //    }
                    //    for(int j = 0; j<intTotalFlowCnt; j++)
                    //    {
                    //        pfrmProgress.lblStatus.Text = "Create Line";
                    //        int intProgress = j * 100 / intTotalFlowCnt;
                    //        pfrmProgress.bgWorker.ReportProgress(intProgress);

                    //        pFromPt = new PointClass();
                    //        pToPt = new PointClass();
                    //        pFromPt.PutCoords(dblValues[j][0], dblValues[j][1]);
                    //        pToPt.PutCoords(dblValues[j][2], dblValues[j][3]);

                    //        pPolyline = new PolylineClass();
                    //        pPolyline.FromPoint = pFromPt;
                    //        pPolyline.ToPoint = pToPt;
                    //        IFeature pFeature = pFCOutput.CreateFeature();
                    //        pFeature.Shape = pPolyline;
                    //        if (intCheckedFldCnt > 0)
                    //            for (int i = 0; i < intCheckedFldCnt; i++)
                    //                pFeature.set_Value(intAddFldIdsInFC[i], dblValues[j][3+i]);

                    //        pFeature.Store();
                    //    }
                    #endregion
                }
                else if (cboSpatialInfo.Text == "From ShapeFile")
                {
                    string strRefSHPName  = cbo1.Text;
                    string strJoinFldName = cbo2.Text;
                    string strOIDFldName  = cbo3.Text;
                    string strDIDFldName  = cbo4.Text;

                    int intJoinFldIdx = m_pFClass.FindField(strJoinFldName);
                    int intOIDIdx     = m_tblFlow.FindField(strOIDFldName);
                    int intDIDIdx     = m_tblFlow.FindField(strDIDFldName);

                    int intFeatureCount = m_pFClass.FeatureCount(null);

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

                    List <RefSpatialInfo> lstRefInfo = new List <RefSpatialInfo>();

                    IArea  pArea;
                    IPoint pPoint;

                    int cnt = 0;
                    while (pFeature != null)
                    {
                        pfrmProgress.lblStatus.Text = "Getting Spatial Information from Shape file";
                        int intProgress = cnt * 100 / intFeatureCount;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        RefSpatialInfo RefInfo = new RefSpatialInfo();
                        RefInfo.JoinID = pFeature.get_Value(intJoinFldIdx).ToString();

                        if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            pArea         = (IArea)pFeature.Shape;
                            RefInfo.XCoor = pArea.Centroid.X;
                            RefInfo.YCoor = pArea.Centroid.Y;
                        }
                        else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            pPoint        = (IPoint)pFeature.Shape;
                            RefInfo.XCoor = pPoint.X;
                            RefInfo.YCoor = pPoint.Y;
                        }

                        lstRefInfo.Add(RefInfo);

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

                    int     intTotalFlowCnt = m_tblFlow.RowCount(null);
                    ICursor pCursor         = m_tblFlow.Search(null, false);
                    IRow    pRow            = pCursor.NextRow();

                    IPoint pFromPt = null;
                    IPoint pToPt = null;
                    double dblFromX = 0, dblFromY = 0, dblToX = 0, dblToY = 0;

                    IPolyline pPolyline = new PolylineClass();

                    cnt = 0;
                    int intNonMatchedFlow = 0;
                    while (pRow != null)
                    {
                        pfrmProgress.lblStatus.Text = "Create Flow Lines";
                        int intProgress = cnt * 100 / intTotalFlowCnt;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        string strOID = pRow.get_Value(intOIDIdx).ToString();
                        string strDID = pRow.get_Value(intDIDIdx).ToString();

                        RefSpatialInfo RefOInfo = lstRefInfo.Find(x => x.JoinID == strOID);
                        RefSpatialInfo RefDInfo = lstRefInfo.Find(x => x.JoinID == strDID);

                        if (RefOInfo == null || RefDInfo == null)
                        {
                            intNonMatchedFlow++;
                            pRow = pCursor.NextRow();
                            cnt++;
                        }
                        else
                        {
                            dblFromX = RefOInfo.XCoor;
                            dblFromY = RefOInfo.YCoor;
                            dblToX   = RefDInfo.XCoor;
                            dblToY   = RefDInfo.YCoor;

                            pFromPt = new PointClass();
                            pToPt   = new PointClass();
                            pFromPt.PutCoords(dblFromX, dblFromY);
                            pToPt.PutCoords(dblToX, dblToY);

                            pPolyline           = new PolylineClass();
                            pPolyline.FromPoint = pFromPt;
                            pPolyline.ToPoint   = pToPt;
                            IFeature pNewFeature = pFCOutput.CreateFeature();
                            pNewFeature.Shape = pPolyline;

                            if (intCheckedFldCnt > 0)
                            {
                                for (int i = 0; i < intCheckedFldCnt; i++)
                                {
                                    pNewFeature.set_Value(intAddFldIdsInFC[i], pRow.get_Value(intAddFldIdsInTable[i]));
                                }
                            }

                            pNewFeature.Store();
                            pRow = pCursor.NextRow();
                            cnt++;
                        }
                    }
                    //MessageBox.Show(intNonMatchedFlow.ToString()+" flow lines are not matched with the reference file"); //Check the message. 080516 HK
                }
                pfrmProgress.Close();

                watch.Stop();
                double dblTime = watch.ElapsedMilliseconds;
                MessageBox.Show("Run-time: " + dblTime.ToString());

                DialogResult dialogResult = MessageBox.Show("Do you want to add the output data to the map?", "Add Data", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    IFeatureLayer pFeaturelayer = new FeatureLayer();
                    pFeaturelayer.Name         = pFCOutput.AliasName;
                    pFeaturelayer.FeatureClass = pFCOutput;
                    m_pActiveView.FocusMap.AddLayer((ILayer)pFeaturelayer);
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 7
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            int intDeciPlaces = 5;

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

            frmProgress pfrmProgress = new frmProgress();

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

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

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

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

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

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

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

            int i = 0;

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

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

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

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

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

            if (strNameR == null)
            {
                return;
            }

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

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

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

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

            string strNonZeroDiag = null;

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

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


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

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

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

                pfrmResult.Show();
            }
            pfrmProgress.Close();
        }
Ejemplo n.º 8
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

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

            REngine pEngine = m_pForm.pEngine;

            int nFeature = m_pFClass.FeatureCount(null);

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

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

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

            int[] arrFID = new int[nFeature];

            int i = 0;

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

            pFCursor.Flush();

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

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

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

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

            if (strNameR == null)
            {
                return;
            }

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

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

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

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

            string strNonZero = null;

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

            string[] strSPQuadrants = null;

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

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

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

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

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

            int featureIdx = 0;

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

                pFCursor.UpdateFeature(pFeature);

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

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

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

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

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

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

                        intTotalCount = pTable.RowCount(pQFilter);

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

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

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

                        pSymbol.Angle = m_pQuadrantSymbols[j].Angle;

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

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

                        intTotalCount = pTable.RowCount(pQFilter);

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

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

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

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

                pfrmMScatterResult.pChart.Series.Add(seriesPts);

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

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

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

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

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

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

                pfrmMScatterResult.pChart.Series.Add(seriesLine);

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

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

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

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

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

                pfrmMScatterResult.Show();
            }
            pfrmProgress.Close();
        }
Ejemplo n.º 9
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboFieldName.Text == "")
                {
                    MessageBox.Show("Please select an ID field to be used as region ID.",
                                    "Please choose an ID field");
                    return;
                }


                if (txtOutput.Text == "")
                {
                    MessageBox.Show("Please specify path and file name.",
                                    "Please specify a path");
                    return;
                }


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

                //Create Row ID vectors
                int nFeature = m_pFClass.FeatureCount(null);

                //Get index for independent and dependent variables
                string strIDfield = cboFieldName.Text;
                int    intIDIdx   = m_pFClass.Fields.FindField(strIDfield);

                double[] arrRowID = new double[nFeature];

                int            i        = 0;
                IFeatureCursor pFCursor = m_pFClass.Search(null, true);
                IFeature       pFeature = pFCursor.NextFeature();
                while (pFeature != null)
                {
                    arrRowID[i] = Convert.ToDouble(pFeature.get_Value(intIDIdx));

                    i++;
                    pFeature = pFCursor.NextFeature();
                }
                NumericVector vecRowID = m_pEngine.CreateNumericVector(arrRowID);
                m_pEngine.SetSymbol("sample.ids", vecRowID);

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

                //Shp name
                IDataset dataset    = (IDataset)(m_pFLayer);
                string   strShpname = dataset.BrowseName;
                if (dataset.Category == "Shapefile Feature Class")
                {
                    strShpname = strShpname + ".shp";
                }

                //Output
                string strOutput = m_pSnippet.FilePathinRfromText(txtOutput.Text);

                int intSuccess = 0;

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

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

                if (intSuccess == 0)
                {
                    MessageBox.Show("Fail to create spatial weights.", "Fail");
                    return;
                }
                else
                {
                    m_pEngine.Evaluate("write.nb.gal(sample.nb, '" + strOutput + "', oldstyle = F, shpfile = '" + strShpname + "', ind = '" + strIDfield + "')");
                    MessageBox.Show("A spatial weights file is successfuly created in " + strOutput, "Success");
                }


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

            if (cboMeasure.Text == "Lee's L")
            {
                pEngine.Evaluate("sample.result <- test.global.lee.L(sample.v1, sample.v2, sample.nb, style = 'W', alternative='two.sided', diag.zero = " + strNonZero + ")");
            }
            else if (cboMeasure.Text == "Pearson's r")
            {
                pEngine.Evaluate("sample.result <- test.global.pearson(sample.v1, sample.v2, alternative='two.sided')");
            }
            else if (cboMeasure.Text == "Bivariate Moran")
            {
                pEngine.Evaluate("sample.result <- test.global.bMoran(sample.v1, sample.v2, sample.nb, style = 'W', alternative='two.sided', diag.zero = " + strNonZero + ")");
            }
            else if (cboMeasure.Text == "Bivariate Geary")
            {
                pEngine.Evaluate("sample.result <- test.global.bGeary(sample.v1, sample.v2, sample.nb, style = 'W', alternative='two.sided', diag.zero = " + strNonZero + ")");
            }
            int intDeciPlaces = 4;
            //Print Output
            string strDecimalPlaces = "N" + intDeciPlaces.ToString();

            string[] strResults = new string[8];
            strResults[0] = pEngine.Evaluate("sample.result$method").AsCharacter().First();
            strResults[1] = "";
            if (cboMeasure.Text != "Pearson's r")
            {
                if (chkDiagZero.Checked)
                {
                    strResults[2] = "Weights: W*";
                }
                else
                {
                    strResults[2] = "Weights: W";
                }
            }
            else
            {
                strResults[2] = string.Empty;
            }

            NumericVector vecResults = pEngine.Evaluate("sample.result$estimate").AsNumeric();

            strResults[3] = "Observed: " + vecResults[0].ToString(strDecimalPlaces);
            strResults[4] = "Expectation: " + vecResults[1].ToString(strDecimalPlaces);
            strResults[5] = "Variance: " + vecResults[2].ToString(strDecimalPlaces);
            double dblStd  = pEngine.Evaluate("sample.result$statistic").AsNumeric().First();
            double dblPval = pEngine.Evaluate("sample.result$p.value").AsNumeric().First();

            strResults[6] = "Standard deviate: " + dblStd.ToString(strDecimalPlaces);
            strResults[7] = "p-value: " + dblPval.ToString(strDecimalPlaces);

            frmGenResult pfrmResult = new frmGenResult();

            pfrmResult.Text                = "Summary";
            pfrmResult.txtField.Text       = cboFldnm1.Text + " & " + cboFldnm2.Text;
            pfrmResult.txtStatistics.Lines = strResults;
            pfrmProgress.Close();
            pfrmResult.Show();
        }
Ejemplo n.º 11
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

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

            REngine pEngine = m_pForm.pEngine;

            int nFeature = m_pFClass.FeatureCount(null);

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

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

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

            int[] arrFID = new int[nFeature];

            int i = 0;

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

            pFCursor.Flush();

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

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

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

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

            if (strNameR == null)
            {
                return;
            }

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

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

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

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

            string strNonZero = null;

            if (chkDiagZero.Checked)
            {
                strNonZero = "FALSE";
            }
            else
            {
                strNonZero = "TRUE";
            }
            string strSigLv = nudSigLv.Value.ToString();

            string[] strSPQuadrants = null;

            //double[] adblVar1 = null;
            //double[] adblVar2 = null;
            //NumericVector vecCoeff = null;
            if (cboMeasure.Text == "Lee's L")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', sig.level=c(" + strSigLv + "), method='" + cboMethod.Text + "', alternative='" + txtAlternative.Text + "', diag.zero = " + strNonZero + ")");

                //pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.lee(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style = 'W', sig.level=c(" + strSigLv + "), method='total', alternative='two.sided', diag.zero = " + strNonZero + ")");
                strSPQuadrants = pEngine.Evaluate("as.character(sample.result[[6]])").AsCharacter().ToArray();
            }
            else if (cboMeasure.Text == "Local Pearson")
            {
                pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.pearson(sample.v1, sample.v2, 1:length(sample.nb), sig.level=c(" + strSigLv + ", 0.01), method='" + cboMethod.Text + "', alternative='" + txtAlternative.Text + "')");

                //pEngine.Evaluate("sample.result <- LARRY.bivariate.sig.quad.pearson(sample.v1, sample.v2, 1:length(sample.nb), sig.level=c(" + strSigLv + "), method='total', alternative='two.sided')");
                strSPQuadrants = pEngine.Evaluate("as.character(sample.result[[6]])").AsCharacter().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.esriFieldTypeString;
                    m_pFClass.AddField(newField);
                }
            }

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

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

            int featureIdx = 0;

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

                pFCursor.UpdateFeature(pFeature);

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

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

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

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

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

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

                        intTotalCount = pTable.RowCount(pQFilter);

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

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

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

                        //pSymbol.Angle = m_pQuadrantSymbols[j].Angle;

                        //With hallo
                        pSymbol = new CharacterMarkerSymbolClass();
                        pSymbol.CharacterIndex = 248;
                        //pSymbol.Color = m_pSnippet.getRGB(m_pQuadrantSymbols[j].R, m_pQuadrantSymbols[j].G, m_pQuadrantSymbols[j].B);
                        pSymbol.Size = 10;
                        pSymbol.Font = stdFontCls;

                        pSymbol.Angle = m_pQuadrantSymbols[j].Angle;

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

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

                        intTotalCount = pTable.RowCount(pQFilter);

                        strLabel = m_pQuadrantSymbols[j].Label + " (" + intTotalCount.ToString() + ")";
                        pUniqueValueRenderer.AddValue(m_pQuadrantSymbols[j].Value, null, (ISymbol)pSymbol);
                        pUniqueValueRenderer.set_Label(m_pQuadrantSymbols[j].Value, strLabel);
                    }
                    pUniqueValueRenderer.UseDefaultSymbol = false;
                }
                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = m_pFClass;
                pNewFLayer.Name         = "Bivariate Spatial Significant Quadrant";
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                m_pActiveView.FocusMap.AddLayer(pGFLayer);
                m_pActiveView.Refresh();
                m_pForm.axTOCControl1.Update();
            }
            pfrmProgress.Close();
        }
Ejemplo n.º 12
0
        private void btnSummary_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                int    nFeature         = m_pFClass.FeatureCount(null);
                double dblAdvancedValue = Convert.ToDouble(nudAdvanced.Value);
                //Plot command for R
                StringBuilder plotCommmand = new StringBuilder();

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

                if (strNameR == null)
                {
                    return;
                }
                int intSuccess = 0;
                //Create spatial weight matrix in R
                if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
                    intSuccess = m_pSnippet.ExploreSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, dblAdvancedValue, chkCumulate.Checked);
                }
                else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')");
                    intSuccess = m_pSnippet.ExploreSpatialWeightMatrixPts(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, dblAdvancedValue, chkCumulate.Checked, m_pClippedPolygon);
                }
                else
                {
                    MessageBox.Show("This geometry type is not supported");
                    pfrmProgress.Close();
                    this.Close();
                }

                if (intSuccess == 0)
                {
                    return;
                }


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

                //Get variable index
                int   intFIDIdx = m_pFClass.FindField(m_pFClass.OIDFieldName); // Collect FIDs to apply Brushing and Linking
                int[] arrFID    = new int[nFeature];

                int i = 0;

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

                IArea  pArea;
                IPoint pPoint;

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

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

                //Save Def_SWM
                clsSnippet.Def_SpatialWeightsMatrix pDefSWM = new clsSnippet.Def_SpatialWeightsMatrix();
                pDefSWM.Geometry      = m_pFClass.ShapeType;
                pDefSWM.Definition    = txtSWM.Text;
                pDefSWM.AdvancedValue = dblAdvancedValue;
                pDefSWM.Cumulative    = chkCumulate.Checked;
                pDefSWM.Subset        = m_blnSubset;

                pDefSWM.FIDs    = arrFID;
                pDefSWM.NBIDs   = NBIDs;
                pDefSWM.XYCoord = m_arrXYCoord;

                m_pEngine.Evaluate("c.nb <- card(sample.nb)");
                pDefSWM.FeatureCount         = nFeature;
                pDefSWM.NeighborCounts       = m_pEngine.Evaluate("c.nb").AsNumeric().ToArray();
                pDefSWM.NonZeroLinkCount     = Convert.ToInt32(pDefSWM.NeighborCounts.Sum());
                pDefSWM.PercentNonZeroWeight = Convert.ToDouble(pDefSWM.NonZeroLinkCount) / Math.Pow(nFeature, 2) * 100;
                pDefSWM.AverageNumberofLink  = pDefSWM.NeighborCounts.Average();



                //For higher order;
                if (m_pFClass.ShapeType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon)
                {
                    if (dblAdvancedValue > 1)
                    {
                        int intMaxLag = Convert.ToInt32(dblAdvancedValue);
                        pDefSWM.LinkCountforHigher = new double[intMaxLag];
                        pDefSWM.AverageforHigher   = new double[intMaxLag];

                        for (int j = 0; j < intMaxLag; j++)
                        {
                            m_pEngine.Evaluate("h.nb <- card(sample.nblags[[" + (j + 1).ToString() + "]])");
                            pDefSWM.LinkCountforHigher[j] = m_pEngine.Evaluate("sum(h.nb)").AsNumeric().First();
                            pDefSWM.AverageforHigher[j]   = m_pEngine.Evaluate("mean(h.nb)").AsNumeric().First();
                        }
                    }
                }

                frmSWMSummary pSMWSummary = new frmSWMSummary();
                pSMWSummary.Def_SWM       = pDefSWM;
                pSMWSummary.txtLayer.Text = m_pFLayer.Name;
                pSMWSummary.m_pFLayer     = m_pFLayer;
                pSMWSummary.Show();

                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (cboValueField.Text == "" || cboUField.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 strVarNM  = (string)cboValueField.SelectedItem;
            string strUncNM  = (string)cboUField.SelectedItem;
            int    intVarIdx = m_pFClass.FindField(strVarNM);
            int    intUncIdx = m_pFClass.FindField(strUncNM);
            int    intFIDIdx = m_pFClass.FindField(m_pFClass.OIDFieldName);

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

            int[] arrFID = new int[nFeature];

            int i = 0;

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

            pFCursor.Flush();

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

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

            pEngine.Evaluate("source('" + pathr + "/UncernSAM/functions.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(arrVar);

            pEngine.SetSymbol("sample.est", vecVar1);
            NumericVector vecVar2 = pEngine.CreateNumericVector(arrUnc);

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

            pEngine.Evaluate("sample.result <- UncernSAM(sample.est, sample.var, sample.nb)");

            //Local Geary for comparison
            pEngine.Evaluate("source('" + pathr + "/AllFunctions.R')");
            pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE)");
            pEngine.Evaluate("localsam.result <- localgeary(sample.est, sample.listw);");

            double[] adblBD = pEngine.Evaluate("sample.result[[2]]").AsNumeric().ToArray();
            double[] adblBC = pEngine.Evaluate("sample.result[[3]]").AsNumeric().ToArray();
            //double[] adblHD = pEngine.Evaluate("sample.result[[4]]").AsNumeric().ToArray();
            double[] adblHD = pEngine.Evaluate("localsam.result[,1]").AsNumeric().ToArray();
            //Save Output on SHP
            //Add Target fields to store results in the shapefile // Keep loop
            for (int j = 0; j < 3; 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 strBDFldName = lvFields.Items[0].SubItems[1].Text;
            int    intBDFldIdx  = m_pFClass.FindField(strBDFldName);

            string strBCFldName = lvFields.Items[1].SubItems[1].Text;
            int    intBCFldIdx  = m_pFClass.FindField(strBCFldName);

            string strHDFldName = lvFields.Items[2].SubItems[1].Text;
            int    intHDFldIdx  = m_pFClass.FindField(strHDFldName);


            int featureIdx = 0;

            while (pFeature != null)
            {
                pFeature.set_Value(intBDFldIdx, adblBD[featureIdx]);
                pFeature.set_Value(intBCFldIdx, adblBC[featureIdx]);
                pFeature.set_Value(intHDFldIdx, adblHD[featureIdx]);

                pFCursor.UpdateFeature(pFeature);

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


            if (chkScatterplot.Checked)
            {
                pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W')");

                NumericVector vecWeightVar = null;
                vecWeightVar = pEngine.Evaluate("wx.sample <- lag.listw(sample.listw, sample.est, zero.policy=TRUE)").AsNumeric();

                pEngine.SetSymbol("WVar.sample", vecWeightVar);

                NumericVector vecCoeff = pEngine.Evaluate("lm(WVar.sample~sample.est)$coefficients").AsNumeric();

                frmMCscatterwithColor pfrmMScatterResult = new frmMCscatterwithColor();
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsStartedFromZero = false;
                pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsMarginVisible   = true;

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

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

                pfrmMScatterResult.pChart.Series.Add(seriesPts);

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



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

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

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

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

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

                pfrmMScatterResult.pChart.Series.Add(seriesLine);

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

            pfrmProgress.Close();
        }
Ejemplo n.º 14
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.º 15
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            frmProgress pfrmProgress = new frmProgress();

            pfrmProgress.Show();
            pfrmProgress.lblStatus.Text = "Collecting Information";
            int intProgress = 0;

            pfrmProgress.bgWorker.ReportProgress(intProgress);

            //Get Sample Table setting
            string strTableName = txtSampleTable.Text;

            if (strTableName == "")
            {
                return;
            }
            string            strSourceFolder  = System.IO.Path.GetDirectoryName(strTableName);
            string            strSourceFile    = System.IO.Path.GetFileName(strTableName);
            IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
            IWorkspace        workspace        = workspaceFactory.OpenFromFile(strSourceFolder, 0);
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
            IFeatureClass     pFClass          = featureWorkspace.OpenFeatureClass(strSourceFile);
            //string strXNewFld = "NewRefX";
            string strXNewFld    = "NewRefX1";
            int    intXNewFldIdx = pFClass.FindField(strXNewFld);

            if (intXNewFldIdx == -1)
            {
                AddFld(pFClass, strXNewFld, esriFieldType.esriFieldTypeDouble);
                intXNewFldIdx = pFClass.FindField(strXNewFld);
            }

            //string strYNewFld = "NewRefY";
            string strYNewFld    = "NewRefY1";
            int    intYNewFldIdx = pFClass.FindField(strYNewFld);

            if (intYNewFldIdx == -1)
            {
                AddFld(pFClass, strYNewFld, esriFieldType.esriFieldTypeDouble);
                intYNewFldIdx = pFClass.FindField(strYNewFld);
            }

            string strFlagFld    = "Flag";
            int    intFlagFldIdx = pFClass.FindField(strFlagFld);

            if (intFlagFldIdx == -1)
            {
                AddFld(pFClass, strFlagFld, esriFieldType.esriFieldTypeSmallInteger);
                intFlagFldIdx = pFClass.FindField(strFlagFld);
            }

            //Get Reference Street file
            string strRefStreet = txtRefStreet.Text;

            if (strRefStreet == "")
            {
                return;
            }
            string            strRefSource = System.IO.Path.GetDirectoryName(strRefStreet);
            string            strRefName   = System.IO.Path.GetFileName(strRefStreet);
            IWorkspace        pwsRef       = workspaceFactory.OpenFromFile(strRefSource, 0);
            IFeatureWorkspace pfwsRef      = pwsRef as IFeatureWorkspace;
            IFeatureClass     pRefFClass   = pfwsRef.OpenFeatureClass(strRefName);

            //Get Reference Street File
            //string[] addFldNames = new string[] { "JOINID", "Length", "RLMean", "LLMean", "CompassA", "DirMean", "AveX", "AveY", "AveLen" };
            List <RefStreetVertices> lstRefStreetInfo = new List <RefStreetVertices>();

            //RefStreetInfo pRefStreetInfo = new RefStreetInfo();
            //int intInforCnt = addFldNames.Length;
            //int[] intInfoIdxs = new int[intInforCnt];

            //for (int i = 0; i < intInforCnt; i++)
            //    intInfoIdxs[i] = pRefFClass.FindField(addFldNames[i]);

            int intJoinIDIdx = pRefFClass.FindField("JOINID");
            //int intRefStreetCnt = pRefFClass.FeatureCount(null);
            IFeatureCursor pRefFCursor = pRefFClass.Search(null, false);
            IFeature       pRefFeature = pRefFCursor.NextFeature();

            while (pRefFeature != null)
            {
                RefStreetVertices pRefStreetInfo = new RefStreetVertices();
                pRefStreetInfo.JoinID = pRefFeature.get_Value(intJoinIDIdx).ToString();
                IPolyline        pPolyLine        = (IPolyline)pRefFeature.ShapeCopy;
                IPointCollection pPointCollection = (IPointCollection)pPolyLine;
                pRefStreetInfo.pointCollection = pPointCollection;

                lstRefStreetInfo.Add(pRefStreetInfo);
                pRefFeature = pRefFCursor.NextFeature();
            }

            int          intRefXIdx  = pFClass.FindField(cboXRef.Text);
            int          intRefYIdx  = pFClass.FindField(cboYRef.Text);
            string       strRefID    = "Ref_ID";
            int          intRefIDIdx = pFClass.FindField(strRefID);
            IQueryFilter pQFilter    = new QueryFilterClass();

            //pQFilter.WhereClause = "Status = 'M'";
            pQFilter.WhereClause = "Score > 0";

            IFeatureCursor pFCursor = pFClass.Update(pQFilter, true);
            IFeature       pFeature = pFCursor.NextFeature();

            int intFlag = 0;

            while (pFeature != null)
            {
                intFlag = 0;
                TargetPoint p = new TargetPoint();
                p.x = Convert.ToDouble(pFeature.get_Value(intRefXIdx));
                p.y = Convert.ToDouble(pFeature.get_Value(intRefYIdx));

                string strJoinID = pFeature.get_Value(intRefIDIdx).ToString();

                RefStreetVertices pRefStreetVertices = lstRefStreetInfo.Find(x => x.JoinID == strJoinID);

                int intVerticeCnt = pRefStreetVertices.pointCollection.PointCount;
                List <VerticesDist> lstVerDist = new List <VerticesDist>();

                IEnumVertex2 pEnumVertex = pRefStreetVertices.pointCollection.EnumVertices as IEnumVertex2;
                pEnumVertex.Reset();
                //Get the next vertex
                IPoint outVertex;
                int    partIndex;
                int    vertexIndex;
                pEnumVertex.Next(out outVertex, out partIndex, out vertexIndex);

                while (outVertex != null)
                {
                    VerticesDist pVerDist = new VerticesDist();
                    pVerDist.x        = outVertex.X;
                    pVerDist.y        = outVertex.Y;
                    pVerDist.ID       = vertexIndex;
                    pVerDist.Distance = GetDistance(p.x, p.y, pVerDist.x, pVerDist.y);
                    lstVerDist.Add(pVerDist);
                    pEnumVertex.Next(out outVertex, out partIndex, out vertexIndex);
                }

                int         intMinDistIdx = lstVerDist.FindIndex(x => x.Distance == lstVerDist.Min(t => t.Distance));
                TargetPoint l1            = new TargetPoint();
                l1.x = lstVerDist[intMinDistIdx].x;
                l1.y = lstVerDist[intMinDistIdx].y;

                TargetPoint l2             = new TargetPoint();
                TargetPoint pMovedRefPoint = new TargetPoint();

                int intSecondMinDistIdx = 0;
                if (intMinDistIdx == 0)
                {
                    intSecondMinDistIdx = intMinDistIdx + 1;
                    l2.x           = lstVerDist[intSecondMinDistIdx].x;
                    l2.y           = lstVerDist[intSecondMinDistIdx].y;
                    pMovedRefPoint = GetMovedReferencePoint(p, l1, l2);
                }
                else if (intMinDistIdx == lstVerDist.Count - 1)
                {
                    intSecondMinDistIdx = intMinDistIdx - 1;
                    l2.x           = lstVerDist[intSecondMinDistIdx].x;
                    l2.y           = lstVerDist[intSecondMinDistIdx].y;
                    pMovedRefPoint = GetMovedReferencePoint(p, l1, l2);
                }
                else
                {
                    TargetPoint pCandPt1 = new TargetPoint();
                    TargetPoint pCandPt2 = new TargetPoint();

                    intSecondMinDistIdx = intMinDistIdx - 1;
                    l2.x     = lstVerDist[intSecondMinDistIdx].x;
                    l2.y     = lstVerDist[intSecondMinDistIdx].y;
                    pCandPt1 = GetMovedReferencePoint(p, l1, l2);

                    intSecondMinDistIdx = intMinDistIdx + 1;
                    l2.x = lstVerDist[intSecondMinDistIdx].x;
                    l2.y = lstVerDist[intSecondMinDistIdx].y;

                    if (pCandPt1 == null)
                    {
                        pMovedRefPoint = GetMovedReferencePoint(p, l1, l2);
                    }
                    else
                    {
                        pCandPt2 = GetMovedReferencePoint(p, l1, l2);

                        if (pCandPt2 != null)
                        {
                            double distToCPt1 = GetDistance(p.x, p.y, pCandPt1.x, pCandPt1.y);
                            double distToCPt2 = GetDistance(p.x, p.y, pCandPt2.x, pCandPt2.y);

                            if (distToCPt1 > distToCPt2)
                            {
                                pMovedRefPoint = pCandPt2;
                            }
                            else
                            {
                                pMovedRefPoint = pCandPt1;
                            }
                        }
                        else
                        {
                            pMovedRefPoint = pCandPt1;
                        }
                    }
                }

                if (pMovedRefPoint == null)
                {
                    pMovedRefPoint = l1;
                    intFlag        = 1;
                }


                pFeature.set_Value(intXNewFldIdx, pMovedRefPoint.x);
                pFeature.set_Value(intYNewFldIdx, pMovedRefPoint.y);
                pFeature.set_Value(intFlagFldIdx, intFlag);
                pFeature.Store();

                pFeature = pFCursor.NextFeature();
            }

            MessageBox.Show("Done");
            ////Spatial Reference from Reference dataseat
            //IGeoDataset geoDataset = pRefFClass as IGeoDataset;
            //ISpatialReference pSpatialRef = geoDataset.SpatialReference;

            ////Create ShapeFile First
            //string strOutput = txtOutput.Text;
            //if (strOutput == "")
            //    return;
            //string strOutputSource = System.IO.Path.GetDirectoryName(strOutput);
            //string strOutputFile = System.IO.Path.GetFileName(strOutput);
            ////IFeatureClass pFClass = CreateShapeFile(strOutputSource, strOutputFile, pSpatialRef, esriGeometryType.esriGeometryPoint);
        }
Ejemplo n.º 16
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                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();

                //Close Results form, if it is opend.
                CloseOpendResultForm(m_pHandle);
                IGraphicsContainer pGraphicContainer = m_pActiveView.GraphicsContainer;
                pGraphicContainer.DeleteAllElements();

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

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

                IFeatureLayer pFLayer = pLayer as IFeatureLayer;
                //IFeatureClass pFClass = pFLayer.FeatureClass;
                m_intNFeature = 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 strVarNM  = (string)cboFieldName.SelectedItem;
                int    intVarIdx = m_pFClass.FindField(strVarNM);

                //Store Variable at Array
                double[] arrVar = new double[m_intNFeature];
                m_arrXYCoord = new double[m_intNFeature, 2];

                int    i = 0;
                IArea  pArea;
                IPoint pPoint;
                while (pFeature != null)
                {
                    if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        pArea = (IArea)pFeature.Shape;
                        m_arrXYCoord[i, 0] = pArea.Centroid.X;
                        m_arrXYCoord[i, 1] = pArea.Centroid.Y;
                    }
                    else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        pPoint             = (IPoint)pFeature.Shape;
                        m_arrXYCoord[i, 0] = pPoint.X;
                        m_arrXYCoord[i, 1] = pPoint.Y;
                    }

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

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

                    if (strNameR == null)
                    {
                        return;
                    }

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


                    int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress);
                    if (intSuccess == 0)
                    {
                        return;
                    }
                }
                ////Get the file path and name to create spatial weight matrix
                //string strNameR = m_pSnippet.FilePathinRfromLayer(pFLayer);

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

                //int intSuccess = 0;

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

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

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

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

                //Creat Higher spatial lag
                int intMaxLag = Convert.ToInt32(nudLagOrder.Value);
                try
                {
                    m_pEngine.Evaluate("sample.nblags <- nblag(sample.nb, maxlag = " + intMaxLag.ToString() + ")");
                }
                catch
                {
                    MessageBox.Show("Please reduce the maximum lag order");
                }

                m_arrResults      = new double[intMaxLag][];
                m_arrMaxToLinks   = new double[intMaxLag][];
                m_arrMaxFromLinks = new double[intMaxLag];
                pChart.Series.Clear();

                //Plot command for R
                StringBuilder plotCommmand = new StringBuilder();
                NumericVector vecVar       = m_pEngine.CreateNumericVector(arrVar);
                m_pEngine.SetSymbol(strVarNM, vecVar);

                bool blnZeroPolicy = false;
                //Store Information of spatial lag
                for (int j = 0; j < intMaxLag; j++)
                {
                    m_arrResults[j] = new double[5];
                    m_pEngine.Evaluate("card.sample <- card(sample.nblags[[" + (j + 1).ToString() + "]])");
                    m_arrResults[j][0] = m_pEngine.Evaluate("sum(card.sample)").AsNumeric().First();

                    //If ther is no link, return
                    if (m_arrResults[j][0] == 0)
                    {
                        MessageBox.Show("There is no link at " + (j + 1).ToString() + " order.");
                        return;
                    }

                    //Functions below are used for brushing on map control, they are under reviewing 080316 HK
                    //m_arrMaxFromLinks[j] = m_pEngine.Evaluate("which.max(card.sample)").AsNumeric().First();
                    //m_arrMaxToLinks[j] = m_pEngine.Evaluate("sample.nblags[[" + (j + 1).ToString() + "]][[which.max(card.sample)]]").AsNumeric().ToArray();


                    //Select method
                    if (cboSAM.Text == "Moran Coefficient")
                    {
                        try
                        {
                            m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W')");
                        }
                        catch
                        {
                            DialogResult dialogResult = new DialogResult();
                            if (blnZeroPolicy == false)
                            {
                                dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);
                            }


                            if (dialogResult == DialogResult.Yes || blnZeroPolicy == true)
                            {
                                m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W', zero.policy=TRUE)");
                                blnZeroPolicy = true;
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return;
                            }
                        }

                        plotCommmand.Append("sam.result <- moran.test(" + strVarNM + ", sample.listw, ");

                        //select assumption
                        if (cboAssumption.Text == "Normality")
                        {
                            plotCommmand.Append("randomisation=FALSE, alternative ='two.sided', zero.policy=TRUE)");
                        }
                        else if (cboAssumption.Text == "Randomization")
                        {
                            plotCommmand.Append("randomisation=TRUE, alternative ='two.sided', zero.policy=TRUE)");
                        }
                    }
                    else if (cboSAM.Text == "Geary Ratio")
                    {
                        try
                        {
                            m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W')");
                        }
                        catch
                        {
                            DialogResult dialogResult = new DialogResult();
                            if (blnZeroPolicy == false)
                            {
                                dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);
                            }


                            if (dialogResult == DialogResult.Yes || blnZeroPolicy == true)
                            {
                                m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W', zero.policy=TRUE)");
                                blnZeroPolicy = true;
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return;
                            }
                        }

                        plotCommmand.Append("sam.result <- geary.test(" + strVarNM + ", sample.listw, ");

                        //select assumption
                        if (cboAssumption.Text == "Normality")
                        {
                            plotCommmand.Append("randomisation=FALSE, alternative ='two.sided', zero.policy=TRUE)");
                        }
                        else if (cboAssumption.Text == "Randomization")
                        {
                            plotCommmand.Append("randomisation=TRUE, alternative ='two.sided', zero.policy=TRUE)");
                        }
                    }
                    else if (cboSAM.Text == "Global G Statistic")
                    {
                        try
                        {
                            m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W')");
                        }
                        catch
                        {
                            DialogResult dialogResult = new DialogResult();
                            if (blnZeroPolicy == false)
                            {
                                dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);
                            }


                            if (dialogResult == DialogResult.Yes || blnZeroPolicy == true)
                            {
                                m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='B', zero.policy=TRUE)");
                                blnZeroPolicy = true;
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return;
                            }
                        }
                        plotCommmand.Append("sam.result <- globalG.test(" + strVarNM + ", sample.listw, alternative ='two.sided', zero.policy=TRUE)");
                    }

                    m_pEngine.Evaluate(plotCommmand.ToString());
                    plotCommmand.Clear();
                    NumericVector vecResults = m_pEngine.Evaluate("sam.result$estimate").AsNumeric();
                    m_arrResults[j][1] = vecResults[0];
                    m_arrResults[j][2] = vecResults[1];
                    m_arrResults[j][3] = vecResults[2];
                    m_arrResults[j][4] = m_pEngine.Evaluate("sam.result$p.value").AsNumeric().First();

                    double dblXmin = (j + 1) - 0.2;
                    double dblXmax = (j + 1) + 0.2;
                    double dblYmax = vecResults[0] + (Math.Sqrt(vecResults[2]) * 1.96);
                    double dblYmin = vecResults[0] - (Math.Sqrt(vecResults[2]) * 1.96);


                    AddLineSeries(pChart, "min_" + j.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, dblYmin, dblYmin);
                    AddLineSeries(pChart, "max_" + j.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, dblYmax, dblYmax);
                    AddLineSeries(pChart, "rg_" + j.ToString(), Color.Black, 1, ChartDashStyle.Solid, (j + 1), (j + 1), dblYmin, dblYmax);
                }

                //pEngine.Evaluate("sample.nb <- poly2nb(sample.shp);sample.listw <- nb2listw(sample.nb, style='W')");

                double dblExp = m_arrResults[0][2];
                AddLineSeries(pChart, "ex", Color.Red, 1, ChartDashStyle.Dash, 0.5, intMaxLag + 0.5, dblExp, dblExp);

                var pSeries = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name            = "Point",
                    Color           = Color.Black,
                    IsXValueIndexed = false,
                    ChartType       = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                    MarkerStyle     = MarkerStyle.Circle,
                };
                pChart.Series.Add(pSeries);


                for (int j = 0; j < intMaxLag; j++)
                {
                    pSeries.Points.AddXY((j + 1), m_arrResults[j][1]);
                }

                m_intTotalNSeries = pChart.Series.Count;

                //Chart Design
                pChart.ChartAreas[0].AxisX.Title                 = "Spatial Lag";
                pChart.ChartAreas[0].AxisY.Title                 = cboSAM.Text;
                pChart.ChartAreas[0].AxisY.IsStartedFromZero     = false;
                pChart.ChartAreas[0].AxisX.Maximum               = intMaxLag + 0.5;
                pChart.ChartAreas[0].AxisX.Minimum               = 0.5;
                pChart.ChartAreas[0].AxisX.MajorTickMark.Enabled = false; //need to be updated 042816 HK

                pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false;

                for (int j = 0; j < intMaxLag; j++)
                {
                    int intXvalue = j + 1;

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

                    CustomLabel pcutsomLabel = new CustomLabel();
                    pcutsomLabel.FromPosition = dblXmin;
                    pcutsomLabel.ToPosition   = dblXmax;
                    pcutsomLabel.Text         = intXvalue.ToString();

                    pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel);
                }
                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 17
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            frmProgress pfrmProgress = new frmProgress();

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

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

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


            clsSnippet pSnippet = new clsSnippet();


            // Gets the variable names and indices
            BhattaVariables[] pBVariable = new BhattaVariables[intnVar];

            int nFeature = m_pFClass.FeatureCount(null);

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

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

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

                //pBVariable.Add(tmp);
                pBVariable[j] = new BhattaVariables();
                pBVariable[j].variableNames = (string)dgvVariables.Rows[j].Cells[0].Value;
                pBVariable[j].errorNames    = (string)dgvVariables.Rows[j].Cells[1].Value;

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

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

            //Get values of var and error from shp file
            IFeatureCursor pFCursor = m_pFClass.Search(null, true);
            IFeature       pFeature = pFCursor.NextFeature();

            //Store independent values at Array

            int i = 0;

            while (pFeature != null)
            {
                for (int j = 0; j < intnVar; j++)
                {
                    //arrInDepen[j] = new double[nFeature];
                    pBVariable[j].arrVar[i]   = Convert.ToDouble(pFeature.get_Value(pBVariable[j].idVar));
                    pBVariable[j].arrError[i] = Convert.ToDouble(pFeature.get_Value(pBVariable[j].idError));
                }

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

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

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

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

                //Need to optimize 12132017 HK
                for (int k = 0; k < nFeature; k++)
                {
                    for (int l = 0; l < k + 1; l++)
                    {
                        for (int j = 0; j < 4; j++)
                        {
                            plotCommmand[j] = new StringBuilder();
                        }

                        plotCommmand[0].Append("x1 <- cbind(");
                        plotCommmand[1].Append("x2 <- cbind(");
                        plotCommmand[2].Append("v1 <- cbind(");
                        plotCommmand[3].Append("v2 <- cbind(");

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

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


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

                pfrmProgress.lblStatus.Text = "Finding Clusters";

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

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

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

                pfrmProgress.lblStatus.Text = "Finding Clusters";

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

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

            pSnippet.drawPlottoForm(strTitle, strCommand);

            int intNClasses = Convert.ToInt32(nudNClasses.Value);

            m_pEngine.Evaluate("sample.cut <- cutree(sample.hclu, " + intNClasses.ToString() + ")");

            //Save Outputs in SHP
            pfrmProgress.lblStatus.Text = "Save Results";
            //The field names are related with string[] DeterminedName in clsSnippet
            string strOutputFldName = txtOutputFld.Text;

            //Get EVs and residuals
            NumericVector nvClasses = m_pEngine.Evaluate("sample.cut").AsNumeric();

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

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


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

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

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

                pFCursor.UpdateFeature(pFeature);

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

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


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

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

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


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

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

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

            //geoFeatureLayer.Renderer = uniqueValueRenderer as IFeatureRenderer;

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

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


            pfrmProgress.Close();
        }
Ejemplo n.º 18
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
                {
                    MessageBox.Show("Please select target field");
                    return;
                }

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

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

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

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

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

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

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

                int i = 0;

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

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

                string strStartPath = m_pForm.strPath;
                string pathr        = strStartPath.Replace(@"\", @"/");
                pEngine.Evaluate("source('" + pathr + "/AllFunctions_LeeL.R')");

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

                if (strNameR == null)
                {
                    return;
                }

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

                if (txtSWM.Text == "Default")
                {
                    pEngine.Evaluate("sample.nb <- poly2nb(sample.shp)");
                }
                else
                {
                    int intResult = m_pSnippet.SWMusingGAL(pEngine, pFClass, txtSWM.Text);
                    if (intResult == -1)
                    {
                        return;
                    }
                }

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

                string strSigLv     = nudSigLv.Value.ToString();
                string strSigMethod = cboSigMethod.Text;

                if (cboSAM.Text == "Lee's L")
                {
                    #region Li
                    pEngine.Evaluate("sample.l <- L.local.test(sample.v1, sample.v2, 1:length(sample.nb), sample.nb, style='W', sig.levels=c(" + strSigLv + "), method='" + strSigMethod + "', alternative='two.sided', diag.zero=FALSE)");

                    double[] dblLValues = pEngine.Evaluate("sample.l$local.L").AsNumeric().ToArray();
                    double[] dblPvalues = pEngine.Evaluate("sample.l$pvalue").AsNumeric().ToArray();
                    string[] strFlgs    = pEngine.Evaluate("as.character(sample.l$sig)").AsCharacter().ToArray();

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

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

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

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

                        pFCursor.UpdateFeature(pFeature);

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

                    pfrmProgress.Close();

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

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

                        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;

                        IFeatureLayer pNewFLayer = new FeatureLayerClass();
                        pNewFLayer.FeatureClass = pFClass;
                        pNewFLayer.Name         = cboSAM.Text + " of " + 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
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 19
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();


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

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

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

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

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

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

                    if (strNameR == null)
                    {
                        return;
                    }

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


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

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

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

                //int intSuccess = 0;


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

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

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

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


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

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

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

                int i = 0;

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

                IArea  pArea;
                IPoint pPoint;

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

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


                //Collect NB for Brushing and linking

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

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

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

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

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

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

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

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

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

                pfrmMScatterResult.pChart.Series.Add(seriesPts);

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



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

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

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

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

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

                pfrmMScatterResult.pChart.Series.Add(seriesLine);

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

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

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

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

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

                pfrmMScatterResult.Show();
                pfrmProgress.Close();
                //this.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Ejemplo n.º 20
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

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

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

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

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

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

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

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

            int i = 0;

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

            pFCursor.Flush();

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

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

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

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

            if (strNameR == null)
            {
                return;
            }

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

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

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

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

            string strRSigLv  = nudRsigLv.Value.ToString();
            string strLSigLv  = nudLsigLv.Value.ToString();
            string strLSig    = cboLocalL.Text;
            string strRsig    = cboLocalPearson.Text;
            string strRowStd  = cboRowStandardization.Text;
            string strNonZero = null;

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

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

            string[] strSPOutliers = pEngine.Evaluate("as.character(sample.result$sp.outlier)").AsCharacter().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 (pFClass.FindField(strfldName) == -1)
                {
                    IField     newField  = new FieldClass();
                    IFieldEdit fieldEdit = (IFieldEdit)newField;
                    fieldEdit.Name_2 = strfldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    pFClass.AddField(newField);
                }
            }

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

            string strSpOutlierFldName = lvFields.Items[0].SubItems[1].Text;
            int    intSpOutlierFldIdx  = pFClass.FindField(strSpOutlierFldName);

            int featureIdx = 0;

            while (pFeature != null)
            {
                pFeature.set_Value(intSpOutlierFldIdx, strSPOutliers[featureIdx]);

                pFCursor.UpdateFeature(pFeature);

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

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

                IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass();
                pUniqueValueRenderer.FieldCount = 1;
                pUniqueValueRenderer.set_Field(0, strSpOutlierFldName);
                if (cboMaptype.Text == "choropleth map")
                {
                    ISimpleFillSymbol pSymbol;
                    IQueryFilter      pQFilter = new QueryFilterClass();
                    int    intTotalCount       = 0;
                    string strLabel            = null;

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

                        pQFilter.WhereClause = strSpOutlierFldName + " = '" + m_pOutlierSymbols[j].Value + "'";

                        intTotalCount = pTable.RowCount(pQFilter);

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

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

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

                        pSymbol.Angle = m_pOutlierSymbols[j].Angle;

                        pQFilter.WhereClause = strSpOutlierFldName + " = '" + m_pOutlierSymbols[j].Value + "'";

                        intTotalCount = pTable.RowCount(pQFilter);

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

                pfrmProgress.Close();
            }
            else
            {
                MessageBox.Show("Complete. The results are stored in the shape file");
            }
        }
Ejemplo n.º 21
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (cboFldnm1.Text == "" || cboFldnm2.Text == "")
            {
                MessageBox.Show("Please select target field");
                return;
            }

            frmProgress pfrmProgress = new frmProgress();

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

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

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

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

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

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

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

            int i = 0;

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

            pFCursor.Flush();

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

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

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

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

            if (strNameR == null)
            {
                return;
            }

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

            NumericVector vecVar1 = pEngine.CreateNumericVector(arrVar1);

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

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

            string strSigLv   = nudSigLv.Value.ToString();
            string strLSig    = cboLocalL.Text;
            string strRsig    = cboLocalPearson.Text;
            string strRowStd  = cboRowStandardization.Text;
            string strNonZero = null;

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

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

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

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

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

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

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

            int featureIdx = 0;

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

                pFCursor.UpdateFeature(pFeature);

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

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

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

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


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

                        intSigIdx = 3;

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

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

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

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

                pUniqueValueRenderer.UseDefaultSymbol = false;

                IFeatureLayer pNewFLayer = new FeatureLayerClass();
                pNewFLayer.FeatureClass = pFClass;
                pNewFLayer.Name         = "Bivariate Spatial Clusters";
                IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer;
                pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer;
                m_pActiveView.FocusMap.AddLayer(pGFLayer);
                m_pActiveView.Refresh();
                m_pForm.axTOCControl1.Update();
                pfrmProgress.Close();
            }
            else
            {
                MessageBox.Show("Complete. The results are stored in the shape file");
            }
        }
Ejemplo n.º 22
0
        private double[] ClassSeparabilityMeasure(int intNClasses, int intNFeatures, IFeatureCursor pFCursor, int intEstIdx, int intVarIdx)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                if (intNFeatures > MaxFeaturesforPGB)
                {
                    pfrmProgress.lblStatus.Text    = "Calculate Class Separabilities";
                    pfrmProgress.pgbProgress.Style = ProgressBarStyle.Blocks;
                    pfrmProgress.pgbProgress.Value = 0;
                    pfrmProgress.Show();
                }

                double[] Cs = new double[intNClasses + 1];

                arrEst     = new double[intNFeatures];
                arrVar     = new double[intNFeatures];
                arrResults = new double[intNFeatures - 1];
                double[] arrSortedResult = new double[intNFeatures - 1];

                IFeature pFeature = pFCursor.NextFeature();
                int      k        = 0;
                while (pFeature != null)
                {
                    arrEst[k] = Convert.ToDouble(pFeature.get_Value(intEstIdx));
                    arrVar[k] = Convert.ToDouble(pFeature.get_Value(intVarIdx));
                    k++;
                    pFeature = pFCursor.NextFeature();
                }

                for (int i = 0; i < intNFeatures - 1; i++)
                {
                    double dblCLMin = double.MaxValue; // needs to be changed to p-value 09.25.15 HK
                    double dblCL    = 0;
                    for (int m = i; m >= 0; m--)
                    {
                        for (int n = (i + 1); n < intNFeatures; n++)
                        {
                            dblCL = Math.Abs(arrEst[n] - arrEst[m]) / (Math.Sqrt(Math.Pow(arrVar[n], 2) + Math.Pow(arrVar[m], 2)));
                            if (dblCL < dblCLMin)
                            {
                                dblCLMin = dblCL;
                            }
                        }
                    }
                    arrResults[i]      = dblCLMin;
                    arrSortedResult[i] = dblCLMin;

                    if (intNFeatures > MaxFeaturesforPGB)
                    {
                        pfrmProgress.pgbProgress.Value = (i * 100) / intNFeatures;
                    }
                }

                if (intNFeatures > MaxFeaturesforPGB)
                {
                    pfrmProgress.pgbProgress.Value = 100;
                    pfrmProgress.lblStatus.Text    = "Show Results";
                }

                System.Array.Sort <double>(arrSortedResult, new Comparison <double>(
                                               (i1, i2) => i2.CompareTo(i1)
                                               ));

                Chart pChart = new Chart();

                dblpValue    = new double[intNClasses - 1];
                intResultIdx = new int[intNClasses - 1];
                for (int i = 0; i < intNClasses - 1; i++)
                {
                    intResultIdx[i] = System.Array.IndexOf(arrResults, arrSortedResult[i]);
                    //dblpValue[i] = pChart.DataManipulator.Statistics.NormalDistribution(arrSortedResult[i]);
                }
                System.Array.Sort(intResultIdx);

                Cs[0] = arrEst.Min();

                Cs[intNClasses] = arrEst.Max();
                for (int i = 0; i < intNClasses - 1; i++)
                {
                    Cs[i + 1]    = arrEst[intResultIdx[i]];
                    dblpValue[i] = pChart.DataManipulator.Statistics.NormalDistribution(arrResults[intResultIdx[i]]);
                }

                pfrmProgress.Close();
                return(Cs);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this.Handle.ToString() + " Error:" + ex.Message);
                return(null);
            }
        }
Ejemplo n.º 23
0
        private void btnSave_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 = cvEVName[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)nmEVs[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.º 24
0
        private void CalKhatWithEgde()
        {
            frmProgress pfrmProgress = new frmProgress();

            pfrmProgress.bgWorker.ReportProgress(0);
            pfrmProgress.lblStatus.Text = "Caculate Lhat";
            pfrmProgress.Show();

            m_dblBeginDist = Convert.ToDouble(nudBeginDist.Value);
            m_dblDistInc   = Convert.ToDouble(nudDistInc.Value);
            int intNDistBnd = Convert.ToInt32(nudNDistBands.Value);

            m_arrResultIdxs = new List <int> [intNDistBnd];
            for (int j = 0; j < intNDistBnd; j++)
            {
                m_arrResultIdxs[j] = new List <int>();
            }

            int intNFeatureCount = 0;

            IFeatureCursor pFCursor1 = m_pFClass.Search(null, false);

            intNFeatureCount = m_pFClass.FeatureCount(null);

            if (intNFeatureCount == 0)
            {
                return;
            }

            int intTotalFlowCnt = intNFeatureCount * (intNFeatureCount - 1);

            m_arrValue = new double[intTotalFlowCnt][];

            IFeature pFeature1 = pFCursor1.NextFeature();

            double[,] arrXYPts = new double[intNFeatureCount, 2];
            IPoint pPoint1;
            int    i = 0;

            while (pFeature1 != null)
            {
                pPoint1 = pFeature1.Shape as IPoint;

                arrXYPts[i, 0] = pPoint1.X;
                arrXYPts[i, 1] = pPoint1.Y;
                i++;
                pFeature1 = pFCursor1.NextFeature();
            }

            //For Edge Correction
            var watch = Stopwatch.StartNew();

            double[][] dblWeightCnt = EdgeCorrection(intNFeatureCount, intNDistBnd, m_pFeature, arrXYPts, m_dblDistInc, m_dblBeginDist);

            watch.Stop();
            double dblTime = watch.ElapsedMilliseconds;

            //For Edge Correction


            double[] arrResultCnt = new double[intNDistBnd];
            i = 0;
            for (int j = 0; j < intNFeatureCount; j++)
            {
                for (int k = 0; k < intNFeatureCount; k++)
                {
                    if (j != k)
                    {
                        int intProgress = i * 100 / intTotalFlowCnt;
                        pfrmProgress.bgWorker.ReportProgress(intProgress);

                        m_arrValue[i]    = new double[5];
                        m_arrValue[i][0] = arrXYPts[j, 0];
                        m_arrValue[i][1] = arrXYPts[j, 1];
                        m_arrValue[i][2] = arrXYPts[k, 0];
                        m_arrValue[i][3] = arrXYPts[k, 1];
                        m_arrValue[i][4] = Math.Sqrt(Math.Pow(arrXYPts[j, 0] - arrXYPts[k, 0], 2) + Math.Pow(arrXYPts[j, 1] - arrXYPts[k, 1], 2));

                        for (int l = 1; l <= intNDistBnd; l++)
                        {
                            double dblRefDist = l * m_dblDistInc + m_dblBeginDist;
                            if (m_arrValue[i][4] < dblRefDist)
                            {
                                m_arrResultIdxs[l - 1].Add(i);
                                arrResultCnt[l - 1] = arrResultCnt[l - 1] + dblWeightCnt[j][l - 1];
                            }
                        }
                        i++;
                    }
                }
            }

            pChart.Series.Clear();

            var pSeries = new System.Windows.Forms.DataVisualization.Charting.Series
            {
                Name              = "ObsLine",
                Color             = Color.Red,
                IsVisibleInLegend = false,
                ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line,
            };

            pChart.Series.Add(pSeries);

            double dblConstant = m_dblArea / Math.Pow(intNFeatureCount, 2);

            for (int j = 0; j < intNDistBnd; j++)
            {
                double dblRefDist = (j + 1) * m_dblDistInc + m_dblBeginDist;
                //double dblDenorm = Math.PI * Math.Pow(dblRefDist, 2);

                double dblKhat = (arrResultCnt[j] * dblConstant); // Kfunction
                //pSeries.Points.AddXY(dblRefDist, dblKhat);

                double dblLhat = Math.Sqrt(dblKhat / Math.PI) - dblRefDist;
                pSeries.Points.AddXY(dblRefDist, dblLhat); //LFunction
            }
            m_intTotalNSeries = 1;



            //Permutation
            if (chkConfBnd.Checked)
            {
                pfrmProgress.bgWorker.ReportProgress(0);
                pfrmProgress.lblStatus.Text = "Caculate Confidence Bound";

                IEnvelope pEnv = m_pFLayer.AreaOfInterest;

                int intNPermutation = Convert.ToInt32(nudNPermutation.Value);
                double[,] arrConfBnds = new double[intNDistBnd, 2];
                for (int j = 0; j < intNDistBnd; j++)
                {
                    arrConfBnds[j, 0] = double.MinValue;
                    arrConfBnds[j, 1] = double.MaxValue;
                }

                for (int p = 0; p < intNPermutation; p++)
                {
                    int intProgress = p * 100 / intNPermutation;
                    pfrmProgress.bgWorker.ReportProgress(intProgress);

                    double[,] arrRndPts = RndPtswithStudyArea(intNFeatureCount, pEnv, m_pFeature);

                    //EdgeCorrection
                    double[][] dblPermWeightCnt = EdgeCorrection(intNFeatureCount, intNDistBnd, m_pFeature, arrRndPts, m_dblDistInc, m_dblBeginDist);

                    double[] arrPermCount = new double[intNDistBnd];
                    double   dblEstDist   = 0;

                    for (int j = 0; j < intNFeatureCount; j++)
                    {
                        for (int k = 0; k < intNFeatureCount; k++)
                        {
                            if (j != k)
                            {
                                dblEstDist = Math.Sqrt(Math.Pow(arrRndPts[j, 0] - arrRndPts[k, 0], 2) + Math.Pow(arrRndPts[j, 1] - arrRndPts[k, 1], 2));
                                for (int l = 1; l <= intNDistBnd; l++)
                                {
                                    double dblRefDist = l * m_dblDistInc + m_dblBeginDist;
                                    if (dblEstDist < dblRefDist)
                                    {
                                        arrPermCount[l - 1] = dblPermWeightCnt[j][l - 1] + arrPermCount[l - 1];
                                    }
                                }
                            }
                        }
                    }

                    for (int j = 0; j < intNDistBnd; j++)
                    {
                        double dblRefDist = (j + 1) * m_dblDistInc + m_dblBeginDist;
                        double dblKhat    = (arrPermCount[j] * dblConstant); // Kfunction
                        double dblLhat    = Math.Sqrt(dblKhat / Math.PI) - dblRefDist;

                        if (dblLhat > arrConfBnds[j, 0])
                        {
                            arrConfBnds[j, 0] = dblLhat;
                        }

                        if (dblLhat < arrConfBnds[j, 1])
                        {
                            arrConfBnds[j, 1] = dblLhat;
                        }
                    }
                }

                var pMaxSeries = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name              = "MaxLine",
                    Color             = Color.Gray,
                    IsVisibleInLegend = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line,
                };
                pChart.Series.Add(pMaxSeries);

                var pMinSeries = new System.Windows.Forms.DataVisualization.Charting.Series
                {
                    Name              = "MinLine",
                    Color             = Color.Gray,
                    IsVisibleInLegend = false,
                    ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line,
                };
                pChart.Series.Add(pMinSeries);

                for (int j = 0; j < intNDistBnd; j++)
                {
                    double dblRefDist = (j + 1) * m_dblDistInc + m_dblBeginDist;

                    pMaxSeries.Points.AddXY(dblRefDist, arrConfBnds[j, 0]);
                    pMinSeries.Points.AddXY(dblRefDist, arrConfBnds[j, 1]);
                }

                m_intTotalNSeries = 3;
            }

            pfrmProgress.Close();
        }
Ejemplo n.º 25
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                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();

                //Decimal places
                int intDeciPlaces = 5;

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

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

                //pFLayer = pLayer as IFeatureLayer;
                //pFClass = pFLayer.FeatureClass;
                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  = cboFieldName.Text;
                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;
                    }
                }

                //pEngine.Evaluate("sample.nb <- poly2nb(sample.shp);sample.listw <- nb2listw(sample.nb, style='W')");
                NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar);
                m_pEngine.SetSymbol(strVarNM, vecVar);
                plotCommmand.Append("sam.result <- ");

                //Select method
                if (cboSAM.Text == "Moran Coefficient")
                {
                    plotCommmand.Append("moran.test");
                }
                else if (cboSAM.Text == "Geary Ratio")
                {
                    plotCommmand.Append("geary.test");
                }

                plotCommmand.Append("(" + strVarNM + ", sample.listw, ");

                //select assumption
                if (cboAssumption.Text == "Normality")
                {
                    plotCommmand.Append("randomisation=FALSE, , zero.policy=TRUE)");
                }
                else if (cboAssumption.Text == "Randomization")
                {
                    plotCommmand.Append("randomisation=TRUE, , zero.policy=TRUE)");
                }

                m_pEngine.Evaluate(plotCommmand.ToString());
                //Print Output
                string   strDecimalPlaces = "N" + intDeciPlaces.ToString();
                string[] strResults       = new string[7];
                strResults[0] = cboSAM.Text + " under " + cboAssumption.Text;
                strResults[1] = "";
                NumericVector vecResults = m_pEngine.Evaluate("sam.result$estimate").AsNumeric();
                strResults[2] = "Statistic: " + vecResults[0].ToString(strDecimalPlaces);
                strResults[3] = "Expectation: " + vecResults[1].ToString(strDecimalPlaces);
                strResults[4] = "Variance: " + vecResults[2].ToString(strDecimalPlaces);
                double dblStd  = m_pEngine.Evaluate("sam.result$statistic").AsNumeric().First();
                double dblPval = m_pEngine.Evaluate("sam.result$p.value").AsNumeric().First();
                strResults[5] = "Standard deviate: " + dblStd.ToString(strDecimalPlaces);
                if (dblPval < Math.Pow(0.1, intDeciPlaces))
                {
                    strResults[6] = "p-value: < 0.001";
                }
                else
                {
                    strResults[6] = "p-value: " + dblPval.ToString(strDecimalPlaces);
                }

                frmGenResult pfrmResult = new frmGenResult();
                pfrmResult.Text                = "Summary";
                pfrmResult.txtField.Text       = strVarNM;
                pfrmResult.txtStatistics.Lines = strResults;
                pfrmProgress.Close();
                pfrmResult.Show();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();

                return;
            }
        }
Ejemplo n.º 26
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();

            try
            {
                //REngine pEngine = m_pForm.pEngine;
                if (cboFieldName.Text == "")
                {
                    MessageBox.Show("Please select the dependent input variables to be used in the regression model.",
                                    "Please choose at least one input variable");
                }
                if (lstIndeVar.Items.Count == 0)
                {
                    MessageBox.Show("Please select independents input variables to be used in the regression model.",
                                    "Please choose at least one input variable");
                }



                //Decimal places
                int intDeciPlaces = 5;

                //Get number of Independent variables
                int nIndevarlistCnt = lstIndeVar.Items.Count;
                //Indicate an intercept only model (2) or a non-intercept model (1) or not (0)
                int intInterceptModel = 1;
                for (int j = 0; j < nIndevarlistCnt; j++)
                {
                    if ((string)lstIndeVar.Items[j] == "Intercept")
                    {
                        intInterceptModel = 0;
                    }
                }
                if (nIndevarlistCnt == 1 && intInterceptModel == 0)
                {
                    intInterceptModel = 2;
                }

                int nIDepen = 0;
                if (intInterceptModel == 0)
                {
                    nIDepen = nIndevarlistCnt - 1;
                }
                else if (intInterceptModel == 1)
                {
                    nIDepen = nIndevarlistCnt;
                }

                // Gets the column of the dependent variable
                String dependentName = (string)cboFieldName.SelectedItem;
                //sourceTable.AcceptChanges();
                //DataTable dependent = sourceTable.DefaultView.ToTable(false, dependentName);

                // Gets the columns of the independent variables
                String[] independentNames   = new string[nIDepen];
                int      intIdices          = 0;
                string   strIndependentName = "";
                for (int j = 0; j < nIndevarlistCnt; j++)
                {
                    strIndependentName = (string)lstIndeVar.Items[j];
                    if (strIndependentName != "Intercept")
                    {
                        independentNames[intIdices] = strIndependentName;
                        intIdices++;
                    }
                }
                // Creates the input and output matrices from the shapefile//
                clsSnippet pSnippet = new clsSnippet();

                int nFeature = m_pFClass.FeatureCount(null);

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

                //Get index for independent and dependent variables
                int   intDepenIdx = m_pFClass.Fields.FindField(dependentName);
                int[] idxes       = new int[nIDepen];

                for (int j = 0; j < nIDepen; j++)
                {
                    idxes[j] = m_pFClass.Fields.FindField(independentNames[j]);
                }


                //Store independent values at Array
                double[]   arrDepen   = new double[nFeature];
                double[][] arrInDepen = new double[nIDepen][]; //Zigzaged Array needs to be define

                for (int j = 0; j < nIDepen; j++)
                {
                    arrInDepen[j] = new double[nFeature];
                }

                int i = 0;
                while (pFeature != null)
                {
                    arrDepen[i] = Convert.ToDouble(pFeature.get_Value(intDepenIdx));

                    for (int j = 0; j < nIDepen; j++)
                    {
                        //arrInDepen[j] = new double[nFeature];
                        arrInDepen[j][i] = Convert.ToDouble(pFeature.get_Value(idxes[j]));
                        //arrInDepen[i, j] = Convert.ToDouble(pFeature.get_Value(idxes[j]));
                    }

                    i++;
                    pFeature = pFCursor.NextFeature();
                }
                pfrmProgress.lblStatus.Text = "Calculate Regression Coefficients";
                //Plot command for R
                StringBuilder plotCommmand = new StringBuilder();

                //Dependent variable to R vector
                NumericVector vecDepen = m_pEngine.CreateNumericVector(arrDepen);
                m_pEngine.SetSymbol(dependentName, vecDepen);
                plotCommmand.Append("lm(" + dependentName + "~");

                if (intInterceptModel == 2)
                {
                    plotCommmand.Append("1");
                }
                else
                {
                    for (int j = 0; j < nIDepen; j++)
                    {
                        NumericVector vecIndepen = m_pEngine.CreateNumericVector(arrInDepen[j]);
                        m_pEngine.SetSymbol(independentNames[j], vecIndepen);
                        plotCommmand.Append(independentNames[j] + "+");
                    }
                    plotCommmand.Remove(plotCommmand.Length - 1, 1);

                    if (intInterceptModel == 1)
                    {
                        plotCommmand.Append("-1");
                    }
                }


                plotCommmand.Append(")");
                m_pEngine.Evaluate("sum.lm <- summary(" + plotCommmand + ")");

                NumericMatrix matCoe = m_pEngine.Evaluate("as.matrix(sum.lm$coefficient)").AsNumericMatrix();
                NumericVector vecF   = m_pEngine.Evaluate("as.numeric(sum.lm$fstatistic)").AsNumeric();
                m_pEngine.Evaluate("fvalue <- as.numeric(sum.lm$fstatistic)");
                double        dblPValueF    = m_pEngine.Evaluate("pf(fvalue[1],fvalue[2],fvalue[3],lower.tail=F)").AsNumeric().First();
                double        dblRsqaure    = m_pEngine.Evaluate("sum.lm$r.squared").AsNumeric().First();
                double        dblAdjRsqaure = m_pEngine.Evaluate("sum.lm$adj.r.squared").AsNumeric().First();
                double        dblResiSE     = m_pEngine.Evaluate("sum.lm$sigma").AsNumeric().First();
                NumericVector vecResiDF     = m_pEngine.Evaluate("sum.lm$df").AsNumeric();

                double dblResiMC     = 0;
                double dblResiMCpVal = 0;

                if (chkResiAuto.Checked)
                {
                    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;
                        }
                    }


                    m_pEngine.Evaluate("sample.n <- length(sample.nb)");

                    //Calculate MC
                    if (cboAlternative.Text == "Greater")
                    {
                        m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'greater', zero.policy=TRUE)");
                    }
                    else if (cboAlternative.Text == "Less")
                    {
                        m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'less', zero.policy=TRUE)");
                    }
                    else if (cboAlternative.Text == "Two Sided")
                    {
                        m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'two.sided', zero.policy=TRUE)");
                    }
                    else
                    {
                        m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'greater', zero.policy=TRUE)");
                    }

                    dblResiMC     = m_pEngine.Evaluate("zmc$estimate[1]").AsNumeric().First();
                    dblResiMCpVal = m_pEngine.Evaluate("zmc$p.value").AsNumeric().First();
                }

                pfrmProgress.lblStatus.Text = "Printing Output:";
                //Open Ouput form
                frmRegResult pfrmRegResult = new frmRegResult();
                pfrmRegResult.Text = "Linear Regression Summary";

                //Create DataTable to store Result
                System.Data.DataTable tblRegResult = new DataTable("OLSResult");

                //Assign DataTable
                DataColumn dColName = new DataColumn();
                dColName.DataType   = System.Type.GetType("System.String");
                dColName.ColumnName = "Name";
                tblRegResult.Columns.Add(dColName);

                DataColumn dColValue = new DataColumn();
                dColValue.DataType   = System.Type.GetType("System.Double");
                dColValue.ColumnName = "Estimate";
                tblRegResult.Columns.Add(dColValue);

                DataColumn dColSE = new DataColumn();
                dColSE.DataType   = System.Type.GetType("System.Double");
                dColSE.ColumnName = "Std. Error";
                tblRegResult.Columns.Add(dColSE);

                DataColumn dColTValue = new DataColumn();
                dColTValue.DataType   = System.Type.GetType("System.Double");
                dColTValue.ColumnName = "t value";
                tblRegResult.Columns.Add(dColTValue);

                DataColumn dColPvT = new DataColumn();
                dColPvT.DataType   = System.Type.GetType("System.Double");
                dColPvT.ColumnName = "Pr(>|t|)";
                tblRegResult.Columns.Add(dColPvT);


                //Store Data Table by R result
                int intNCoeff = matCoe.RowCount;
                for (int j = 0; j < intNCoeff; j++)
                {
                    DataRow pDataRow = tblRegResult.NewRow();
                    if (j == 0 && intInterceptModel != 1)
                    {
                        pDataRow["Name"] = "(Intercept)";
                    }
                    else if (intInterceptModel == 1)
                    {
                        pDataRow["Name"] = independentNames[j];
                    }
                    else
                    {
                        pDataRow["Name"] = independentNames[j - 1];
                    }
                    pDataRow["Estimate"]   = Math.Round(matCoe[j, 0], intDeciPlaces);
                    pDataRow["Std. Error"] = Math.Round(matCoe[j, 1], intDeciPlaces);
                    pDataRow["t value"]    = Math.Round(matCoe[j, 2], intDeciPlaces);
                    pDataRow["Pr(>|t|)"]   = Math.Round(matCoe[j, 3], intDeciPlaces);
                    tblRegResult.Rows.Add(pDataRow);
                }

                //Assign Datagridview to Data Table
                pfrmRegResult.dgvResults.DataSource = tblRegResult;

                //Assign values at Textbox
                string[] strResults = null;
                if (chkResiAuto.Checked)
                {
                    strResults = new string[4];
                    if (dblResiMCpVal < 0.001)
                    {
                        strResults[3] = "MC of residuals: " + dblResiMC.ToString("N3") + ", p-value < 0.001";
                    }
                    else if (dblResiMCpVal > 0.999)
                    {
                        strResults[3] = "MC of residuals: " + dblResiMC.ToString("N3") + ", p-value > 0.999";
                    }
                    else
                    {
                        strResults[3] = "MC of residuals: " + dblResiMC.ToString("N3") + ", p-value: " + dblResiMCpVal.ToString("N3");
                    }
                }
                else
                {
                    strResults = new string[3];
                }

                strResults[0] = "Residual standard error: " + dblResiSE.ToString("N" + intDeciPlaces.ToString()) +
                                " on " + vecResiDF[1].ToString() + " degrees of freedom";
                strResults[1] = "Multiple R-squared: " + dblRsqaure.ToString("N" + intDeciPlaces.ToString()) +
                                ", Adjusted R-squared: " + dblAdjRsqaure.ToString("N" + intDeciPlaces.ToString());

                if (intInterceptModel != 2)
                {
                    if (dblPValueF < 0.001)
                    {
                        strResults[2] = "F-Statistic: " + vecF[0].ToString("N" + intDeciPlaces.ToString()) +
                                        " on " + vecF[1].ToString() + " and " + vecF[2].ToString() + " DF, p-value < 0.001";
                    }
                    else if (dblPValueF > 0.999)
                    {
                        strResults[2] = "F-Statistic: " + vecF[0].ToString("N" + intDeciPlaces.ToString()) +
                                        " on " + vecF[1].ToString() + " and " + vecF[2].ToString() + " DF, p-value > 0.999";
                    }
                    else
                    {
                        strResults[2] = "F-Statistic: " + vecF[0].ToString("N" + intDeciPlaces.ToString()) +
                                        " on " + vecF[1].ToString() + " and " + vecF[2].ToString() + " DF, p-value: " + dblPValueF.ToString("N" + intDeciPlaces.ToString());
                    }
                }
                else
                {
                    strResults[2] = "";
                }

                pfrmRegResult.txtOutput.Lines = strResults;
                pfrmRegResult.Show();

                //Create Plots for Regression
                if (chkPlots.Checked)
                {
                    string strTitle   = "Linear Regression Results";
                    string strCommand = "plot(" + plotCommmand + ");";

                    pSnippet.drawPlottoForm(strTitle, strCommand);
                }

                //Save Outputs in SHP
                if (chkSave.Checked)
                {
                    //The field names are related with string[] DeterminedName in clsSnippet
                    string strResiFldName = 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(strResiFldName) == -1)
                    {
                        //Add fields
                        IField     newField  = new FieldClass();
                        IFieldEdit fieldEdit = (IFieldEdit)newField;
                        fieldEdit.Name_2 = strResiFldName;
                        fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                        m_pFClass.AddField(newField);
                    }
                    else
                    {
                        DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " 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(strResiFldName);

                    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");
                }

                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog();
                pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                pfrmProgress.Close();
                return;
            }
        }
Ejemplo n.º 27
0
        private double[] BhattaDist(int intNClasses, int intNFeatures, IFeatureCursor pFCursor, int intEstIdx, int intVarIdx)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                if (intNFeatures > MaxFeaturesforPGB)
                {
                    pfrmProgress.lblStatus.Text    = "Calculate Bhattacharyya distance";
                    pfrmProgress.pgbProgress.Style = ProgressBarStyle.Blocks;
                    pfrmProgress.pgbProgress.Value = 0;
                    pfrmProgress.Show();
                }

                double[] Cs = new double[intNClasses + 1];

                arrEst = new double[intNFeatures];
                double[] arrVar = new double[intNFeatures];
                double[,] arrResults = new double[intNFeatures, intNFeatures];

                IFeature pFeature = pFCursor.NextFeature();
                int      k        = 0;
                while (pFeature != null)
                {
                    arrEst[k] = Convert.ToDouble(pFeature.get_Value(intEstIdx));
                    arrVar[k] = Convert.ToDouble(pFeature.get_Value(intVarIdx));
                    k++;
                    pFeature = pFCursor.NextFeature();
                }

                for (int i = 0; i < intNFeatures; i++)
                {
                    double dblsquaredVar1 = Math.Pow(arrVar[i], 2);

                    for (int j = 0; j < intNFeatures; j++)
                    {
                        double dblsquaredVar2 = Math.Pow(arrVar[j], 2);
                        double dblVarComp     = Math.Log(0.25 * ((dblsquaredVar1 / dblsquaredVar2) + (dblsquaredVar2 / dblsquaredVar1) + 2));
                        double dblMeanComp    = Math.Pow(arrEst[i] - arrEst[j], 2) / (dblsquaredVar1 + dblsquaredVar2);
                        arrResults[i, j] = 0.25 * (dblVarComp + dblMeanComp);
                    }

                    if (intNFeatures > MaxFeaturesforPGB)
                    {
                        pfrmProgress.pgbProgress.Value = (i * 100) / intNFeatures;
                    }
                }

                if (intNFeatures > MaxFeaturesforPGB)
                {
                    pfrmProgress.pgbProgress.Value = 100;
                    pfrmProgress.lblStatus.Text    = "Show Results";
                }

                NumericMatrix pBhattaDist = pEngine.CreateNumericMatrix(arrResults);
                pEngine.SetSymbol("Bhatta.diss", pBhattaDist);
                pEngine.Evaluate("library(cluster)");
                pEngine.Evaluate("kmed.result <- pam(as.dist(Bhatta.diss), diss=TRUE, " + intNClasses.ToString() + ")");
                NumericVector pClustering = pEngine.Evaluate("kmed.result$clustering").AsNumeric();

                Cs[0]           = arrEst.Min();
                Cs[intNClasses] = arrEst.Max();

                //double[] tempCs = new double[intNClasses + 1];
                //tempCs[0] = Cs[0];
                //tempCs[intNClasses] = Cs[intNClasses];

                for (int i = 0; i < intNFeatures; i++)
                {
                    for (int j = 1; j < intNClasses; j++)
                    {
                        if (pClustering[i] == j)
                        {
                            double tempClassMax = arrEst[i];
                            if (tempClassMax > Cs[j])
                            {
                                Cs[j] = tempClassMax;
                            }
                        }
                    }
                }

                pfrmProgress.Close();
                return(Cs);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this.Handle.ToString() + " Error:" + ex.Message);
                return(null);
            }
        }
Ejemplo n.º 28
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");
            }