Example #1
0
        public void enableButtons(System.Collections.Generic.List <string> multipageImage, int intCurrentIdx, frmPlot pfrmPlot)
        {
            try
            {
                if (intCurrentIdx > 0)
                {
                    pfrmPlot.btnPreviousPlot.Enabled = true;
                }
                else
                {
                    pfrmPlot.btnPreviousPlot.Enabled = false;
                }

                if (intCurrentIdx >= multipageImage.Count - 1)
                {
                    pfrmPlot.btnNextPlot.Enabled = false;
                }
                else
                {
                    pfrmPlot.btnNextPlot.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #2
0
        private void UpdateListview(ListView pListView, DataTable dt)
        {
            try
            {
                pListView.BeginUpdate();
                string strResiFldNm = "glm_resi";

                //Update Name Using the UpdateFldName Function

                strResiFldNm = UpdateFldName(strResiFldNm, dt);

                if (strResiFldNm == null)
                {
                    return;
                }

                pListView.Items[0].SubItems[1].Text = strResiFldNm;
                pListView.EndUpdate();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #3
0
 private void btnSubset_Click(object sender, EventArgs e)
 {
     try
     {
         frmSubsetPoly pfrmSubsetPoly = new frmSubsetPoly();
         pfrmSubsetPoly.ShowDialog();
         m_blnSubset = pfrmSubsetPoly.m_blnSubset;
         if (m_blnSubset)
         {
             m_pClippedPolygon   = pfrmSubsetPoly.m_pMaplayer;;
             chkCumulate.Visible = true;
             chkCumulate.Text    = "Clipped by '" + m_pClippedPolygon.DataSet.Name + "'";
             chkCumulate.Checked = true;
             chkCumulate.Enabled = true;
         }
         else
         {
             chkCumulate.Visible = false;
         }
     }
     catch (Exception ex)
     {
         frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
         return;
     }
 }
Example #4
0
        private void btnApply_Click(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

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

                if (strNameR == null)
                {
                    return;
                }

                int intSuccess = 0;

                //Create spatial weight matrix in R
                if (m_pMapLayer is MapPolygonLayer)
                {
                    m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')");
                    intSuccess = m_pSnippet.CreateSpatialWeightMatrixPoly(m_pEngine, m_pMapLayer, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked);
                }
                else if (m_pMapLayer is MapPointLayer)
                {
                    m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')");
                    intSuccess = m_pSnippet.CreateSpatialWeightMatrixPts(m_pEngine, m_pMapLayer, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked);

                    //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();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #5
0
        private void frmAdvSWM_Load(object sender, EventArgs e)
        {
            try
            {
                //New Spatial Weight matrix function 083117 HK
                clsSnippet.SpatialWeightMatrixType pSWMType = new clsSnippet.SpatialWeightMatrixType();
                if (m_pMapLayer is MapPolygonLayer) //Apply Different Spatial weight matrix according to geometry type 05/24/18 HK
                {
                    //txtSWM.Text = pSWMType.strPolySWM;
                    txtSWM.DataSource = pSWMType.strPolyDefs;

                    lblClip.Visible     = false; btnSubset.Visible = false; btnSubset.Enabled = false;
                    chkCumulate.Visible = true; chkCumulate.Text = "Cumulate neighbors:";
                    lblAdvanced.Text    = "Contiguity Order:";
                    nudAdvanced.Value   = 1; nudAdvanced.Increment = 1; nudAdvanced.DecimalPlaces = 0;

                    if (blnCorrelogram)
                    {
                        chkCumulate.Visible = false; nudAdvanced.Visible = false;
                        lblAdvanced.Visible = false;
                    }
                }
                else if (m_pMapLayer is MapPointLayer)
                {
                    //txtSWM.Text = pSWMType.strPointSWM;
                    txtSWM.DataSource   = pSWMType.strPointDef;
                    lblClip.Visible     = true; btnSubset.Visible = true; btnSubset.Enabled = true;
                    chkCumulate.Visible = false;
                    lblAdvanced.Text    = "Threshold distance:";
                    nudAdvanced.Value   = 100; nudAdvanced.Increment = 10; nudAdvanced.DecimalPlaces = 2;
                }
                else if (m_pMapLayer is MapLineLayer)
                {
                    MessageBox.Show("Spatial weight matrix for polyline is not supported.");
                    btnSubset.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Please check the type of the shapefile.");
                    btnSubset.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #6
0
 private void cboTargetLayer_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         string strLayerName = cboTargetLayer.Text;
         m_pMaplayer = null;
         for (int i = 0; i < m_pForm.map1.Layers.Count; i++)
         {
             if (strLayerName == m_pForm.map1.Layers[i].DataSet.Name)
             {
                 m_pMaplayer = m_pForm.map1.Layers[i];
             }
         }
     }
     catch (Exception ex)
     {
         frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
         return;
     }
 }
Example #7
0
 public void drawCurrentChart(System.Collections.Generic.List <string> multipageImage, int currIndex, frmPlot mPlot)
 {
     try
     {
         if (multipageImage.Count > 0)
         {
             using (System.IO.StreamReader str = new System.IO.StreamReader(multipageImage[currIndex]))
             {
                 //mPlot.picPlot.Image = new System.Drawing.Bitmap(str.BaseStream);
                 mPlot.picPlot.Image = new System.Drawing.Imaging.Metafile(str.BaseStream);
                 str.Close();
             }
             mPlot.picPlot.Invalidate();
         }
     }
     catch (Exception ex)
     {
         frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
         return;
     }
 }
Example #8
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //Get Start up path to set a sample data path and path of temporary folder
                strPath = System.Windows.Forms.Application.StartupPath;
                //R environment setting
                //Current version of R is 3.4.4 (05/23/18 HK)
                var envPath  = Environment.GetEnvironmentVariable("PATH");
                var rBinPath = strPath + @"\R-3.4.4\bin\i386"; // R is copited into startup path
                Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
                Environment.SetEnvironmentVariable("R_HOME", strPath + @"\R-3.4.4");

                //Loading REngine
                pEngine = REngine.CreateInstance(strREngineName);
                pEngine.Initialize();

                //Set Library home and remove local home!
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                string strLibPath = strPath.Replace(@"\", @"/") + "/R-3.4.4/library"; //path for R packages
                pEngine.Evaluate(".Library.site <- file.path('" + strLibPath + "')");
                pEngine.Evaluate("Sys.setenv(R_LIBS_USER='******')");
                pEngine.Evaluate(".libPaths(c('" + strLibPath + "', .Library.site, .Library))");

                //Checked installed packages and R
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                pEngine.Evaluate("ip <- installed.packages()").AsCharacter();
                string[] installedPackages = pEngine.Evaluate("ip[,1]").AsCharacter().ToArray(); //To Check Installed Packages in R

                //The funtion below will be added to check installed packages in R (HK 05/23/18)
                //clsRPackageNames pPckNames = new clsRPackageNames();
                //blnsInstalledPcks = pPckNames.CheckedRequiredPackages(installedPackages);
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
        public frmSpatialRegression()
        {
            try
            {
                InitializeComponent();
                m_pForm = Application.OpenForms["MainForm"] as MainForm;

                for (int i = 0; i < m_pForm.map1.Layers.Count; i++)
                {
                    cboTargetLayer.Items.Add(m_pForm.map1.Layers[i].DataSet.Name);
                }

                m_pEngine = m_pForm.pEngine;
                m_pEngine.Evaluate("library(spdep); library(maptools); library(MASS)");

                m_pSnippet = new clsSnippet();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #10
0
        private void cboFamily_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboTargetLayer.Text != "" && cboFamily.Text != "")
                {
                    if (cboFamily.Text == "Linear (Gaussian)")
                    {
                        cboNormalization.Enabled = false;
                        cboNormalization.Text    = "";
                        lblNorm.Enabled          = false;
                    }
                    else
                    {
                        cboNormalization.Enabled = true;
                        lblNorm.Enabled          = true;
                        if (cboFamily.Text == "Binomial")
                        {
                            lblNorm.Text = "Normalization";
                        }
                        else
                        {
                            lblNorm.Text = "Offset";
                        }
                    }

                    string strLayerName = cboTargetLayer.Text;
                    m_pMaplayer = null;
                    for (int i = 0; i < m_pForm.map1.Layers.Count; i++)
                    {
                        if (strLayerName == m_pForm.map1.Layers[i].DataSet.Name)
                        {
                            m_pMaplayer = m_pForm.map1.Layers[i];
                        }
                    }


                    if (m_pMaplayer is MapPointLayer)
                    {
                        MapPointLayer pMapPointLyr = default(MapPointLayer);
                        pMapPointLyr = (MapPointLayer)m_pMaplayer;
                        m_dt         = pMapPointLyr.DataSet.DataTable;
                    }
                    else if (m_pMaplayer is MapPolygonLayer)
                    {
                        MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                        pMapPolyLyr = (MapPolygonLayer)m_pMaplayer;
                        m_dt        = pMapPolyLyr.DataSet.DataTable;
                    }

                    cboFieldName.Items.Clear();
                    cboFieldName.Text = "";
                    lstFields.Items.Clear();
                    lstIndeVar.Items.Clear();
                    cboNormalization.Text = "";

                    if (cboFamily.Text == "Poisson")
                    {
                        for (int i = 0; i < m_dt.Columns.Count; i++)
                        {
                            if (FindNumberFieldType(m_dt.Columns[i]))
                            {
                                lstFields.Items.Add(m_dt.Columns[i].ColumnName);
                                cboNormalization.Items.Add(m_dt.Columns[i].ColumnName);
                                if (m_dt.Columns[i].DataType == Type.GetType("System.Int32"))
                                {
                                    cboFieldName.Items.Add(m_dt.Columns[i].ColumnName);
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < m_dt.Columns.Count; i++)
                        {
                            if (FindNumberFieldType(m_dt.Columns[i]))
                            {
                                lstFields.Items.Add(m_dt.Columns[i].ColumnName);
                                cboNormalization.Items.Add(m_dt.Columns[i].ColumnName);
                                cboFieldName.Items.Add(m_dt.Columns[i].ColumnName);
                            }
                        }
                    }

                    if (chkSave.Checked)
                    {
                        UpdateListview(lstSave, m_dt);
                    }
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #11
0
        }//For only polygons

        public int CreateSpatialWeightMatrixPts(REngine pEngine, IMapLayer pMapLayer, string strSWMtype, frmProgress pfrmProgress, double dblAdvancedValue, bool blnCumul)//For only point dataset
        {
            try
            {
                //Return 0, means fails to create spatial weight matrix, 1 means success.

                SpatialWeightMatrixType pSWMType = new SpatialWeightMatrixType();

                if (pMapLayer is MapPointLayer)
                {
                    #region Delaunay
                    if (strSWMtype == pSWMType.strPointDef[0])
                    {
                        if (blnCumul == false)
                        {
                            pEngine.Evaluate("sample.nb <- tri2nb(coordinates(sample.shp))");
                            //For dealing empty neighbors

                            try
                            {
                                pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W'); sample.listb <- nb2listw(sample.nb, style='B')");
                            }
                            catch
                            {
                                DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                                if (dialogResult == DialogResult.Yes)
                                {
                                    pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                                }
                                else if (dialogResult == DialogResult.No)
                                {
                                    pfrmProgress.Close();
                                    return(0);
                                }
                            }
                        }
                        else
                        {
                            if (pMapLayer == null)
                            {
                                return(0);
                            }

                            MainForm pForm = System.Windows.Forms.Application.OpenForms["MainForm"] as MainForm;

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

                            try
                            {
                                pEngine.Evaluate("library(deldir); library(rgeos)");
                            }
                            catch
                            {
                                MessageBox.Show("Please checked R packages installed in your local computer.");
                                return(0);
                            }


                            string strPolypathR = FilePathinRfromLayer(pMapLayer);

                            pEngine.Evaluate("sample.sub.shp <- readShapePoly('" + strPolypathR + "')");

                            pEngine.Evaluate("sample.nb <- del.subset(sample.shp, sample.sub.shp)");
                            bool blnError = pEngine.Evaluate("nrow(sample.shp) == length(sample.nb)").AsLogical().First();

                            if (blnError == false)
                            {
                                MessageBox.Show("The number of features in points and the rows of neighbors is not matched.", "Error");
                                return(0);
                            }
                            else
                            {
                                try
                                {
                                    pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W'); sample.listb <- nb2listw(sample.nb, style='B')");
                                }
                                catch
                                {
                                    DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                                    if (dialogResult == DialogResult.Yes)
                                    {
                                        pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                                    }
                                    else if (dialogResult == DialogResult.No)
                                    {
                                        return(0);
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                    else if (strSWMtype == pSWMType.strPointDef[1])
                    {
                        pEngine.Evaluate("sample.nb <- dnearneigh(coordinates(sample.shp), 0, " + dblAdvancedValue.ToString() + ")");
                        //For dealing empty neighbors
                        if (pEngine.Evaluate("sum(card(sample.nb)) < 1").AsLogical().First())
                        {
                            MessageBox.Show("There are too many empty neighbors");
                            pfrmProgress.Close();
                            return(0);
                        }

                        try
                        {
                            pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W'); sample.listb <- nb2listw(sample.nb, style='B')");
                        }
                        catch
                        {
                            DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                            if (dialogResult == DialogResult.Yes)
                            {
                                pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return(0);
                            }
                        }
                        finally
                        {
                            pfrmProgress.Close();
                            MessageBox.Show("Fail to create spatial weights matrix");
                        }
                    }
                    else if (strSWMtype == pSWMType.strPointDef[2])
                    {
                        pEngine.Evaluate("col.knn <- knearneigh(coordinates(sample.shp), k=" + dblAdvancedValue.ToString() + ")");
                        pEngine.Evaluate("sample.nb <- knn2nb(col.knn)");
                        //For dealing empty neighbors

                        bool blnSymmetric = pEngine.Evaluate("is.symmetric.nb(sample.nb)").AsLogical().First();
                        if (blnSymmetric == false)
                        {
                            DialogResult dialogResult = MessageBox.Show("This spatial weight matrix is asymmetric. Some functions are restricted in an asymmetric matrix. Do you want to continue?", "Asymmetric spatial weight matrix", MessageBoxButtons.YesNo);
                            if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return(0);
                            }
                        }

                        try
                        {
                            pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W'); sample.listb <- nb2listw(sample.nb, style='B')");
                        }
                        catch
                        {
                            DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                            if (dialogResult == DialogResult.Yes)
                            {
                                pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return(0);
                            }
                        }
                    }
                }
                else
                {
                    int intResult = SWMusingGAL(pEngine, pMapLayer, strSWMtype);
                    if (intResult == -1)
                    {
                        pfrmProgress.Close();
                        return(0);
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return(0);
            }
        }
Example #12
0
        public void drawPlottoForm(string strTitle, string strCommand)
        {
            try
            {
                MainForm mForm   = Application.OpenForms["MainForm"] as MainForm;
                REngine  pEngine = mForm.pEngine;
                //Create Plots in R
                StringBuilder CommandPlot = new StringBuilder();

                //Plots are saved in temporary folders.
                string path = Path.GetTempPath();
                //Have to assing pathes differently at R and ArcObject
                string pathr = path.Replace(@"\", @"/");
                //Remove existing image file pathes
                if (mForm.multipageImage == null)
                {
                    mForm.multipageImage = new List <string>();
                }
                else
                {
                    mForm.multipageImage.Clear();
                }

                //Delete existing image files
                mForm.multipageImage.AddRange(Directory.GetFiles(path, "rnet*.wmf"));

                for (int j = 0; j < mForm.multipageImage.Count; j++)
                {
                    FileInfo pinfo = new FileInfo(mForm.multipageImage[j]);
                    if (pinfo.Exists)
                    {
                        pinfo.Delete();
                    }
                    pinfo.Refresh();
                }

                //Load Form and assign the settings
                frmPlot pfrmPlot = new frmPlot();
                pfrmPlot.Text = strTitle;
                pfrmPlot.Show();
                string strwidth  = pfrmPlot.picPlot.Size.Width.ToString();
                string strHeight = pfrmPlot.picPlot.Size.Height.ToString();

                //Create Plots in R
                CommandPlot.Append("win.metafile('" + pathr + "rnet%01d.wmf');");
                CommandPlot.Append(strCommand);
                CommandPlot.Append("graphics.off()");
                pEngine.Evaluate(CommandPlot.ToString());

                //Add Plot pathes at List
                mForm.multipageImage.Clear();
                mForm.multipageImage.AddRange(Directory.GetFiles(path, "rnet*.wmf"));

                //Draw plots at the Form
                mForm.intCurrentIdx = 0;
                drawCurrentChart(mForm.multipageImage, mForm.intCurrentIdx, pfrmPlot);
                enableButtons(mForm.multipageImage, mForm.intCurrentIdx, pfrmPlot);
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #13
0
        //Creating Spatial Weight Matrix
        public int CreateSpatialWeightMatrix(REngine pEngine, IMapLayer pMapLayer, string strSWMtype, frmProgress pfrmProgress)
        {
            try
            {
                //Return 0, means fails to create spatial weight matrix, 1 means success.

                SpatialWeightMatrixType pSWMType = new SpatialWeightMatrixType();

                if (pMapLayer is MapPolygonLayer)
                {
                    if (strSWMtype == pSWMType.strPolyDefs[0])
                    {
                        pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=T)");
                    }
                    else if (strSWMtype == pSWMType.strPolyDefs[1])
                    {
                        pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=F)");
                    }
                    else
                    {
                        pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=T)");
                    }
                    //For dealing empty neighbors
                    try
                    {
                        pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W');sample.listb <- nb2listw(sample.nb, style='B')");
                    }
                    catch
                    {
                        DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                        if (dialogResult == DialogResult.Yes)
                        {
                            pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                        }
                        else if (dialogResult == DialogResult.No)
                        {
                            pfrmProgress.Close();
                            return(0);
                        }
                    }
                }
                else if (pMapLayer is MapPointLayer)
                {
                    FormCollection pFormCollection = System.Windows.Forms.Application.OpenForms;
                    bool           blnOpen         = false;
                    int            intIdx          = 0;

                    for (int j = 0; j < pFormCollection.Count; j++)
                    {
                        if (pFormCollection[j].Name == "frmSubsetPoly")//Brushing to Histogram
                        {
                            intIdx = j;

                            blnOpen = true;
                        }
                    }

                    if (blnOpen) //Delaunay with clipping
                    {
                        frmSubsetPoly pfrmSubsetPoly1 = pFormCollection[intIdx] as frmSubsetPoly;
                        if (pfrmSubsetPoly1.m_blnSubset)
                        {
                            string strPolypathR = FilePathinRfromLayer(pfrmSubsetPoly1.m_pMaplayer);

                            pEngine.Evaluate("sample.sub.shp <- readShapePoly('" + strPolypathR + "')");

                            pEngine.Evaluate("sample.nb <- del.subset(sample.shp, sample.sub.shp)");
                            bool blnError = pEngine.Evaluate("nrow(sample.shp) == length(sample.nb)").AsLogical().First();

                            if (blnError == false)
                            {
                                MessageBox.Show("The number of features in points and the rows of neighbors is not matched.", "Error");
                                return(0);
                            }
                            else
                            {
                                try
                                {
                                    pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W'); sample.listb <- nb2listw(sample.nb, style='B')");
                                }
                                catch
                                {
                                    DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                                    if (dialogResult == DialogResult.Yes)
                                    {
                                        pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                                    }
                                    else if (dialogResult == DialogResult.No)
                                    {
                                        pfrmProgress.Close();
                                        return(0);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        pEngine.Evaluate("sample.nb <- tri2nb(coordinates(sample.shp))");
                        //For dealing empty neighbors

                        try
                        {
                            pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W'); sample.listb <- nb2listw(sample.nb, style='B')");
                        }
                        catch
                        {
                            DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                            if (dialogResult == DialogResult.Yes)
                            {
                                pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                pfrmProgress.Close();
                                return(0);
                            }
                        }
                    }
                }
                else
                {
                    int intResult = SWMusingGAL(pEngine, pMapLayer, strSWMtype);
                    if (intResult == -1)
                    {
                        pfrmProgress.Close();
                        return(0);
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return(0);
            }
        }
Example #14
0
        public int CreateSpatialWeightMatrixPoly(REngine pEngine, IMapLayer pMapLayer, string strSWMtype, frmProgress pfrmProgress, double dblAdvancedValue, bool blnCumul)
        {
            try
            {
                //Return 0, means fails to create spatial weight matrix, 1 means success.

                SpatialWeightMatrixType pSWMType = new SpatialWeightMatrixType();

                if (pMapLayer is MapPolygonLayer)
                {
                    if (strSWMtype == pSWMType.strPolyDefs[0])
                    {
                        pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=T)");
                    }
                    else if (strSWMtype == pSWMType.strPolyDefs[1])
                    {
                        pEngine.Evaluate("sample.nb <- poly2nb(sample.shp, queen=F)");
                    }

                    if (dblAdvancedValue > 1)
                    {
                        try
                        {
                            pEngine.Evaluate("sample.nblags <- nblag(sample.nb, maxlag = " + dblAdvancedValue.ToString() + ")");
                        }
                        catch
                        {
                            MessageBox.Show("Please reduce the maximum lag order");
                        }

                        if (blnCumul)
                        {
                            pEngine.Evaluate("sample.nb <- nblag_cumul(sample.nblags)");
                        }
                        else
                        {
                            pEngine.Evaluate("sample.nb <- sample.nblags[[" + dblAdvancedValue.ToString() + "]]");
                        }
                    }

                    //For dealing empty neighbors
                    try
                    {
                        pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W');sample.listb <- nb2listw(sample.nb, style='B')");
                    }
                    catch
                    {
                        DialogResult dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo);


                        if (dialogResult == DialogResult.Yes)
                        {
                            pEngine.Evaluate("sample.listw <- nb2listw(sample.nb, style='W', zero.policy=TRUE);sample.listb <- nb2listw(sample.nb, style='B', zero.policy=TRUE)");
                        }
                        else if (dialogResult == DialogResult.No)
                        {
                            pfrmProgress.Close();
                            return(0);
                        }
                    }
                }
                else
                {
                    int intResult = SWMusingGAL(pEngine, pMapLayer, strSWMtype);
                    if (intResult == -1)
                    {
                        pfrmProgress.Close();
                        return(0);
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return(0);
            }
        }//For only polygons
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                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");
                    return;
                }
                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");
                    return;
                }
                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");
                    return;
                }
                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");
                    return;
                }

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


                //Decimal places
                int intDeciPlaces = 5;

                //Get number of Independent variables
                int nIDepen = lstIndeVar.Items.Count;
                // 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];
                for (int j = 0; j < nIDepen; j++)
                {
                    independentNames[j] = (string)lstIndeVar.Items[j];
                }

                int nFeature = m_dt.Rows.Count;

                //Get index for independent and dependent variables
                int intDepenIdx = m_dt.Columns.IndexOf(dependentName);

                int[] idxes = new int[nIDepen];

                for (int j = 0; j < nIDepen; j++)
                {
                    idxes[j] = m_dt.Columns.IndexOf(independentNames[j]);
                }

                //Store independent values at Array
                double[]   arrDepen   = new double[nFeature];
                double[][] arrInDepen = new double[nIDepen][];

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

                int i = 0;
                foreach (DataRow row in m_dt.Rows)
                {
                    arrDepen[i] = Convert.ToDouble(row[intDepenIdx]);

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

                //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_pMaplayer);

                    if (strNameR == null)
                    {
                        return;
                    }

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


                    int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pMaplayer, 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 + "~");
                }


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

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

                //int intNObser = pEngine.Evaluate("as.numeric(nrow(sum.lm$X))").AsInteger().First();
                //int intNParmeter = pEngine.Evaluate(" as.numeric(sum.lm$parameters)").AsInteger().First();

                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 = m_pEngine.Evaluate("as.numeric(sum.lm$NK)").AsNumeric().First();
                //Draw result form

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

                //Store Data Table by R result
                for (int j = 0; j < nIDepen + 1; j++)
                {
                    DataRow pDataRow = tblRegResult.NewRow();
                    if (j == 0)
                    {
                        pDataRow["Name"] = "(Intercept)";
                    }
                    else
                    {
                        if (rbtDurbin.Checked)
                        {
                            if (j <= nIDepen / 2)
                            {
                                pDataRow["Name"] = independentNames[j - 1];
                            }
                            else
                            {
                                pDataRow["Name"] = "lag." + independentNames[j - (nIDepen / 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)
                {
                    strResults[0] = "rho: " + 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) + ", LM test for residuals autocorrelation: " + dblResiAuto.ToString(strDecimalPlaces);
                }
                else if (rbtError.Checked)
                {
                    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
                {
                    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);
                }
                strResults[4] = "Nagelkerke pseudo-R-squared: " + dblRsquared.ToString(strDecimalPlaces);

                pfrmRegResult.txtOutput.Lines = strResults;

                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_dt.Columns.IndexOf(strResiFldName) == -1)
                    {
                        //Add fields
                        DataColumn pColumn = new DataColumn(strResiFldName);
                        pColumn.DataType = Type.GetType("System.Double");
                        m_dt.Columns.Add(pColumn);
                    }
                    else
                    {
                        DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " field?", "Overwrite", MessageBoxButtons.YesNo);

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

                    //Update Field
                    int featureIdx    = 0;
                    int intResiFldIdx = m_dt.Columns.IndexOf(strResiFldName);

                    foreach (DataRow row in m_dt.Rows)
                    {
                        //Update Residuals
                        row[intResiFldIdx] = nvResiduals[featureIdx];
                        featureIdx++;
                    }

                    //Save Result;
                    if (m_pMaplayer is MapPointLayer)
                    {
                        MapPointLayer pMapPointLyr = default(MapPointLayer);
                        pMapPointLyr = (MapPointLayer)m_pMaplayer;
                        pMapPointLyr.DataSet.Save();
                    }
                    else if (m_pMaplayer is MapPolygonLayer)
                    {
                        MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                        pMapPolyLyr = (MapPolygonLayer)m_pMaplayer;
                        pMapPolyLyr.DataSet.Save();
                    }
                    else if (m_pMaplayer is MapLineLayer)
                    {
                        MapLineLayer pMapLineLyr = default(MapLineLayer);
                        pMapLineLyr = (MapLineLayer)m_pMaplayer;
                        pMapLineLyr.DataSet.Save();
                    }
                }

                pfrmProgress.Close();
                pfrmRegResult.Show();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #16
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                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");
                    return;
                }
                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");
                    return;
                }
                if (cboFamily.Text == "Binomial" && cboNormalization.Text == "")
                {
                    MessageBox.Show("Please select a variable for normailization");
                    return;
                }
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Pre-Processing:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                //Decimal places
                int intDeciPlaces = 5;

                //Get number of Independent variables
                int nIDepen = lstIndeVar.Items.Count;
                // Gets the column of the dependent variable
                String dependentName = (string)cboFieldName.SelectedItem;
                string strNoramlName = cboNormalization.Text;
                //sourceTable.AcceptChanges();
                //DataTable dependent = sourceTable.DefaultView.ToTable(false, dependentName);

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

                int nFeature = m_dt.Rows.Count;

                //Get index for independent and dependent variables
                int intDepenIdx = m_dt.Columns.IndexOf(dependentName);
                int intNoramIdx = -1;
                if (strNoramlName != "")
                {
                    intNoramIdx = m_dt.Columns.IndexOf(strNoramlName);
                }

                int[] idxes = new int[nIDepen];

                for (int j = 0; j < nIDepen; j++)
                {
                    idxes[j] = m_dt.Columns.IndexOf(independentNames[j]);
                }

                //Store independent values at Array
                double[]   arrDepen   = new double[nFeature];
                double[][] arrInDepen = new double[nIDepen][];
                double[]   arrNormal  = new double[nFeature];

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

                int i = 0;
                foreach (DataRow row in m_dt.Rows)
                {
                    arrDepen[i] = Convert.ToDouble(row[intDepenIdx]);

                    if (intNoramIdx != -1)
                    {
                        arrNormal[i] = Convert.ToDouble(row[intNoramIdx]);
                    }

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

                //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_pMaplayer);

                    if (strNameR == null)
                    {
                        return;
                    }

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


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

                //Dependent variable to R vector
                NumericVector vecDepen = m_pEngine.CreateNumericVector(arrDepen);
                m_pEngine.SetSymbol(dependentName, vecDepen);
                //plotCommmand.Append("lm.full <- " + dependentName + "~");
                NumericVector vecNormal = null;
                if (cboFamily.Text == "Binomial")
                {
                    vecNormal = m_pEngine.CreateNumericVector(arrNormal);
                    m_pEngine.SetSymbol(strNoramlName, vecNormal);
                    plotCommmand.Append("cbind(" + dependentName + ", " + strNoramlName + "-" + dependentName + ")~");
                }
                else if (cboFamily.Text == "Poisson" && intNoramIdx != -1)
                {
                    vecNormal = m_pEngine.CreateNumericVector(arrNormal);
                    m_pEngine.SetSymbol(strNoramlName, vecNormal);
                    plotCommmand.Append(dependentName + "~");
                }
                else
                {
                    plotCommmand.Append(dependentName + "~");
                }

                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 (cboFamily.Text == "Poisson")
                {
                    PoissonRegression(pfrmProgress, m_pMaplayer, plotCommmand.ToString(), nIDepen, independentNames, strNoramlName, intDeciPlaces);
                }
                else if (cboFamily.Text == "Binomial")
                {
                    BinomRegression(pfrmProgress, m_pMaplayer, plotCommmand.ToString(), nIDepen, independentNames, intDeciPlaces);
                }

                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #17
0
        private void ViewAttributeTable_Click(object sender, EventArgs e)
        {
            try
            {
                IMapLayer pMapLayer = this.map1.Layers.SelectedLayer;
                if (pMapLayer != null)
                {
                    frmAttributeTable pfrmAttTable = new frmAttributeTable();
                    DataTable         dt           = null;
                    if (pMapLayer is MapPointLayer)
                    {
                        MapPointLayer pMapPointLyr = default(MapPointLayer);
                        pMapPointLyr = (MapPointLayer)pMapLayer;
                        dt           = pMapPointLyr.DataSet.DataTable;
                    }
                    else if (pMapLayer is MapPolygonLayer)
                    {
                        MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                        pMapPolyLyr = (MapPolygonLayer)pMapLayer;
                        dt          = pMapPolyLyr.DataSet.DataTable;
                    }
                    else if (pMapLayer is MapLineLayer)
                    {
                        MapLineLayer pMapLineLyr = default(MapLineLayer);
                        pMapLineLyr = (MapLineLayer)pMapLayer;
                        dt          = pMapLineLyr.DataSet.DataTable;
                    }
                    pfrmAttTable.dgvAttTable.DataSource = dt;

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        if (i != 1)
                        {
                            if (dt.Columns[i].DataType == System.Type.GetType("System.Int16"))
                            {
                                pfrmAttTable.dgvAttTable.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            }
                            if (dt.Columns[i].DataType == System.Type.GetType("System.Int32"))
                            {
                                pfrmAttTable.dgvAttTable.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            }
                            if (dt.Columns[i].DataType == System.Type.GetType("System.Single"))
                            {
                                pfrmAttTable.dgvAttTable.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            }
                            if (dt.Columns[i].DataType == System.Type.GetType("System.Double"))
                            {
                                pfrmAttTable.dgvAttTable.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                            }
                        }
                    }


                    pfrmAttTable.Text = "Attribute of " + pMapLayer.DataSet.Name;
                    pfrmAttTable.dgvAttTable.AllowUserToAddRows = false;

                    pfrmAttTable.Show();
                }
                else
                {
                    MessageBox.Show("Please select a feature layer");
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #18
0
        private void BinomRegression(frmProgress pfrmProgress, IMapLayer pMapLayer, string strLM, int nIDepen, String[] independentNames, int intDeciPlaces)
        {
            try
            {
                pfrmProgress.lblStatus.Text = "Calculate Regression Coefficients";
                m_pEngine.Evaluate("sample.glm <- glm(" + strLM + ", family='binomial')");

                pfrmProgress.lblStatus.Text = "Printing Output:";
                m_pEngine.Evaluate("sum.glm <- summary(sample.glm)");
                m_pEngine.Evaluate("sample.n <- length(sample.nb)");

                NumericMatrix   matCoe      = m_pEngine.Evaluate("as.matrix(sum.glm$coefficient)").AsNumericMatrix();
                CharacterVector vecNames    = m_pEngine.Evaluate("attributes(sum.glm$coefficients)$dimnames[[1]]").AsCharacter();
                double          dblNullDevi = m_pEngine.Evaluate("sum.glm$null.deviance").AsNumeric().First();
                double          dblNullDF   = m_pEngine.Evaluate("sum.glm$df.null").AsNumeric().First();
                double          dblResiDevi = m_pEngine.Evaluate("sum.glm$deviance").AsNumeric().First();
                double          dblResiDF   = m_pEngine.Evaluate("sum.glm$df.residual").AsNumeric().First();

                //Nagelkerke r squared
                double dblPseudoRsquared = m_pEngine.Evaluate("(1 - exp((sample.glm$dev - sample.glm$null)/sample.n))/(1 - exp(-sample.glm$null/sample.n))").AsNumeric().First();

                double dblResiLMMC   = 0;
                double dblResiLMpVal = 0;
                if (chkResiAuto.Checked)
                {
                    m_pEngine.Evaluate("orgresi.mc <-moran.mc(residuals(sample.glm, type='" + cboResiType.Text + "'), listw =sample.listb, nsim=999, zero.policy=TRUE)");
                    dblResiLMMC   = m_pEngine.Evaluate("orgresi.mc$statistic").AsNumeric().First();
                    dblResiLMpVal = m_pEngine.Evaluate("orgresi.mc$p.value").AsNumeric().First();
                }

                NumericVector nvecNonAIC = m_pEngine.Evaluate("sample.glm$aic").AsNumeric();

                //Open Ouput form
                frmRegResult pfrmRegResult = new frmRegResult();
                pfrmRegResult.Text = "Binomial Regression Summary";

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

                //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 = "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);

                int intNCoeff = nIDepen + 1;

                //Store Data Table by R result
                for (int j = 0; j < intNCoeff; j++)
                {
                    DataRow pDataRow = tblRegResult.NewRow();
                    if (j == 0)
                    {
                        pDataRow["Name"] = "(Intercept)";
                    }
                    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;

                //Get Data Table
                DataTable pDT = null;
                if (pMapLayer is MapPointLayer)
                {
                    MapPointLayer pMapPointLyr = default(MapPointLayer);
                    pMapPointLyr = (MapPointLayer)pMapLayer;
                    pDT          = pMapPointLyr.DataSet.DataTable;
                }
                else if (pMapLayer is MapPolygonLayer)
                {
                    MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                    pMapPolyLyr = (MapPolygonLayer)pMapLayer;
                    pDT         = pMapPolyLyr.DataSet.DataTable;
                }

                int nFeature = pDT.Rows.Count;

                //Assign values at Textbox
                string   strDecimalPlaces = "N" + intDeciPlaces.ToString();
                string[] strResults       = new string[6];
                strResults[0] = "Number of rows: " + nFeature.ToString();
                strResults[1] = "AIC: " + nvecNonAIC.Last().ToString(strDecimalPlaces);
                strResults[2] = "Null deviance: " + dblNullDevi.ToString(strDecimalPlaces) + " on " + dblNullDF.ToString("N0") + " degrees of freedom";
                strResults[3] = "Residual deviance: " + dblResiDevi.ToString(strDecimalPlaces) + " on " + dblResiDF.ToString("N0") + " degrees of freedom";
                strResults[4] = "Nagelkerke pseudo R squared: " + dblPseudoRsquared.ToString(strDecimalPlaces);
                if (chkResiAuto.Checked)
                {
                    strResults[5] = "MC of residuals: " + dblResiLMMC.ToString("N3") + ", p-value: " + dblResiLMpVal.ToString("N3");
                }
                else
                {
                    strResults[5] = "";
                }

                pfrmRegResult.txtOutput.Lines = strResults;

                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(residuals(sample.glm, type='" + cboResiType.Text + "'))").AsNumeric();


                    // Create field, if there isn't
                    // Create field, if there isn't
                    if (m_dt.Columns.IndexOf(strResiFldName) == -1)
                    {
                        //Add fields
                        DataColumn pColumn = new DataColumn(strResiFldName);
                        pColumn.DataType = Type.GetType("System.Double");
                        m_dt.Columns.Add(pColumn);
                    }
                    else
                    {
                        DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " field?", "Overwrite", MessageBoxButtons.YesNo);

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

                    //Update Field
                    int featureIdx    = 0;
                    int intResiFldIdx = m_dt.Columns.IndexOf(strResiFldName);

                    foreach (DataRow row in m_dt.Rows)
                    {
                        //Update Residuals
                        row[intResiFldIdx] = nvResiduals[featureIdx];
                        featureIdx++;
                    }

                    //Save Result;
                    if (m_pMaplayer is MapPointLayer)
                    {
                        MapPointLayer pMapPointLyr = default(MapPointLayer);
                        pMapPointLyr = (MapPointLayer)m_pMaplayer;
                        pMapPointLyr.DataSet.Save();
                    }
                    else if (m_pMaplayer is MapPolygonLayer)
                    {
                        MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                        pMapPolyLyr = (MapPolygonLayer)m_pMaplayer;
                        pMapPolyLyr.DataSet.Save();
                    }
                    else if (m_pMaplayer is MapLineLayer)
                    {
                        MapLineLayer pMapLineLyr = default(MapLineLayer);
                        pMapLineLyr = (MapLineLayer)m_pMaplayer;
                        pMapLineLyr.DataSet.Save();
                    }
                }

                pfrmRegResult.Show();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #19
0
        private void cboTargetLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboTargetLayer.Text != "" && cboFamily.Text != "")
                {
                    string strLayerName = cboTargetLayer.Text;
                    m_pMaplayer = null;
                    for (int i = 0; i < m_pForm.map1.Layers.Count; i++)
                    {
                        if (strLayerName == m_pForm.map1.Layers[i].DataSet.Name)
                        {
                            m_pMaplayer = m_pForm.map1.Layers[i];
                        }
                    }


                    groupBox1.Enabled = true;

                    clsSnippet.SpatialWeightMatrixType pSWMType = new clsSnippet.SpatialWeightMatrixType();
                    if (m_pMaplayer is MapPointLayer)
                    {
                        MapPointLayer pMapPointLyr = default(MapPointLayer);
                        pMapPointLyr = (MapPointLayer)m_pMaplayer;
                        m_dt         = pMapPointLyr.DataSet.DataTable;
                        txtSWM.Text  = pSWMType.strPointSWM;
                    }
                    else if (m_pMaplayer is MapPolygonLayer)
                    {
                        MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                        pMapPolyLyr = (MapPolygonLayer)m_pMaplayer;
                        m_dt        = pMapPolyLyr.DataSet.DataTable;
                        txtSWM.Text = pSWMType.strPolySWM;
                    }
                    else if (m_pMaplayer is MapLineLayer)
                    {
                        MessageBox.Show("Spatial weight matrix for polyline is not supported.");
                        groupBox1.Enabled   = false;
                        chkResiAuto.Checked = false;
                    }


                    cboFieldName.Text = "";
                    lstFields.Items.Clear();
                    lstIndeVar.Items.Clear();
                    cboNormalization.Text = "";

                    if (cboFamily.Text == "Poisson")
                    {
                        for (int i = 0; i < m_dt.Columns.Count; i++)
                        {
                            if (FindNumberFieldType(m_dt.Columns[i]))
                            {
                                lstFields.Items.Add(m_dt.Columns[i].ColumnName);
                                cboNormalization.Items.Add(m_dt.Columns[i].ColumnName);
                                if (m_dt.Columns[i].DataType == Type.GetType("System.Int32"))
                                {
                                    cboFieldName.Items.Add(m_dt.Columns[i].ColumnName);
                                }
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < m_dt.Columns.Count; i++)
                        {
                            if (FindNumberFieldType(m_dt.Columns[i]))
                            {
                                lstFields.Items.Add(m_dt.Columns[i].ColumnName);
                                cboNormalization.Items.Add(m_dt.Columns[i].ColumnName);
                                cboFieldName.Items.Add(m_dt.Columns[i].ColumnName);
                            }
                        }
                    }

                    if (chkSave.Checked)
                    {
                        UpdateListview(lstSave, m_dt);
                    }
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #20
0
        private void txtSWM_TextChanged(object sender, EventArgs e)
        {
            try
            {
                clsSnippet.SpatialWeightMatrixType pSWMType = new clsSnippet.SpatialWeightMatrixType();

                if (txtSWM.Text == pSWMType.strPointDef[0])
                {
                    lblClip.Visible     = true; lblClip.Enabled = true;
                    btnSubset.Visible   = true; btnSubset.Enabled = true;
                    chkCumulate.Visible = false;
                    lblAdvanced.Text    = "Threshold distance:";
                    lblAdvanced.Enabled = false;
                    nudAdvanced.Value   = 100; nudAdvanced.Increment = 10; nudAdvanced.DecimalPlaces = 2;
                    nudAdvanced.Enabled = false;
                }
                else if (txtSWM.Text == pSWMType.strPointDef[1])
                {
                    lblClip.Visible     = true; btnSubset.Visible = true; btnSubset.Enabled = true;
                    chkCumulate.Visible = false;
                    lblAdvanced.Text    = "Threshold distance:";
                    lblAdvanced.Enabled = true;
                    nudAdvanced.Value   = 100; nudAdvanced.Increment = 10; nudAdvanced.DecimalPlaces = 2;
                    nudAdvanced.Enabled = true;
                    btnSubset.Enabled   = false; btnSubset.Visible = false;
                    lblClip.Enabled     = false; lblClip.Visible = false;
                    //if (m_dblDefaultDistThres != null)
                    //    nudAdvanced.Value = Convert.ToDecimal(m_dblDefaultDistThres);
                }
                else if (txtSWM.Text == pSWMType.strPointDef[2])
                {
                    lblClip.Visible     = true; btnSubset.Visible = true; btnSubset.Enabled = true;
                    chkCumulate.Visible = false;
                    lblAdvanced.Text    = "Number of neighbors:";
                    lblAdvanced.Enabled = true;
                    nudAdvanced.Value   = 4; nudAdvanced.Increment = 1; nudAdvanced.DecimalPlaces = 0;
                    nudAdvanced.Enabled = true;
                    btnSubset.Enabled   = false; btnSubset.Visible = false;
                    lblClip.Enabled     = false; lblClip.Visible = false;
                }
                else
                {
                    lblClip.Visible     = false; btnSubset.Visible = false; btnSubset.Enabled = false;
                    chkCumulate.Enabled = false; chkCumulate.Visible = true;
                    lblAdvanced.Enabled = true; lblAdvanced.Text = "Contiguity Order:";
                    nudAdvanced.Enabled = true; nudAdvanced.Value = 1; nudAdvanced.Increment = 1; nudAdvanced.DecimalPlaces = 0;

                    int intT = pSWMType.strPolyDefs.Length;
                    for (int i = 0; i < intT; i++)
                    {
                        if (txtSWM.Text == pSWMType.strPolyDefs[i])
                        {
                            return;
                        }
                    }
                    btnSubset.Enabled   = false;
                    chkCumulate.Enabled = false;
                    lblAdvanced.Enabled = false;
                    nudAdvanced.Enabled = false;
                    lblClip.Enabled     = false;
                }
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Example #21
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                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");
                    return;
                }
                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");
                    return;
                }

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


                //Decimal places
                int intDeciPlaces = 5;

                //Get number of Independent variables
                int nIDepen = lstIndeVar.Items.Count;
                // 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];
                for (int j = 0; j < nIDepen; j++)
                {
                    independentNames[j] = (string)lstIndeVar.Items[j];
                }

                int nFeature = m_dt.Rows.Count;

                //Get index for independent and dependent variables
                int intDepenIdx = m_dt.Columns.IndexOf(dependentName);

                int[] idxes = new int[nIDepen];

                for (int j = 0; j < nIDepen; j++)
                {
                    idxes[j] = m_dt.Columns.IndexOf(independentNames[j]);
                }

                //Store independent values at Array
                double[]   arrDepen   = new double[nFeature];
                double[][] arrInDepen = new double[nIDepen][];

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

                int i = 0;
                foreach (DataRow row in m_dt.Rows)
                {
                    arrDepen[i] = Convert.ToDouble(row[intDepenIdx]);

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

                //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 + "~");

                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);
                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_pMaplayer);

                        if (strNameR == null)
                        {
                            return;
                        }

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


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


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

                    //Calculate MC
                    m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, 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
                for (int j = 0; j < nIDepen + 1; j++)
                {
                    DataRow pDataRow = tblRegResult.NewRow();
                    if (j == 0)
                    {
                        pDataRow["Name"] = "(Intercept)";
                    }
                    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];
                    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());
                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());
                pfrmRegResult.txtOutput.Lines = strResults;
                pfrmRegResult.Show();

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

                    m_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
                    // Create field, if there isn't
                    if (m_dt.Columns.IndexOf(strResiFldName) == -1)
                    {
                        //Add fields
                        DataColumn pColumn = new DataColumn(strResiFldName);
                        pColumn.DataType = Type.GetType("System.Double");
                        m_dt.Columns.Add(pColumn);
                    }
                    else
                    {
                        DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " field?", "Overwrite", MessageBoxButtons.YesNo);

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

                    //Update Field
                    int featureIdx    = 0;
                    int intResiFldIdx = m_dt.Columns.IndexOf(strResiFldName);

                    foreach (DataRow row in m_dt.Rows)
                    {
                        //Update Residuals
                        row[intResiFldIdx] = nvResiduals[featureIdx];
                        featureIdx++;
                    }

                    //Save Result;
                    if (m_pMaplayer is MapPointLayer)
                    {
                        MapPointLayer pMapPointLyr = default(MapPointLayer);
                        pMapPointLyr = (MapPointLayer)m_pMaplayer;
                        pMapPointLyr.DataSet.Save();
                    }
                    else if (m_pMaplayer is MapPolygonLayer)
                    {
                        MapPolygonLayer pMapPolyLyr = default(MapPolygonLayer);
                        pMapPolyLyr = (MapPolygonLayer)m_pMaplayer;
                        pMapPolyLyr.DataSet.Save();
                    }
                    else if (m_pMaplayer is MapLineLayer)
                    {
                        MapLineLayer pMapLineLyr = default(MapLineLayer);
                        pMapLineLyr = (MapLineLayer)m_pMaplayer;
                        pMapLineLyr.DataSet.Save();
                    }

                    MessageBox.Show("Residuals are stored in the shape file");
                }

                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }