Esempio n. 1
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            try
            {
                if (pfrmAttributeField.cboSourceLayer.Text != "" && pfrmAttributeField.cboValueField.Text != "")
                {
                    mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;

                    IActiveView pActiveView        = mForm.axMapControl1.ActiveView;
                    string      strTargetLayerName = pfrmAttributeField.cboSourceLayer.Text;
                    string      strValueField      = pfrmAttributeField.cboValueField.Text;

                    int    x      = X;
                    int    y      = Y;
                    IPoint pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);


                    double    Tol      = 4; //Needs to be changed
                    IEnvelope pEnvelop = pPoint.Envelope;
                    pEnvelop.Expand(Tol, Tol, false);
                    ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                    pSpatialFilter.Geometry   = pEnvelop;
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    clsSnippet pSnippet = new clsSnippet();

                    int intTLayerIdx = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName);

                    ILayer        pLayer         = mForm.axMapControl1.get_Layer(intTLayerIdx);
                    IFeatureLayer pFLayer        = (IFeatureLayer)pLayer;
                    string        ShapeFieldName = pFLayer.FeatureClass.ShapeFieldName;
                    pSpatialFilter.GeometryField = pFLayer.FeatureClass.ShapeFieldName;
                    IFeatureClass  pFeatureClass = pFLayer.FeatureClass;
                    IFeatureCursor pFCursor      = pFeatureClass.Search(pSpatialFilter, false);
                    IFeature       pFeature      = pFCursor.NextFeature();
                    pFCursor.Flush();
                    if (pFeature == null)
                    {
                        return;
                    }

                    int intValueFldIdx = pFeatureClass.FindField(strValueField);

                    double[] dblAllValue = pfrmAttributeField.arrValue;
                    double[] dblValue    = new double[1];
                    dblValue[0] = Convert.ToDouble(pFeature.get_Value(intValueFldIdx));
                    int           intCount    = pFeatureClass.FeatureCount(null);
                    REngine       pEngine     = mForm.pEngine;
                    NumericVector vecValue    = pEngine.CreateNumericVector(dblValue);
                    NumericVector vecAllValue = pEngine.CreateNumericVector(dblAllValue);
                    pEngine.SetSymbol("value", vecValue);
                    pEngine.SetSymbol("all.value", vecAllValue);

                    StringBuilder sbCommand = new StringBuilder();
                    sbCommand.Append("hist(all.value);");
                    sbCommand.Append("abline(v=value, col='red');");
                    string strTitle = "Histogram";

                    pSnippet.drawPlottoForm(strTitle, sbCommand.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("HistTool Error:" + ex.Message);
                return;
            }
        }
Esempio n. 2
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            if (pDrawDenplot.cboSourceLayer.Text != "" && pDrawDenplot.cboUField.Text != "" && pDrawDenplot.cboValueField.Text != "")
            {
                mForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;

                IActiveView pActiveView        = mForm.axMapControl1.ActiveView;
                string      strTargetLayerName = pDrawDenplot.cboSourceLayer.Text;
                string      strValueField      = pDrawDenplot.cboValueField.Text;
                string      strUncerField      = pDrawDenplot.cboUField.Text;


                int    x      = X;
                int    y      = Y;
                IPoint pPoint = pActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(x, y);


                double    Tol      = 4; //Needs to be changed
                IEnvelope pEnvelop = pPoint.Envelope;
                pEnvelop.Expand(Tol, Tol, false);
                ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                pSpatialFilter.Geometry   = pEnvelop;
                pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                clsSnippet pSnippet = new clsSnippet();

                int intTLayerIdx = pSnippet.GetIndexNumberFromLayerName(pActiveView, strTargetLayerName);

                ILayer        pLayer         = mForm.axMapControl1.get_Layer(intTLayerIdx);
                IFeatureLayer pFLayer        = (IFeatureLayer)pLayer;
                string        ShapeFieldName = pFLayer.FeatureClass.ShapeFieldName;
                pSpatialFilter.GeometryField = pFLayer.FeatureClass.ShapeFieldName;
                IFeatureClass  pFeatureClass = pFLayer.FeatureClass;
                IFeatureCursor pFCursor      = pFeatureClass.Search(pSpatialFilter, false);
                IFeature       pFeature      = pFCursor.NextFeature();
                pFCursor.Flush();
                if (pFeature == null)
                {
                    return;
                }

                int intValueFldIdx = pFeatureClass.FindField(strValueField);
                int intUncerFldIdx = pFeatureClass.FindField(strUncerField);


                double[] dblValue = new double[1];
                dblValue[0] = Convert.ToDouble(pFeature.get_Value(intValueFldIdx));
                double[] dblUncern = new double[1];
                dblUncern[0] = Convert.ToDouble(pFeature.get_Value(intUncerFldIdx));
                REngine       pEngine  = mForm.pEngine;
                NumericVector vecValue = pEngine.CreateNumericVector(dblValue);
                NumericVector vecSD    = pEngine.CreateNumericVector(dblUncern);
                pEngine.SetSymbol("samp.mean", vecValue);
                pEngine.SetSymbol("samp.sd", vecSD);

                pEngine.Evaluate("samp.xlim <- c(samp.mean-(samp.sd*3), samp.mean+(samp.sd*3))");
                pEngine.Evaluate("confLevel <- " + pDrawDenplot.nudConfiLevel.Value.ToString());
                pEngine.Evaluate("bothlevel <- 1-((100-confLevel)/200)");
                pEngine.Evaluate("error <- qnorm(bothlevel)*samp.sd");
                pEngine.Evaluate("confint <- c(samp.mean-error, samp.mean+error)");

                StringBuilder sbCommand = new StringBuilder();
                sbCommand.Append("curve(dnorm(x, mean=samp.mean, sd=samp.sd), lwd=2, xlim=samp.xlim, ylab='Probability', xlab='" + strValueField + "');");
                sbCommand.Append("abline(v=samp.mean, col='red');");
                sbCommand.Append("abline(v=confint, col='blue');");
                string strTitle = "Probability Denstiy Plot";

                pSnippet.drawPlottoForm(strTitle, sbCommand.ToString());
            }

            //int intFID = Convert.ToInt32(pFeature.get_Value(0)); //Get FID Value
            //return intFID;



            //int intFID = FindFeatureFID(pPoint);
            //int intColumnLength = arrSimuResults.GetUpperBound(1) + 1;
            //double[] arrHist = new double[intColumnLength];
            //for (int i = 0; i < intColumnLength; i++)
            //{
            //    arrHist[i] = arrSimuResults[intFID, i];
            //}
            //NumericVector vecBLL = pEngine.CreateNumericVector(arrHist);
            //pEngine.SetSymbol(strValue, vecBLL);

            //string strCommand = "hist(" + strValue + ", freq=FALSE, main=paste('Histogram of FID ', " + intFID.ToString() + "));abline(v=" + Math.Round(arrOrivalue[intFID], 3).ToString() + ", col='red');";
            //string strTitle = "Histogram";

            //System.Text.StringBuilder CommandPlot = new System.Text.StringBuilder();
        }
Esempio n. 3
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;
            }
        }
Esempio n. 4
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();
        }
Esempio n. 5
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");
            }