private void btnRun_Click(object sender, EventArgs e) { try { if (cboFieldName.Text == "") { MessageBox.Show("Please select target field"); return; } frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); //Decimal places int intDeciPlaces = 5; // Creates the input and output matrices from the shapefile// //string strLayerName = cboTargetLayer.Text; //int intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName); //ILayer pLayer = m_pForm.axMapControl1.get_Layer(intLIndex); //pFLayer = pLayer as IFeatureLayer; //pFClass = pFLayer.FeatureClass; int nFeature = m_pFClass.FeatureCount(null); IFeatureCursor pFCursor = m_pFLayer.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables //Get variable index string strVarNM = cboFieldName.Text; int intVarIdx = m_pFClass.FindField(strVarNM); //Store Variable at Array double[] arrVar = new double[nFeature]; int i = 0; while (pFeature != null) { arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx)); i++; pFeature = pFCursor.NextFeature(); } //Plot command for R StringBuilder plotCommmand = new StringBuilder(); if (!m_blnCreateSWM) { //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); if (strNameR == null) { return; } //Create spatial weight matrix in R if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); } else { MessageBox.Show("This geometry type is not supported"); pfrmProgress.Close(); this.Close(); } int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress); if (intSuccess == 0) { return; } } //pEngine.Evaluate("sample.nb <- poly2nb(sample.shp);sample.listw <- nb2listw(sample.nb, style='W')"); NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar); m_pEngine.SetSymbol(strVarNM, vecVar); plotCommmand.Append("sam.result <- "); //Select method if (cboSAM.Text == "Moran Coefficient") { plotCommmand.Append("moran.test"); } else if (cboSAM.Text == "Geary Ratio") { plotCommmand.Append("geary.test"); } plotCommmand.Append("(" + strVarNM + ", sample.listw, "); //select assumption if (cboAssumption.Text == "Normality") { plotCommmand.Append("randomisation=FALSE, , zero.policy=TRUE)"); } else if (cboAssumption.Text == "Randomization") { plotCommmand.Append("randomisation=TRUE, , zero.policy=TRUE)"); } m_pEngine.Evaluate(plotCommmand.ToString()); //Print Output string strDecimalPlaces = "N" + intDeciPlaces.ToString(); string[] strResults = new string[7]; strResults[0] = cboSAM.Text + " under " + cboAssumption.Text; strResults[1] = ""; NumericVector vecResults = m_pEngine.Evaluate("sam.result$estimate").AsNumeric(); strResults[2] = "Statistic: " + vecResults[0].ToString(strDecimalPlaces); strResults[3] = "Expectation: " + vecResults[1].ToString(strDecimalPlaces); strResults[4] = "Variance: " + vecResults[2].ToString(strDecimalPlaces); double dblStd = m_pEngine.Evaluate("sam.result$statistic").AsNumeric().First(); double dblPval = m_pEngine.Evaluate("sam.result$p.value").AsNumeric().First(); strResults[5] = "Standard deviate: " + dblStd.ToString(strDecimalPlaces); if (dblPval < Math.Pow(0.1, intDeciPlaces)) { strResults[6] = "p-value: < 0.001"; } else { strResults[6] = "p-value: " + dblPval.ToString(strDecimalPlaces); } frmGenResult pfrmResult = new frmGenResult(); pfrmResult.Text = "Summary"; pfrmResult.txtField.Text = strVarNM; pfrmResult.txtStatistics.Lines = strResults; pfrmProgress.Close(); pfrmResult.Show(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void btnRun_Click(object sender, EventArgs e) { try { frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); if (cboFldNm1.Text == "") { MessageBox.Show("Please select a proper field"); return; } // Creates the input and output matrices from the shapefile// //string strLayerName = cboTargetLayer.Text; //int intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName); //ILayer pLayer = m_pForm.axMapControl1.get_Layer(intLIndex); //IFeatureLayer pFLayer = pLayer as IFeatureLayer; //pFClass = pFLayer.FeatureClass; int nFeature = m_pFClass.FeatureCount(null); //Plot command for R StringBuilder plotCommmand = new StringBuilder(); if (!m_blnCreateSWM) { //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); if (strNameR == null) { return; } //Create spatial weight matrix in R if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); } else { MessageBox.Show("This geometry type is not supported"); pfrmProgress.Close(); this.Close(); } int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress); if (intSuccess == 0) { return; } } ////Get the file path and name to create spatial weight matrix //string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); //if (strNameR == null) // return; //int intSuccess = 0; ////Create spatial weight matrix in R //if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) //{ // m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); // intSuccess = m_pSnippet.CreateSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked); //} //else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) //{ // m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); // //intSuccess = m_pSnippet.ExploreSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked); // intSuccess = m_pSnippet.CreateSpatialWeightMatrixPts(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked, m_pClippedPolygon); // //chkCumulate.Visible = false; //} //else //{ // MessageBox.Show("This geometry type is not supported"); // pfrmProgress.Close(); // this.Close(); //} //if (intSuccess == 0) // return; IFeatureCursor pFCursor = m_pFClass.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables //Get variable index string strVarNM = (string)cboFldNm1.SelectedItem; int intVarIdx = m_pFClass.FindField(strVarNM); int intFIDIdx = m_pFClass.FindField(m_pFClass.OIDFieldName); // Collect FIDs to apply Brushing and Linking //Store Variable at Array double[] arrVar = new double[nFeature]; int[] arrFID = new int[nFeature]; int i = 0; m_arrXYCoord = new double[nFeature, 2]; List <int>[] NBIDs = new List <int> [nFeature]; IArea pArea; IPoint pPoint; while (pFeature != null) { if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { pArea = (IArea)pFeature.Shape; m_arrXYCoord[i, 0] = pArea.Centroid.X; m_arrXYCoord[i, 1] = pArea.Centroid.Y; } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { pPoint = (IPoint)pFeature.Shape; m_arrXYCoord[i, 0] = pPoint.X; m_arrXYCoord[i, 1] = pPoint.Y; } NBIDs[i] = m_pEngine.Evaluate("sample.nb[[" + (i + 1).ToString() + "]]").AsInteger().ToList(); arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx)); arrFID[i] = Convert.ToInt32(pFeature.get_Value(intFIDIdx)); i++; pFeature = pFCursor.NextFeature(); } pFCursor.Flush(); //Collect NB for Brushing and linking NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar); m_pEngine.SetSymbol(strVarNM, vecVar); if (chkStd.Checked) { m_pEngine.Evaluate(strVarNM + " <- scale(" + strVarNM + ")"); //Scaled vecVar = m_pEngine.Evaluate(strVarNM).AsNumeric(); } NumericVector vecWeightVar = null; if (cboMethod.Text == "MC") { vecWeightVar = m_pEngine.Evaluate("wx.sample <- lag.listw(sample.listw, " + strVarNM + ", zero.policy=TRUE)").AsNumeric(); } else if (cboMethod.Text == "GR") { string strStartPath = m_pForm.strPath; string pathr = strStartPath.Replace(@"\", @"/"); m_pEngine.Evaluate("source('" + pathr + "/AllFunctions.R')"); vecWeightVar = m_pEngine.Evaluate("wx.sample <- diff.lag.listw(sample.listw, " + strVarNM + ")").AsNumeric(); } else if (cboMethod.Text == "L") { string strStartPath = m_pForm.strPath; string pathr = strStartPath.Replace(@"\", @"/"); m_pEngine.Evaluate("source('" + pathr + "/AllFunctions.R')"); vecWeightVar = m_pEngine.Evaluate("wx.sample <- diff.lag.listw(sample.listw, " + strVarNM + ")").AsNumeric(); } m_pEngine.SetSymbol("WVar.sample", vecWeightVar); //double[] arrWeightVar = vecWeightVar.ToArray(); NumericVector vecCoeff = m_pEngine.Evaluate("lm(WVar.sample~" + strVarNM + ")$coefficients").AsNumeric(); frmMScatterResults pfrmMScatterResult = new frmMScatterResults(); pfrmMScatterResult.m_arrXYCoord = m_arrXYCoord; pfrmMScatterResult.m_NBIDs = NBIDs; pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsStartedFromZero = false; pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsMarginVisible = true; pfrmMScatterResult.pChart.ChartAreas[0].AxisY.IsStartedFromZero = false; pfrmMScatterResult.Text = "Moran Scatter Plot of " + m_pFLayer.Name; pfrmMScatterResult.pChart.Series.Clear(); System.Drawing.Color pMarkerColor = System.Drawing.Color.Blue; var seriesPts = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "Points", Color = pMarkerColor, BorderColor = pMarkerColor, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle }; pfrmMScatterResult.pChart.Series.Add(seriesPts); for (int j = 0; j < vecVar.Length; j++) { seriesPts.Points.AddXY(vecVar[j], vecWeightVar[j]); } var VLine = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "VLine", Color = System.Drawing.Color.Black, BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash, //BorderColor = System.Drawing.Color.Black, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line }; pfrmMScatterResult.pChart.Series.Add(VLine); VLine.Points.AddXY(vecVar.Average(), vecWeightVar.Min()); VLine.Points.AddXY(vecVar.Average(), vecWeightVar.Max()); var HLine = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "HLine", Color = System.Drawing.Color.Black, BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash, //BorderColor = System.Drawing.Color.Black, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line }; pfrmMScatterResult.pChart.Series.Add(HLine); HLine.Points.AddXY(vecVar.Min(), vecWeightVar.Average()); HLine.Points.AddXY(vecVar.Max(), vecWeightVar.Average()); var seriesLine = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "RegLine", Color = System.Drawing.Color.Red, //BorderColor = System.Drawing.Color.Black, IsVisibleInLegend = false, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line }; pfrmMScatterResult.pChart.Series.Add(seriesLine); seriesLine.Points.AddXY(vecVar.Min(), vecVar.Min() * vecCoeff[1] + vecCoeff[0]); seriesLine.Points.AddXY(vecVar.Max(), vecVar.Max() * vecCoeff[1] + vecCoeff[0]); if (chkStd.Checked) { pfrmMScatterResult.pChart.ChartAreas[0].AxisX.Title = "standardized " + strVarNM; pfrmMScatterResult.pChart.ChartAreas[0].AxisY.Title = "Spatially lagged standardized " + strVarNM; pfrmMScatterResult.lblRegression.Text = "Spatially lagged standardized " + strVarNM + " = " + vecCoeff[1].ToString("N3") + " * " + "standardized " + strVarNM; } else { pfrmMScatterResult.pChart.ChartAreas[0].AxisX.Title = strVarNM; pfrmMScatterResult.pChart.ChartAreas[0].AxisY.Title = "Spatially lagged " + strVarNM; pfrmMScatterResult.lblRegression.Text = "Spatially lagged " + strVarNM + " = " + vecCoeff[1].ToString("N3") + " * " + strVarNM + " + " + vecCoeff[0].ToString("N3"); } pfrmMScatterResult.m_pForm = m_pForm; pfrmMScatterResult.m_pFLayer = m_pFLayer; pfrmMScatterResult.m_pActiveView = m_pActiveView; pfrmMScatterResult.arrVar = arrVar; pfrmMScatterResult.arrFID = arrFID; pfrmMScatterResult.strFIDNM = m_pFClass.OIDFieldName; //pfrmMScatterResult.arrWeightVar = arrWeightVar; pfrmMScatterResult.pMakerColor = pMarkerColor; pfrmMScatterResult.strVarNM = strVarNM; if (chkStd.Checked) { pfrmMScatterResult.pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false; pfrmMScatterResult.pChart.ChartAreas[0].AxisX.CustomLabels.Clear(); pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.TickMarkStyle = System.Windows.Forms.DataVisualization.Charting.TickMarkStyle.None; //pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.Interval = 1; //pfrmMScatterResult.pChart.ChartAreas[0].AxisX.MajorTickMark.IntervalOffset = -2; int intMin = Convert.ToInt32(Math.Floor(vecVar.Min())); int intMax = Convert.ToInt32(Math.Ceiling(vecVar.Max())); for (int n = intMin; n < intMax; n++) { System.Windows.Forms.DataVisualization.Charting.CustomLabel pcutsomLabel = new System.Windows.Forms.DataVisualization.Charting.CustomLabel(); pcutsomLabel.FromPosition = n - 0.5; pcutsomLabel.ToPosition = n + 0.5; pcutsomLabel.Text = n.ToString(); pfrmMScatterResult.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel); } } pfrmMScatterResult.Show(); pfrmProgress.Close(); //this.Close(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void btnRun_Click(object sender, EventArgs e) { try { frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); if (cboFieldName.Text == "") { MessageBox.Show("Please select the dependent input variables to be used in the regression model.", "Please choose at least one input variable"); } if (lstIndeVar.Items.Count == 0) { MessageBox.Show("Please select independents input variables to be used in the regression model.", "Please choose at least one input variable"); } //Decimal places int intDeciPlaces = 5; //Get number of Independent variables int nIndevarlistCnt = lstIndeVar.Items.Count; //Indicate an intercept only model (2) or a non-intercept model (1) or not (0) int intInterceptModel = 1; for (int j = 0; j < nIndevarlistCnt; j++) { if ((string)lstIndeVar.Items[j] == "Intercept") { intInterceptModel = 0; } } if (nIndevarlistCnt == 1 && intInterceptModel == 0) { intInterceptModel = 2; } int nIDepen = 0; if (intInterceptModel == 0) { nIDepen = nIndevarlistCnt - 1; } else if (intInterceptModel == 1) { nIDepen = nIndevarlistCnt; } // Gets the column of the dependent variable String dependentName = (string)cboFieldName.SelectedItem; //sourceTable.AcceptChanges(); //DataTable dependent = sourceTable.DefaultView.ToTable(false, dependentName); // Gets the columns of the independent variables String[] independentNames = new string[nIDepen]; int intIdices = 0; string strIndependentName = ""; for (int j = 0; j < nIndevarlistCnt; j++) { strIndependentName = (string)lstIndeVar.Items[j]; if (strIndependentName != "Intercept") { independentNames[intIdices] = strIndependentName; intIdices++; } } int nFeature = m_pFClass.FeatureCount(null); //Warning for method if (rbtEigen.Checked) { if (nFeature > m_pForm.intWarningCount) { DialogResult dialogResult = MessageBox.Show("It might take a lot of time. Do you want to continue?", "Warning", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { pfrmProgress.Close(); return; } } } IFeatureCursor pFCursor = m_pFLayer.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables int intDepenIdx = m_pFLayer.FeatureClass.Fields.FindField(dependentName); int[] idxes = new int[nIDepen]; for (int j = 0; j < nIDepen; j++) { idxes[j] = m_pFLayer.FeatureClass.Fields.FindField(independentNames[j]); } //Store independent values at Array double[] arrDepen = new double[nFeature]; double[][] arrInDepen = new double[nIDepen][]; //Zigzaged Array needs to be define for (int j = 0; j < nIDepen; j++) { arrInDepen[j] = new double[nFeature]; } int i = 0; while (pFeature != null) { arrDepen[i] = Convert.ToDouble(pFeature.get_Value(intDepenIdx)); for (int j = 0; j < nIDepen; j++) { arrInDepen[j][i] = Convert.ToDouble(pFeature.get_Value(idxes[j])); } i++; pFeature = pFCursor.NextFeature(); } //Plot command for R StringBuilder plotCommmand = new StringBuilder(); if (!m_blnCreateSWM) { //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); if (strNameR == null) { return; } //Create spatial weight matrix in R if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); } else { MessageBox.Show("This geometry type is not supported"); pfrmProgress.Close(); this.Close(); } int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress); if (intSuccess == 0) { return; } } //Dependent variable to R vector NumericVector vecDepen = m_pEngine.CreateNumericVector(arrDepen); m_pEngine.SetSymbol(dependentName, vecDepen); if (rbtError.Checked) { plotCommmand.Append("errorsarlm(" + dependentName + "~"); } else if (rbtLag.Checked || rbtDurbin.Checked) { plotCommmand.Append("lagsarlm(" + dependentName + "~"); } else { plotCommmand.Append("spautolm(" + dependentName + "~"); } if (intInterceptModel == 2) { plotCommmand.Append("1"); } else { for (int j = 0; j < nIDepen; j++) { //double[] arrVector = arrInDepen.GetColumn<double>(j); NumericVector vecIndepen = m_pEngine.CreateNumericVector(arrInDepen[j]); m_pEngine.SetSymbol(independentNames[j], vecIndepen); plotCommmand.Append(independentNames[j] + "+"); } plotCommmand.Remove(plotCommmand.Length - 1, 1); if (intInterceptModel == 1) { plotCommmand.Append("-1"); } } //Select Method if (rbtEigen.Checked) { plotCommmand.Append(", method='eigen'"); } else if (rbtMatrix.Checked) { plotCommmand.Append(", method='Matrix'"); } else if (rbtMatrixJ.Checked) { plotCommmand.Append(", method='Matrix_J'"); } else if (rbtLU.Checked) { plotCommmand.Append(", method='LU'"); } else if (rbtChebyshev.Checked) { plotCommmand.Append(", method='Chebyshev'"); } else if (rbtMC.Checked) { plotCommmand.Append(", method='MC'"); } else { plotCommmand.Append(", method='eigen'"); } if (rbtError.Checked) { plotCommmand.Append(", listw=sample.listw, tol.solve=1.0e-20, zero.policy=TRUE)"); } else if (rbtLag.Checked) { plotCommmand.Append(", listw=sample.listw, tol.solve=1.0e-20, zero.policy=TRUE)"); } else if (rbtCAR.Checked) { plotCommmand.Append(", listw=sample.listw, family='CAR', verbose=TRUE, zero.policy=TRUE)"); } else if (rbtSMA.Checked) { plotCommmand.Append(", listw=sample.listw, family='SMA', verbose=TRUE, zero.policy=TRUE)"); } else if (rbtDurbin.Checked) { plotCommmand.Append(", type='mixed', listw=sample.listw, tol.solve=1.0e-20, zero.policy=TRUE)"); } else { return; } try { m_pEngine.Evaluate("sum.lm <- summary(" + plotCommmand.ToString() + ", Nagelkerke=T)"); } catch { MessageBox.Show("Cannot solve the regression. Try again with different variables."); pfrmProgress.Close(); return; } //Collect results from R NumericMatrix matCoe = m_pEngine.Evaluate("as.matrix(sum.lm$Coef)").AsNumericMatrix(); double dblLRLambda = m_pEngine.Evaluate("as.numeric(sum.lm$LR1$statistic)").AsNumeric().First(); double dblpLambda = m_pEngine.Evaluate("as.numeric(sum.lm$LR1$p.value)").AsNumeric().First(); double dblLRErrorModel = m_pEngine.Evaluate("as.numeric(sum.lm$LR1$estimate)").AsNumeric().First(); double dblSigmasquared = 0; double dblAIC = 0; double dblWald = 0; double dblpWald = 0; if (rbtLag.Checked || rbtError.Checked || rbtDurbin.Checked) { dblSigmasquared = m_pEngine.Evaluate("as.numeric(sum.lm$s2)").AsNumeric().First(); //dblAIC = pEngine.Evaluate("as.numeric(sum.lm$AIC_lm.model)").AsNumeric().First(); dblWald = m_pEngine.Evaluate("as.numeric(sum.lm$Wald1$statistic)").AsNumeric().First(); dblpWald = m_pEngine.Evaluate("as.numeric(sum.lm$Wald1$p.value)").AsNumeric().First(); double dblParaCnt = m_pEngine.Evaluate("as.numeric(sum.lm$parameters)").AsNumeric().First(); dblAIC = (2 * dblParaCnt) - (2 * dblLRErrorModel); } else { dblSigmasquared = m_pEngine.Evaluate("as.numeric(sum.lm$fit$s2)").AsNumeric().First(); double dblParaCnt = m_pEngine.Evaluate("as.numeric(sum.lm$parameters)").AsNumeric().First(); dblAIC = (2 * dblParaCnt) - (2 * dblLRErrorModel); } double dblLambda = 0; double dblSELambda = 0; double dblResiAuto = 0; double dblResiAutoP = 0; if (rbtLag.Checked || rbtDurbin.Checked) { dblLambda = m_pEngine.Evaluate("as.numeric(sum.lm$rho)").AsNumeric().First(); dblSELambda = m_pEngine.Evaluate("as.numeric(sum.lm$rho.se)").AsNumeric().First(); dblResiAuto = m_pEngine.Evaluate("as.numeric(sum.lm$LMtest)").AsNumeric().First(); dblResiAutoP = m_pEngine.Evaluate("as.numeric(sum.lm$rho.se)").AsNumeric().First(); } else { dblLambda = m_pEngine.Evaluate("as.numeric(sum.lm$lambda)").AsNumeric().First(); dblSELambda = m_pEngine.Evaluate("as.numeric(sum.lm$lambda.se)").AsNumeric().First(); } double dblRsquared = 0; //Previous method //if(intInterceptModel != 1) // dblRsquared = m_pEngine.Evaluate("as.numeric(sum.lm$NK)").AsNumeric().First(); //New pseduo R squared calculation if (rbtError.Checked || rbtLag.Checked || rbtDurbin.Checked) { dblRsquared = m_pEngine.Evaluate("summary(lm(sum.lm$y~sum.lm$fitted.values))$r.squared").AsNumeric().First(); } else { dblRsquared = m_pEngine.Evaluate("summary(lm(sum.lm$Y~sum.lm$fit$fitted.values))$r.squared").AsNumeric().First(); } //Open Ouput form frmRegResult pfrmRegResult = new frmRegResult(); if (rbtError.Checked) { pfrmRegResult.Text = "Spatial Autoregressive Model Summary (Error Model)"; } else if (rbtLag.Checked) { pfrmRegResult.Text = "Spatial Autoregressive Model Summary (Lag Model)"; } else if (rbtCAR.Checked) { pfrmRegResult.Text = "Spatial Autoregressive Model Summary (CAR Model)"; } else if (rbtDurbin.Checked) { pfrmRegResult.Text = "Spatial Autoregressive Model Summary (Spatial Durbin Model)"; } else { pfrmRegResult.Text = "Spatial Autoregressive Model Summary (SMA Model)"; } //pfrmRegResult.panel2.Visible = true; //Create DataTable to store Result System.Data.DataTable tblRegResult = new DataTable("SRResult"); //Assign DataTable DataColumn dColName = new DataColumn(); dColName.DataType = System.Type.GetType("System.String"); dColName.ColumnName = "Name"; tblRegResult.Columns.Add(dColName); DataColumn dColValue = new DataColumn(); dColValue.DataType = System.Type.GetType("System.Double"); dColValue.ColumnName = "Estimate"; tblRegResult.Columns.Add(dColValue); DataColumn dColSE = new DataColumn(); dColSE.DataType = System.Type.GetType("System.Double"); dColSE.ColumnName = "Std. Error"; tblRegResult.Columns.Add(dColSE); String.Format("{0:0.##}", tblRegResult.Columns["Std. Error"]); DataColumn dColTValue = new DataColumn(); dColTValue.DataType = System.Type.GetType("System.Double"); dColTValue.ColumnName = "z value"; tblRegResult.Columns.Add(dColTValue); DataColumn dColPvT = new DataColumn(); dColPvT.DataType = System.Type.GetType("System.Double"); dColPvT.ColumnName = "Pr(>|z|)"; tblRegResult.Columns.Add(dColPvT); //if (rbtDurbin.Checked) // nIDepen = nIDepen * 2; int intNCoeff = matCoe.RowCount; //Store Data Table by R result for (int j = 0; j < intNCoeff; j++) { DataRow pDataRow = tblRegResult.NewRow(); if (j == 0 && intInterceptModel != 1) { pDataRow["Name"] = "(Intercept)"; } else if (intInterceptModel == 1) { if (rbtDurbin.Checked) { if (j <= intNCoeff / 2) { pDataRow["Name"] = independentNames[j]; } else { pDataRow["Name"] = "lag." + independentNames[j - (intNCoeff / 2)]; } } else { pDataRow["Name"] = independentNames[j]; } } else { if (rbtDurbin.Checked) { if (j <= intNCoeff / 2) { pDataRow["Name"] = independentNames[j - 1]; } else { pDataRow["Name"] = "lag." + independentNames[j - (intNCoeff / 2) - 1]; } } else { pDataRow["Name"] = independentNames[j - 1]; } } pDataRow["Estimate"] = Math.Round(matCoe[j, 0], intDeciPlaces); pDataRow["Std. Error"] = Math.Round(matCoe[j, 1], intDeciPlaces); pDataRow["z value"] = Math.Round(matCoe[j, 2], intDeciPlaces); pDataRow["Pr(>|z|)"] = Math.Round(matCoe[j, 3], intDeciPlaces); tblRegResult.Rows.Add(pDataRow); } //Assign Datagridview to Data Table pfrmRegResult.dgvResults.DataSource = tblRegResult; //Assign values at Textbox string strDecimalPlaces = "N" + intDeciPlaces.ToString(); string[] strResults = new string[5]; if (rbtLag.Checked || rbtDurbin.Checked) { if (dblpLambda < 0.001) { strResults[0] = "rho: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value < 0.001"; } else if (dblpLambda > 0.999) { strResults[0] = "rho: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value > 0.999"; } else { strResults[0] = "rho: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces); } if (dblpWald < 0.001) { strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value < 0.001"; } else if (dblpWald > 0.999) { strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value > 0.999"; } else { strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value: " + dblpWald.ToString(strDecimalPlaces); } strResults[2] = "Log likelihood: " + dblLRErrorModel.ToString(strDecimalPlaces) + ", Sigma-squared: " + dblSigmasquared.ToString(strDecimalPlaces); strResults[3] = "AIC: " + dblAIC.ToString(strDecimalPlaces) + ", LM test for residuals autocorrelation: " + dblResiAuto.ToString(strDecimalPlaces); } else if (rbtError.Checked) { if (dblpLambda < 0.001) { strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value < 0.001"; } else if (dblpLambda > 0.999) { strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value > 0.999"; } else { strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces); } if (dblpWald < 0.001) { strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value < 0.001"; } else if (dblpWald > 0.999) { strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value > 0.999"; } else { strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value: " + dblpWald.ToString(strDecimalPlaces); } //strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + // ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces); //strResults[1] = "Asymptotic S.E: " + dblSELambda.ToString(strDecimalPlaces) + // ", Wald: " + dblWald.ToString(strDecimalPlaces) + ", p-value: " + dblpWald.ToString(strDecimalPlaces); strResults[2] = "Log likelihood: " + dblLRErrorModel.ToString(strDecimalPlaces) + ", Sigma-squared: " + dblSigmasquared.ToString(strDecimalPlaces); strResults[3] = "AIC: " + dblAIC.ToString(strDecimalPlaces); } else { if (dblpLambda < 0.001) { strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value < 0.001"; } else if (dblpLambda > 0.999) { strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value > 0.999"; } else { strResults[0] = "Lambda: " + dblLambda.ToString(strDecimalPlaces) + ", LR Test Value: " + dblLRLambda.ToString(strDecimalPlaces) + ", p-value: " + dblpLambda.ToString(strDecimalPlaces); } strResults[1] = "Numerical Hessian S.E of lambda: " + dblSELambda.ToString(strDecimalPlaces); strResults[2] = "Log likelihood: " + dblLRErrorModel.ToString(strDecimalPlaces) + ", Sigma-squared: " + dblSigmasquared.ToString(strDecimalPlaces); strResults[3] = "AIC: " + dblAIC.ToString(strDecimalPlaces); } //if (intInterceptModel != 1) // strResults[4] = "Pseudo-R-squared: " + dblRsquared.ToString(strDecimalPlaces); //else // strResults[4] = ""; strResults[4] = "Pseudo-R-squared: " + dblRsquared.ToString(strDecimalPlaces); pfrmRegResult.txtOutput.Lines = strResults; //Save Outputs in SHP if (chkSave.Checked) { pfrmProgress.lblStatus.Text = "Saving residuals:"; //The field names are related with string[] DeterminedName in clsSnippet string strResiFldName = lstSave.Items[0].SubItems[1].Text; //Get EVs and residuals NumericVector nvResiduals = m_pEngine.Evaluate("as.numeric(sum.lm$residuals)").AsNumeric(); if (rbtCAR.Checked || rbtSMA.Checked) { nvResiduals = m_pEngine.Evaluate("as.numeric(sum.lm$fit$residuals)").AsNumeric(); } // Create field, if there isn't if (m_pFClass.FindField(strResiFldName) == -1) { //Add fields IField newField = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)newField; fieldEdit.Name_2 = strResiFldName; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; m_pFClass.AddField(newField); } else { DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " field?", "Overwrite", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { return; } } //Update Field pFCursor.Flush(); pFCursor = m_pFClass.Update(null, false); pFeature = pFCursor.NextFeature(); int featureIdx = 0; int intResiFldIdx = m_pFClass.FindField(strResiFldName); while (pFeature != null) { //Update Residuals pFeature.set_Value(intResiFldIdx, (object)nvResiduals[featureIdx]); pFCursor.UpdateFeature(pFeature); pFeature = pFCursor.NextFeature(); featureIdx++; } } pfrmProgress.Close(); pfrmRegResult.Show(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void btnRun_Click(object sender, EventArgs e) { frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Collecting Data:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); try { //REngine pEngine = m_pForm.pEngine; if (cboFieldName.Text == "") { MessageBox.Show("Please select the dependent input variables to be used in the regression model.", "Please choose at least one input variable"); } if (lstIndeVar.Items.Count == 0) { MessageBox.Show("Please select independents input variables to be used in the regression model.", "Please choose at least one input variable"); } //Decimal places int intDeciPlaces = 5; //Get number of Independent variables int nIndevarlistCnt = lstIndeVar.Items.Count; //Indicate an intercept only model (2) or a non-intercept model (1) or not (0) int intInterceptModel = 1; for (int j = 0; j < nIndevarlistCnt; j++) { if ((string)lstIndeVar.Items[j] == "Intercept") { intInterceptModel = 0; } } if (nIndevarlistCnt == 1 && intInterceptModel == 0) { intInterceptModel = 2; } int nIDepen = 0; if (intInterceptModel == 0) { nIDepen = nIndevarlistCnt - 1; } else if (intInterceptModel == 1) { nIDepen = nIndevarlistCnt; } // Gets the column of the dependent variable String dependentName = (string)cboFieldName.SelectedItem; //sourceTable.AcceptChanges(); //DataTable dependent = sourceTable.DefaultView.ToTable(false, dependentName); // Gets the columns of the independent variables String[] independentNames = new string[nIDepen]; int intIdices = 0; string strIndependentName = ""; for (int j = 0; j < nIndevarlistCnt; j++) { strIndependentName = (string)lstIndeVar.Items[j]; if (strIndependentName != "Intercept") { independentNames[intIdices] = strIndependentName; intIdices++; } } // Creates the input and output matrices from the shapefile// clsSnippet pSnippet = new clsSnippet(); int nFeature = m_pFClass.FeatureCount(null); IFeatureCursor pFCursor = m_pFClass.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables int intDepenIdx = m_pFClass.Fields.FindField(dependentName); int[] idxes = new int[nIDepen]; for (int j = 0; j < nIDepen; j++) { idxes[j] = m_pFClass.Fields.FindField(independentNames[j]); } //Store independent values at Array double[] arrDepen = new double[nFeature]; double[][] arrInDepen = new double[nIDepen][]; //Zigzaged Array needs to be define for (int j = 0; j < nIDepen; j++) { arrInDepen[j] = new double[nFeature]; } int i = 0; while (pFeature != null) { arrDepen[i] = Convert.ToDouble(pFeature.get_Value(intDepenIdx)); for (int j = 0; j < nIDepen; j++) { //arrInDepen[j] = new double[nFeature]; arrInDepen[j][i] = Convert.ToDouble(pFeature.get_Value(idxes[j])); //arrInDepen[i, j] = Convert.ToDouble(pFeature.get_Value(idxes[j])); } i++; pFeature = pFCursor.NextFeature(); } pfrmProgress.lblStatus.Text = "Calculate Regression Coefficients"; //Plot command for R StringBuilder plotCommmand = new StringBuilder(); //Dependent variable to R vector NumericVector vecDepen = m_pEngine.CreateNumericVector(arrDepen); m_pEngine.SetSymbol(dependentName, vecDepen); plotCommmand.Append("lm(" + dependentName + "~"); if (intInterceptModel == 2) { plotCommmand.Append("1"); } else { for (int j = 0; j < nIDepen; j++) { NumericVector vecIndepen = m_pEngine.CreateNumericVector(arrInDepen[j]); m_pEngine.SetSymbol(independentNames[j], vecIndepen); plotCommmand.Append(independentNames[j] + "+"); } plotCommmand.Remove(plotCommmand.Length - 1, 1); if (intInterceptModel == 1) { plotCommmand.Append("-1"); } } plotCommmand.Append(")"); m_pEngine.Evaluate("sum.lm <- summary(" + plotCommmand + ")"); NumericMatrix matCoe = m_pEngine.Evaluate("as.matrix(sum.lm$coefficient)").AsNumericMatrix(); NumericVector vecF = m_pEngine.Evaluate("as.numeric(sum.lm$fstatistic)").AsNumeric(); m_pEngine.Evaluate("fvalue <- as.numeric(sum.lm$fstatistic)"); double dblPValueF = m_pEngine.Evaluate("pf(fvalue[1],fvalue[2],fvalue[3],lower.tail=F)").AsNumeric().First(); double dblRsqaure = m_pEngine.Evaluate("sum.lm$r.squared").AsNumeric().First(); double dblAdjRsqaure = m_pEngine.Evaluate("sum.lm$adj.r.squared").AsNumeric().First(); double dblResiSE = m_pEngine.Evaluate("sum.lm$sigma").AsNumeric().First(); NumericVector vecResiDF = m_pEngine.Evaluate("sum.lm$df").AsNumeric(); double dblResiMC = 0; double dblResiMCpVal = 0; if (chkResiAuto.Checked) { if (!m_blnCreateSWM) { //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); if (strNameR == null) { return; } //Create spatial weight matrix in R if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); } else { MessageBox.Show("This geometry type is not supported"); pfrmProgress.Close(); this.Close(); } int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress); if (intSuccess == 0) { return; } } m_pEngine.Evaluate("sample.n <- length(sample.nb)"); //Calculate MC if (cboAlternative.Text == "Greater") { m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'greater', zero.policy=TRUE)"); } else if (cboAlternative.Text == "Less") { m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'less', zero.policy=TRUE)"); } else if (cboAlternative.Text == "Two Sided") { m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'two.sided', zero.policy=TRUE)"); } else { m_pEngine.Evaluate("zmc <- lm.morantest(" + plotCommmand.ToString() + ", listw=sample.listw, alternative = 'greater', zero.policy=TRUE)"); } dblResiMC = m_pEngine.Evaluate("zmc$estimate[1]").AsNumeric().First(); dblResiMCpVal = m_pEngine.Evaluate("zmc$p.value").AsNumeric().First(); } pfrmProgress.lblStatus.Text = "Printing Output:"; //Open Ouput form frmRegResult pfrmRegResult = new frmRegResult(); pfrmRegResult.Text = "Linear Regression Summary"; //Create DataTable to store Result System.Data.DataTable tblRegResult = new DataTable("OLSResult"); //Assign DataTable DataColumn dColName = new DataColumn(); dColName.DataType = System.Type.GetType("System.String"); dColName.ColumnName = "Name"; tblRegResult.Columns.Add(dColName); DataColumn dColValue = new DataColumn(); dColValue.DataType = System.Type.GetType("System.Double"); dColValue.ColumnName = "Estimate"; tblRegResult.Columns.Add(dColValue); DataColumn dColSE = new DataColumn(); dColSE.DataType = System.Type.GetType("System.Double"); dColSE.ColumnName = "Std. Error"; tblRegResult.Columns.Add(dColSE); DataColumn dColTValue = new DataColumn(); dColTValue.DataType = System.Type.GetType("System.Double"); dColTValue.ColumnName = "t value"; tblRegResult.Columns.Add(dColTValue); DataColumn dColPvT = new DataColumn(); dColPvT.DataType = System.Type.GetType("System.Double"); dColPvT.ColumnName = "Pr(>|t|)"; tblRegResult.Columns.Add(dColPvT); //Store Data Table by R result int intNCoeff = matCoe.RowCount; for (int j = 0; j < intNCoeff; j++) { DataRow pDataRow = tblRegResult.NewRow(); if (j == 0 && intInterceptModel != 1) { pDataRow["Name"] = "(Intercept)"; } else if (intInterceptModel == 1) { pDataRow["Name"] = independentNames[j]; } else { pDataRow["Name"] = independentNames[j - 1]; } pDataRow["Estimate"] = Math.Round(matCoe[j, 0], intDeciPlaces); pDataRow["Std. Error"] = Math.Round(matCoe[j, 1], intDeciPlaces); pDataRow["t value"] = Math.Round(matCoe[j, 2], intDeciPlaces); pDataRow["Pr(>|t|)"] = Math.Round(matCoe[j, 3], intDeciPlaces); tblRegResult.Rows.Add(pDataRow); } //Assign Datagridview to Data Table pfrmRegResult.dgvResults.DataSource = tblRegResult; //Assign values at Textbox string[] strResults = null; if (chkResiAuto.Checked) { strResults = new string[4]; if (dblResiMCpVal < 0.001) { strResults[3] = "MC of residuals: " + dblResiMC.ToString("N3") + ", p-value < 0.001"; } else if (dblResiMCpVal > 0.999) { strResults[3] = "MC of residuals: " + dblResiMC.ToString("N3") + ", p-value > 0.999"; } else { strResults[3] = "MC of residuals: " + dblResiMC.ToString("N3") + ", p-value: " + dblResiMCpVal.ToString("N3"); } } else { strResults = new string[3]; } strResults[0] = "Residual standard error: " + dblResiSE.ToString("N" + intDeciPlaces.ToString()) + " on " + vecResiDF[1].ToString() + " degrees of freedom"; strResults[1] = "Multiple R-squared: " + dblRsqaure.ToString("N" + intDeciPlaces.ToString()) + ", Adjusted R-squared: " + dblAdjRsqaure.ToString("N" + intDeciPlaces.ToString()); if (intInterceptModel != 2) { if (dblPValueF < 0.001) { strResults[2] = "F-Statistic: " + vecF[0].ToString("N" + intDeciPlaces.ToString()) + " on " + vecF[1].ToString() + " and " + vecF[2].ToString() + " DF, p-value < 0.001"; } else if (dblPValueF > 0.999) { strResults[2] = "F-Statistic: " + vecF[0].ToString("N" + intDeciPlaces.ToString()) + " on " + vecF[1].ToString() + " and " + vecF[2].ToString() + " DF, p-value > 0.999"; } else { strResults[2] = "F-Statistic: " + vecF[0].ToString("N" + intDeciPlaces.ToString()) + " on " + vecF[1].ToString() + " and " + vecF[2].ToString() + " DF, p-value: " + dblPValueF.ToString("N" + intDeciPlaces.ToString()); } } else { strResults[2] = ""; } pfrmRegResult.txtOutput.Lines = strResults; pfrmRegResult.Show(); //Create Plots for Regression if (chkPlots.Checked) { string strTitle = "Linear Regression Results"; string strCommand = "plot(" + plotCommmand + ");"; pSnippet.drawPlottoForm(strTitle, strCommand); } //Save Outputs in SHP if (chkSave.Checked) { //The field names are related with string[] DeterminedName in clsSnippet string strResiFldName = lstSave.Items[0].SubItems[1].Text; //Get EVs and residuals NumericVector nvResiduals = m_pEngine.Evaluate("as.numeric(sum.lm$residuals)").AsNumeric(); // Create field, if there isn't if (m_pFClass.FindField(strResiFldName) == -1) { //Add fields IField newField = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)newField; fieldEdit.Name_2 = strResiFldName; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; m_pFClass.AddField(newField); } else { DialogResult dialogResult = MessageBox.Show("Do you want to overwrite " + strResiFldName + " field?", "Overwrite", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) { return; } } //Update Field pFCursor.Flush(); pFCursor = m_pFClass.Update(null, false); pFeature = pFCursor.NextFeature(); int featureIdx = 0; int intResiFldIdx = m_pFClass.FindField(strResiFldName); while (pFeature != null) { //Update Residuals pFeature.set_Value(intResiFldIdx, (object)nvResiduals[featureIdx]); pFCursor.UpdateFeature(pFeature); pFeature = pFCursor.NextFeature(); featureIdx++; } MessageBox.Show("Residuals are stored in the shape file"); } pfrmProgress.Close(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); pfrmProgress.Close(); return; } }
private void btnRun_Click(object sender, EventArgs e) { try { //Checking if (cboFieldName.Text == "") { MessageBox.Show("Please select target field"); return; } frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); int nFeature = m_pFClass.FeatureCount(null); IFeatureCursor pFCursor = m_pFLayer.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables //Get variable index string strVarNM = (string)cboFieldName.SelectedItem; int intVarIdx = m_pFClass.FindField(strVarNM); //Store Variable at Array double[] arrVar = new double[nFeature]; int i = 0; while (pFeature != null) { arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx)); i++; pFeature = pFCursor.NextFeature(); } //Plot command for R StringBuilder plotCommmand = new StringBuilder(); if (!m_blnCreateSWM) { //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(m_pFLayer); if (strNameR == null) { return; } //Create spatial weight matrix in R if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); } else { MessageBox.Show("This geometry type is not supported"); pfrmProgress.Close(); this.Close(); } int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress); if (intSuccess == 0) { return; } } NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar); m_pEngine.SetSymbol(strVarNM, vecVar); if (cboSAM.Text == "Local Moran") { #region Local Moran plotCommmand.Append("localmoran(" + strVarNM + ", sample.listw, alternative = 'two.sided', "); //select multiple correction method (only Bonferroni.. 100915 HK) if (cboAdjustment.Text == "None") { plotCommmand.Append(", zero.policy=TRUE)"); } else if (cboAdjustment.Text == "Bonferroni correction") { plotCommmand.Append("p.adjust.method='bonferroni', zero.policy=TRUE)"); } NumericMatrix nmResults = m_pEngine.Evaluate(plotCommmand.ToString()).AsNumericMatrix(); string strFlgFldNam = lvFields.Items[3].SubItems[1].Text; //Save Output on SHP //Add Target fields to store results in the shapefile for (int j = 0; j < 4; j++) { IField newField = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)newField; fieldEdit.Name_2 = lvFields.Items[j].SubItems[1].Text; if (j == 3) { fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; } else { fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; } m_pFClass.AddField(newField); } //Update Field pFCursor = m_pFClass.Update(null, false); pFeature = pFCursor.NextFeature(); int intStatFldIdx = m_pFClass.FindField(lvFields.Items[0].SubItems[1].Text); int intZFldIdx = m_pFClass.FindField(lvFields.Items[1].SubItems[1].Text); int intPrFldIdx = m_pFClass.FindField(lvFields.Items[2].SubItems[1].Text); int intFlgFldIdx = m_pFClass.FindField(strFlgFldNam); double dblValue = 0, dblPvalue = 0, dblZvalue = 0; double dblValueMean = arrVar.Average(); double dblPrCri = Convert.ToDouble(nudConfLevel.Value); int featureIdx = 0; while (pFeature != null) { dblValue = arrVar[featureIdx] - dblValueMean; dblZvalue = nmResults[featureIdx, 3]; dblPvalue = nmResults[featureIdx, 4]; pFeature.set_Value(intStatFldIdx, (object)nmResults[featureIdx, 0]); pFeature.set_Value(intZFldIdx, dblZvalue); pFeature.set_Value(intPrFldIdx, dblPvalue); if (dblPvalue < dblPrCri) { if (dblZvalue > 0) { if (dblValue > 0) { pFeature.set_Value(intFlgFldIdx, "HH"); } else { pFeature.set_Value(intFlgFldIdx, "LL"); } } else { if (dblValue > 0) { pFeature.set_Value(intFlgFldIdx, "HL"); } else { pFeature.set_Value(intFlgFldIdx, "LH"); } } } //else // pFeature.set_Value(intFlgFldIdx, ""); pFCursor.UpdateFeature(pFeature); pFeature = pFCursor.NextFeature(); featureIdx++; } pfrmProgress.Close(); if (chkMap.Checked) { double[,] adblMinMaxForLabel = new double[2, 4]; ITable pTable = (ITable)m_pFClass; IUniqueValueRenderer pUniqueValueRenderer = new UniqueValueRendererClass(); pUniqueValueRenderer.FieldCount = 1; pUniqueValueRenderer.set_Field(0, strFlgFldNam); IDataStatistics pDataStat; IStatisticsResults pStatResults; ICursor pCursor; if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { ISimpleFillSymbol pSymbol; IQueryFilter pQFilter = new QueryFilterClass(); pQFilter.WhereClause = strFlgFldNam + " = 'HH'"; int intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 0] = pStatResults.Minimum; adblMinMaxForLabel[1, 0] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleFillSymbolClass(); pSymbol.Style = esriSimpleFillStyle.esriSFSSolid; pSymbol.Color = m_pSnippet.getRGB(255, 80, 80); pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("HH", "HH (no obs)"); } else { pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")"); } pQFilter.WhereClause = strFlgFldNam + " = 'LL'"; intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 1] = pStatResults.Minimum; adblMinMaxForLabel[1, 1] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleFillSymbolClass(); pSymbol.Style = esriSimpleFillStyle.esriSFSSolid; pSymbol.Color = m_pSnippet.getRGB(50, 157, 194); pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("LL", "LL (no obs)"); } else { pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")"); } pQFilter.WhereClause = strFlgFldNam + " = 'HL'"; intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 2] = pStatResults.Minimum; adblMinMaxForLabel[1, 2] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleFillSymbolClass(); pSymbol.Style = esriSimpleFillStyle.esriSFSSolid; pSymbol.Color = m_pSnippet.getRGB(244, 199, 0); pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("HL", "HL (no obs)"); } else { pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")"); } pQFilter.WhereClause = strFlgFldNam + " = 'LH'"; intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 3] = pStatResults.Minimum; adblMinMaxForLabel[1, 3] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleFillSymbolClass(); pSymbol.Style = esriSimpleFillStyle.esriSFSSolid; pSymbol.Color = m_pSnippet.getRGB(173, 255, 179); pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("LH", "LH (no obs)"); } else { pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")"); } pSymbol = new SimpleFillSymbolClass(); pSymbol.Style = esriSimpleFillStyle.esriSFSSolid; pSymbol.Color = m_pSnippet.getRGB(200, 200, 200); //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol); //pUniqueValueRenderer.set_Label("", "Not significant"); pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol; pUniqueValueRenderer.DefaultLabel = "Not significant"; pUniqueValueRenderer.UseDefaultSymbol = true; } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { ISimpleMarkerSymbol pSymbol; IQueryFilter pQFilter = new QueryFilterClass(); pQFilter.WhereClause = strFlgFldNam + " = 'HH'"; int intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 0] = pStatResults.Minimum; adblMinMaxForLabel[1, 0] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleMarkerSymbolClass(); pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; pSymbol.Color = m_pSnippet.getRGB(255, 80, 80); pUniqueValueRenderer.AddValue("HH", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("HH", "HH (no obs)"); } else { pUniqueValueRenderer.set_Label("HH", "HH (" + adblMinMaxForLabel[0, 0].ToString("N1") + "-" + adblMinMaxForLabel[1, 0].ToString("N1") + ")"); } pQFilter.WhereClause = strFlgFldNam + " = 'LL'"; intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 1] = pStatResults.Minimum; adblMinMaxForLabel[1, 1] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleMarkerSymbolClass(); pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; pSymbol.Color = m_pSnippet.getRGB(50, 157, 194); pUniqueValueRenderer.AddValue("LL", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("LL", "LL (no obs)"); } else { pUniqueValueRenderer.set_Label("LL", "LL (" + adblMinMaxForLabel[0, 1].ToString("N1") + "-" + adblMinMaxForLabel[1, 1].ToString("N1") + ")"); } pQFilter.WhereClause = strFlgFldNam + " = 'HL'"; intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 2] = pStatResults.Minimum; adblMinMaxForLabel[1, 2] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleMarkerSymbolClass(); pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; pSymbol.Color = m_pSnippet.getRGB(244, 199, 0); pUniqueValueRenderer.AddValue("HL", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("HL", "HL (no obs)"); } else { pUniqueValueRenderer.set_Label("HL", "HL (" + adblMinMaxForLabel[0, 2].ToString("N1") + "-" + adblMinMaxForLabel[1, 2].ToString("N1") + ")"); } pQFilter.WhereClause = strFlgFldNam + " = 'LH'"; intCnt = pTable.RowCount(pQFilter); pCursor = pTable.Search(pQFilter, true); pDataStat = new DataStatisticsClass(); pDataStat.Field = lvFields.Items[1].SubItems[1].Text; pDataStat.Cursor = pCursor; pStatResults = pDataStat.Statistics; adblMinMaxForLabel[0, 3] = pStatResults.Minimum; adblMinMaxForLabel[1, 3] = pStatResults.Maximum; pCursor.Flush(); pSymbol = new SimpleMarkerSymbolClass(); pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; pSymbol.Color = m_pSnippet.getRGB(173, 255, 179); pUniqueValueRenderer.AddValue("LH", null, (ISymbol)pSymbol); if (intCnt == 1) { pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + ")"); } else if (intCnt == 0) { pUniqueValueRenderer.set_Label("LH", "LH (no obs)"); } else { pUniqueValueRenderer.set_Label("LH", "LH (" + adblMinMaxForLabel[0, 3].ToString("N1") + "-" + adblMinMaxForLabel[1, 3].ToString("N1") + ")"); } pSymbol = new SimpleMarkerSymbolClass(); pSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle; pSymbol.Color = m_pSnippet.getRGB(200, 200, 200); //pUniqueValueRenderer.AddValue("", strFlgFldNam, (ISymbol)pSymbol); //pUniqueValueRenderer.set_Label("", "Not significant"); pUniqueValueRenderer.DefaultSymbol = (ISymbol)pSymbol; pUniqueValueRenderer.DefaultLabel = "Not significant"; pUniqueValueRenderer.UseDefaultSymbol = true; } IFeatureLayer pNewFLayer = new FeatureLayerClass(); pNewFLayer.FeatureClass = m_pFClass; pNewFLayer.Name = cboSAM.Text + " of " + m_pFLayer.Name; IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer; pGFLayer.Renderer = (IFeatureRenderer)pUniqueValueRenderer; m_pActiveView.FocusMap.AddLayer(pGFLayer); m_pActiveView.Refresh(); m_pForm.axTOCControl1.Update(); } else { MessageBox.Show("Complete. The results are stored in the shape file"); } #endregion } else if (cboSAM.Text == "Gi*") { #region Gi* m_pEngine.Evaluate("sample.lg <- localG(" + strVarNM + ", sample.listw, zero.policy=TRUE)"); m_pEngine.Evaluate("sample.p <- 2*pnorm(-abs(sample.lg))"); if (cboAdjustment.Text == "Bonferroni correction") { m_pEngine.Evaluate("sample.p <- p.adjust(sample.p, method = 'bonferroni', n = length(sample.p))"); } double[] dblGValues = m_pEngine.Evaluate("sample.lg").AsNumeric().ToArray(); double[] dblPvalues = m_pEngine.Evaluate("sample.p").AsNumeric().ToArray(); //Save Output on SHP //Add Target fields to store results in the shapefile for (int j = 0; j < 2; j++) { IField newField = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)newField; fieldEdit.Name_2 = lvFields.Items[j].SubItems[1].Text; fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; m_pFClass.AddField(newField); } //Update Field pFCursor = m_pFClass.Update(null, false); pFeature = pFCursor.NextFeature(); int intStatFldIdx = m_pFClass.FindField(lvFields.Items[0].SubItems[1].Text); int intPrFldIdx = m_pFClass.FindField(lvFields.Items[1].SubItems[1].Text); int featureIdx = 0; while (pFeature != null) { pFeature.set_Value(intStatFldIdx, dblGValues[featureIdx]); pFeature.set_Value(intPrFldIdx, dblPvalues[featureIdx]); pFCursor.UpdateFeature(pFeature); pFeature = pFCursor.NextFeature(); featureIdx++; } pFCursor.Flush(); pfrmProgress.Close(); if (chkMap.Checked) { string strStaticFldName = lvFields.Items[0].SubItems[1].Text; m_pEngine.Evaluate("p.vals <- c(0.1, 0.05, 0.01)"); if (cboAdjustment.Text == "Bonferroni correction") { m_pEngine.Evaluate("sample.n <- length(sample.p)"); m_pEngine.Evaluate("p.vals <- p.vals/sample.n"); } m_pEngine.Evaluate("zc <- qnorm(1 - (p.vals/2))"); double[] dblZBrks = m_pEngine.Evaluate("sort(cbind(zc, -zc))").AsNumeric().ToArray(); pFCursor = m_pFClass.Search(null, false); IDataStatistics pDataStat = new DataStatisticsClass(); pDataStat.Field = strStaticFldName; pDataStat.Cursor = (ICursor)pFCursor; IStatisticsResults pStatResults = pDataStat.Statistics; double dblMax = pStatResults.Maximum; double dblMin = pStatResults.Minimum; int intBreaksCount = dblZBrks.Length + 2; double[] cb = new double[intBreaksCount]; //Assign Min and Max values for class breaks if (dblMin < dblZBrks[0]) { cb[0] = dblMin; } else { cb[0] = dblZBrks[0] - 1; //Manually Assigned minimum value } if (dblMax > dblZBrks[dblZBrks.Length - 1]) { cb[intBreaksCount - 1] = dblMax; } else { cb[intBreaksCount - 1] = dblZBrks[dblZBrks.Length - 1] + 1;//Manually Assigned minimum value } for (int k = 0; k < intBreaksCount - 2; k++) { cb[k + 1] = dblZBrks[k]; } IClassBreaksRenderer pCBRenderer = new ClassBreaksRenderer(); pCBRenderer.Field = strStaticFldName; pCBRenderer.BreakCount = intBreaksCount - 1; pCBRenderer.MinimumBreak = cb[0]; //' use this interface to set dialog properties IClassBreaksUIProperties pUIProperties = (IClassBreaksUIProperties)pCBRenderer; pUIProperties.ColorRamp = "Custom"; if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { ISimpleFillSymbol pSimpleFillSym; int[,] arrColors = CreateColorRamp(); //Add Probability Value Manually string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" }; //' be careful, indices are different for the diff lists for (int j = 0; j < intBreaksCount - 1; j++) { pCBRenderer.Break[j] = cb[j + 1]; if (j == 0) { pCBRenderer.Label[j] = " <= " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j]; } else if (j == intBreaksCount - 2) { pCBRenderer.Label[j] = " > " + Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1]; } else { pCBRenderer.Label[j] = Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1] + " ~ " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j]; } pUIProperties.LowBreak[j] = cb[j]; pSimpleFillSym = new SimpleFillSymbolClass(); IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]); pSimpleFillSym.Color = (IColor)pRGBColor; pCBRenderer.Symbol[j] = (ISymbol)pSimpleFillSym; } } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { ISimpleMarkerSymbol pSimpleMarkerSym; int[,] arrColors = CreateColorRamp(); //Add Probability Value Manually string[] strsProbLabels = new string[] { "(0.01)", "(0.05)", "(0.1)", "(0.1)", "(0.05)", "(0.01)" }; //' be careful, indices are different for the diff lists for (int j = 0; j < intBreaksCount - 1; j++) { pCBRenderer.Break[j] = cb[j + 1]; if (j == 0) { pCBRenderer.Label[j] = " <= " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j]; } else if (j == intBreaksCount - 2) { pCBRenderer.Label[j] = " > " + Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1]; } else { pCBRenderer.Label[j] = Math.Round(cb[j], 2).ToString() + strsProbLabels[j - 1] + " ~ " + Math.Round(cb[j + 1], 2).ToString() + strsProbLabels[j]; } pUIProperties.LowBreak[j] = cb[j]; pSimpleMarkerSym = new SimpleMarkerSymbolClass(); IRgbColor pRGBColor = m_pSnippet.getRGB(arrColors[j, 0], arrColors[j, 1], arrColors[j, 2]); pSimpleMarkerSym.Color = (IColor)pRGBColor; pCBRenderer.Symbol[j] = (ISymbol)pSimpleMarkerSym; } } IFeatureLayer pNewFLayer = new FeatureLayerClass(); pNewFLayer.FeatureClass = m_pFClass; pNewFLayer.Name = cboSAM.Text + " of " + m_pFLayer.Name; IGeoFeatureLayer pGFLayer = (IGeoFeatureLayer)pNewFLayer; pGFLayer.Renderer = (IFeatureRenderer)pCBRenderer; m_pActiveView.FocusMap.AddLayer(pGFLayer); m_pActiveView.Refresh(); m_pForm.axTOCControl1.Update(); } else { MessageBox.Show("Complete. The results are stored in the shape file"); } #endregion } this.Close(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }
private void btnRun_Click(object sender, EventArgs e) { try { if (cboFieldName.Text == "") { MessageBox.Show("Please select target field"); return; } frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee; pfrmProgress.Show(); //Close Results form, if it is opend. CloseOpendResultForm(m_pHandle); IGraphicsContainer pGraphicContainer = m_pActiveView.GraphicsContainer; pGraphicContainer.DeleteAllElements(); // Creates the input and output matrices from the shapefile// string strLayerName = cboTargetLayer.Text; int intLIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strLayerName); ILayer pLayer = m_pForm.axMapControl1.get_Layer(intLIndex); IFeatureLayer pFLayer = pLayer as IFeatureLayer; //IFeatureClass pFClass = pFLayer.FeatureClass; m_intNFeature = m_pFClass.FeatureCount(null); IFeatureCursor pFCursor = m_pFClass.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Get index for independent and dependent variables //Get variable index string strVarNM = (string)cboFieldName.SelectedItem; int intVarIdx = m_pFClass.FindField(strVarNM); //Store Variable at Array double[] arrVar = new double[m_intNFeature]; m_arrXYCoord = new double[m_intNFeature, 2]; int i = 0; IArea pArea; IPoint pPoint; while (pFeature != null) { if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { pArea = (IArea)pFeature.Shape; m_arrXYCoord[i, 0] = pArea.Centroid.X; m_arrXYCoord[i, 1] = pArea.Centroid.Y; } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { pPoint = (IPoint)pFeature.Shape; m_arrXYCoord[i, 0] = pPoint.X; m_arrXYCoord[i, 1] = pPoint.Y; } arrVar[i] = Convert.ToDouble(pFeature.get_Value(intVarIdx)); i++; pFeature = pFCursor.NextFeature(); } if (!m_blnCreateSWM) { //Get the file path and name to create spatial weight matrix string strNameR = m_pSnippet.FilePathinRfromLayer(pFLayer); if (strNameR == null) { return; } //Create spatial weight matrix in R if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) { m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); } else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) { m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); } else { MessageBox.Show("This geometry type is not supported"); pfrmProgress.Close(); this.Close(); } int intSuccess = m_pSnippet.CreateSpatialWeightMatrix(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress); if (intSuccess == 0) { return; } } ////Get the file path and name to create spatial weight matrix //string strNameR = m_pSnippet.FilePathinRfromLayer(pFLayer); //if (strNameR == null) // return; //int intSuccess = 0; ////Create spatial weight matrix in R //if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPolygon) //{ // m_pEngine.Evaluate("sample.shp <- readShapePoly('" + strNameR + "')"); // intSuccess = m_pSnippet.CreateSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked); //} //else if (m_pFClass.ShapeType == esriGeometryType.esriGeometryPoint) //{ // m_pEngine.Evaluate("sample.shp <- readShapePoints('" + strNameR + "')"); // //intSuccess = m_pSnippet.ExploreSpatialWeightMatrix1(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked); // intSuccess = m_pSnippet.CreateSpatialWeightMatrixPts(m_pEngine, m_pFClass, txtSWM.Text, pfrmProgress, Convert.ToDouble(nudAdvanced.Value), chkCumulate.Checked, m_pClippedPolygon); // //chkCumulate.Visible = false; //} //else //{ // MessageBox.Show("This geometry type is not supported"); // pfrmProgress.Close(); // this.Close(); //} //if (intSuccess == 0) // return; //Creat Higher spatial lag int intMaxLag = Convert.ToInt32(nudLagOrder.Value); try { m_pEngine.Evaluate("sample.nblags <- nblag(sample.nb, maxlag = " + intMaxLag.ToString() + ")"); } catch { MessageBox.Show("Please reduce the maximum lag order"); } m_arrResults = new double[intMaxLag][]; m_arrMaxToLinks = new double[intMaxLag][]; m_arrMaxFromLinks = new double[intMaxLag]; pChart.Series.Clear(); //Plot command for R StringBuilder plotCommmand = new StringBuilder(); NumericVector vecVar = m_pEngine.CreateNumericVector(arrVar); m_pEngine.SetSymbol(strVarNM, vecVar); bool blnZeroPolicy = false; //Store Information of spatial lag for (int j = 0; j < intMaxLag; j++) { m_arrResults[j] = new double[5]; m_pEngine.Evaluate("card.sample <- card(sample.nblags[[" + (j + 1).ToString() + "]])"); m_arrResults[j][0] = m_pEngine.Evaluate("sum(card.sample)").AsNumeric().First(); //If ther is no link, return if (m_arrResults[j][0] == 0) { MessageBox.Show("There is no link at " + (j + 1).ToString() + " order."); return; } //Functions below are used for brushing on map control, they are under reviewing 080316 HK //m_arrMaxFromLinks[j] = m_pEngine.Evaluate("which.max(card.sample)").AsNumeric().First(); //m_arrMaxToLinks[j] = m_pEngine.Evaluate("sample.nblags[[" + (j + 1).ToString() + "]][[which.max(card.sample)]]").AsNumeric().ToArray(); //Select method if (cboSAM.Text == "Moran Coefficient") { try { m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W')"); } catch { DialogResult dialogResult = new DialogResult(); if (blnZeroPolicy == false) { dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo); } if (dialogResult == DialogResult.Yes || blnZeroPolicy == true) { m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W', zero.policy=TRUE)"); blnZeroPolicy = true; } else if (dialogResult == DialogResult.No) { pfrmProgress.Close(); return; } } plotCommmand.Append("sam.result <- moran.test(" + strVarNM + ", sample.listw, "); //select assumption if (cboAssumption.Text == "Normality") { plotCommmand.Append("randomisation=FALSE, alternative ='two.sided', zero.policy=TRUE)"); } else if (cboAssumption.Text == "Randomization") { plotCommmand.Append("randomisation=TRUE, alternative ='two.sided', zero.policy=TRUE)"); } } else if (cboSAM.Text == "Geary Ratio") { try { m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W')"); } catch { DialogResult dialogResult = new DialogResult(); if (blnZeroPolicy == false) { dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo); } if (dialogResult == DialogResult.Yes || blnZeroPolicy == true) { m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W', zero.policy=TRUE)"); blnZeroPolicy = true; } else if (dialogResult == DialogResult.No) { pfrmProgress.Close(); return; } } plotCommmand.Append("sam.result <- geary.test(" + strVarNM + ", sample.listw, "); //select assumption if (cboAssumption.Text == "Normality") { plotCommmand.Append("randomisation=FALSE, alternative ='two.sided', zero.policy=TRUE)"); } else if (cboAssumption.Text == "Randomization") { plotCommmand.Append("randomisation=TRUE, alternative ='two.sided', zero.policy=TRUE)"); } } else if (cboSAM.Text == "Global G Statistic") { try { m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='W')"); } catch { DialogResult dialogResult = new DialogResult(); if (blnZeroPolicy == false) { dialogResult = MessageBox.Show("Empty neighbor sets are founded. Do you want to continue?", "Empty neighbor", MessageBoxButtons.YesNo); } if (dialogResult == DialogResult.Yes || blnZeroPolicy == true) { m_pEngine.Evaluate("sample.listw <- nb2listw(sample.nblags[[" + (j + 1).ToString() + "]], style='B', zero.policy=TRUE)"); blnZeroPolicy = true; } else if (dialogResult == DialogResult.No) { pfrmProgress.Close(); return; } } plotCommmand.Append("sam.result <- globalG.test(" + strVarNM + ", sample.listw, alternative ='two.sided', zero.policy=TRUE)"); } m_pEngine.Evaluate(plotCommmand.ToString()); plotCommmand.Clear(); NumericVector vecResults = m_pEngine.Evaluate("sam.result$estimate").AsNumeric(); m_arrResults[j][1] = vecResults[0]; m_arrResults[j][2] = vecResults[1]; m_arrResults[j][3] = vecResults[2]; m_arrResults[j][4] = m_pEngine.Evaluate("sam.result$p.value").AsNumeric().First(); double dblXmin = (j + 1) - 0.2; double dblXmax = (j + 1) + 0.2; double dblYmax = vecResults[0] + (Math.Sqrt(vecResults[2]) * 1.96); double dblYmin = vecResults[0] - (Math.Sqrt(vecResults[2]) * 1.96); AddLineSeries(pChart, "min_" + j.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, dblYmin, dblYmin); AddLineSeries(pChart, "max_" + j.ToString(), Color.Black, 1, ChartDashStyle.Solid, dblXmin, dblXmax, dblYmax, dblYmax); AddLineSeries(pChart, "rg_" + j.ToString(), Color.Black, 1, ChartDashStyle.Solid, (j + 1), (j + 1), dblYmin, dblYmax); } //pEngine.Evaluate("sample.nb <- poly2nb(sample.shp);sample.listw <- nb2listw(sample.nb, style='W')"); double dblExp = m_arrResults[0][2]; AddLineSeries(pChart, "ex", Color.Red, 1, ChartDashStyle.Dash, 0.5, intMaxLag + 0.5, dblExp, dblExp); var pSeries = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "Point", Color = Color.Black, IsXValueIndexed = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = MarkerStyle.Circle, }; pChart.Series.Add(pSeries); for (int j = 0; j < intMaxLag; j++) { pSeries.Points.AddXY((j + 1), m_arrResults[j][1]); } m_intTotalNSeries = pChart.Series.Count; //Chart Design pChart.ChartAreas[0].AxisX.Title = "Spatial Lag"; pChart.ChartAreas[0].AxisY.Title = cboSAM.Text; pChart.ChartAreas[0].AxisY.IsStartedFromZero = false; pChart.ChartAreas[0].AxisX.Maximum = intMaxLag + 0.5; pChart.ChartAreas[0].AxisX.Minimum = 0.5; pChart.ChartAreas[0].AxisX.MajorTickMark.Enabled = false; //need to be updated 042816 HK pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false; for (int j = 0; j < intMaxLag; j++) { int intXvalue = j + 1; double dblXmin = Convert.ToDouble(intXvalue) - 0.5; double dblXmax = Convert.ToDouble(intXvalue) + 0.5; CustomLabel pcutsomLabel = new CustomLabel(); pcutsomLabel.FromPosition = dblXmin; pcutsomLabel.ToPosition = dblXmax; pcutsomLabel.Text = intXvalue.ToString(); pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel); } pfrmProgress.Close(); } catch (Exception ex) { frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog(); return; } }