示例#1
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;
            }
        }
示例#2
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;
            }
        }