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