/// <summary> /// 根据图层的列表计算土地利用变化历史趋势。 /// </summary> /// <param name="listLayers"></param> private void CalculateHistoryTrends(List <string> listLayers) { //写入列。列名为图层名。 DataTable dtResults = new DataTable(); for (int i = 0; i < listLayers.Count; i++) { dtResults.Columns.Add(listLayers[i]); } //写入行。除了所有的土地利用类型的栅格数量,还有数量总计,土地开发强度,城市用地增长率。 for (int i = 0; i < landUseTypesCount + 3; i++) { DataRow row = dtResults.NewRow(); dtResults.Rows.Add(row); } //计算并写入数据 int urbanIndex = GetUrbanIndex(); int urbanCount = 0; IRasterLayer rasterLayer; IRasterUniqueValueRenderer rasterUniqueValueRenderer; for (int i = 0; i < listLayers.Count; i++) { rasterLayer = ArcGISOperator.GetRasterLayerByName(listAllLayersInMapName[i]); rasterUniqueValueRenderer = (IRasterUniqueValueRenderer)rasterLayer.Renderer; int[] counts = ArcGISOperator.GetLandUseTypesCount(rasterLayer); int sum = 0; for (int j = 0; j < landUseTypesCount; j++) { dtResults.Rows[j][i] = counts[j]; sum += counts[j]; if (urbanIndex == j) { urbanCount = counts[j]; } } dtResults.Rows[landUseTypesCount][i] = sum; dtResults.Rows[landUseTypesCount + 1][i] = (Convert.ToDecimal(urbanCount) * 100 / sum).ToString("0.00"); if (i != 0) { int oldUrbanCount = Convert.ToInt32(dtResults.Rows[urbanIndex][i - 1]); int newUrbanCount = Convert.ToInt32(dtResults.Rows[urbanIndex][i]); dtResults.Rows[landUseTypesCount + 2][i] = (Convert.ToDecimal(newUrbanCount - oldUrbanCount) * 100 / oldUrbanCount).ToString("0.00"); } } dataGridViewResult.DataSource = dtResults; //设置行名 rasterLayer = ArcGISOperator.GetRasterLayerByName(listAllLayersInMapName[0]); rasterUniqueValueRenderer = (IRasterUniqueValueRenderer)rasterLayer.Renderer; for (int i = 0; i < landUseTypesCount; i++) { dataGridViewResult.RowHeadersWidth = 130; dataGridViewResult.Rows[i].HeaderCell.Value = rasterUniqueValueRenderer.get_Label(0, i); } dataGridViewResult.Rows[landUseTypesCount].HeaderCell.Value = resourceManager.GetString("String150"); dataGridViewResult.Rows[landUseTypesCount + 1].HeaderCell.Value = resourceManager.GetString("String151"); dataGridViewResult.Rows[landUseTypesCount + 2].HeaderCell.Value = resourceManager.GetString("String152"); }
private void buttonCalConvertCells_Click(object sender, EventArgs e) { if (SimulationEndImageName != "") { IRasterLayer rasterLayer = ArcGISOperator.GetRasterLayerByName(simulationStartImageName); int startUrbanConuts = ArcGISOperator.GetUrbanCount(rasterLayer, landUseClassificationInfo); rasterLayer = ArcGISOperator.GetRasterLayerByName(simulationEndImageName); int endUrbanCounts = ArcGISOperator.GetUrbanCount(rasterLayer, landUseClassificationInfo); numericUpDownConvertCount.Value = Convert.ToDecimal(endUrbanCounts - startUrbanConuts); } }
void t_Tick(object sender, EventArgs e) { try { if (VariableMaintainer.IsNeedRefresh) { string simulationLayerName = VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name; IRasterLayer simulationImageLayer = new RasterLayerClass(); if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_LogisticRegression) { simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder + @"\" + simulationLayerName); ArcGISOperator.WriteRaster(simulationImageLayer, VariableMaintainer.CurrentFormLogisticCAWizard.SimulationImage); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_ANN) { simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormANNCAWizard.OutputFolder + @"\" + simulationLayerName); ArcGISOperator.WriteRaster(simulationImageLayer, VariableMaintainer.CurrentFormANNCAWizard.SimulationImage); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_DT) { simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormDTCAWizard.OutputFolder + @"\" + simulationLayerName); ArcGISOperator.WriteRaster(simulationImageLayer, VariableMaintainer.CurrentFormDTCAWizard.SimulationImage); } IRasterLayer l = ArcGISOperator.GetRasterLayerByName(simulationLayerName); IRaster2 raster = simulationImageLayer.Raster as IRaster2; IPnt fromPnt = new PntClass(); fromPnt.SetCoords(0, 0); IPnt blockSize = new PntClass(); blockSize.SetCoords(simulationImageLayer.ColumnCount, simulationImageLayer.RowCount); IPixelBlock pixelBlock = ((IRaster)raster).CreatePixelBlock(blockSize); l.Raster.Read(fromPnt, pixelBlock); ((IRasterEdit)l.Raster).Refresh(); IActiveView activeView = VariableMaintainer.CurrentFoucsMap as IActiveView; activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); VariableMaintainer.IsNeedRefresh = false; } if (VariableMaintainer.IsSimulationFinished) { VariableMaintainer.CurrentTimer.Stop(); VariableMaintainer.IsSimulationFinished = false; } } catch (Exception ex) { //MessageBox.Show(ex.Message); } }
/// <summary> /// 读取并填充土地利用类型信息。 /// </summary> private void FillLanduseInfo(string layerName) { dataGridViewLandUse.Rows.Clear(); //根据第一个图层的符号化设置读取土地利用类型信息。 //注意:因为一般来说符号化设置的设置和属性表一致,因为不需要考虑顺序不一致的问题。 IRasterLayer rasterLayer = ArcGISOperator.GetRasterLayerByName(layerName); IRasterUniqueValueRenderer rasterUniqueValueRenderer = (IRasterUniqueValueRenderer)rasterLayer.Renderer; IRasterRendererUniqueValues rasterRendererUniqueValues = (IRasterRendererUniqueValues)rasterUniqueValueRenderer; IUniqueValues uniqueValues = rasterRendererUniqueValues.UniqueValues; List <object> listUniqueValues = new List <object>(); for (int i = 0; i < uniqueValues.Count; i++) { listUniqueValues.Add(uniqueValues.get_UniqueValue(i)); } int classCount = rasterUniqueValueRenderer.get_ClassCount(0); for (int i = 0; i < classCount; i++) { dataGridViewLandUse.Rows.Add(); dataGridViewLandUse.Rows[i].Cells[0].Value = rasterUniqueValueRenderer.get_Label(0, i); } }
protected override void OnClick() { try { ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager; if (VariableMaintainer.CurrentModel == EnumCurrentModel.Null) { MessageBox.Show(resourceManager.GetString("String168"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } Thread thread = VariableMaintainer.SimulationThread; if (thread != null) { if (thread.ThreadState != ThreadState.Stopped) { MessageBox.Show(resourceManager.GetString("String39"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } StructRasterMetaData structRasterMetaData = new StructRasterMetaData(); string model = ""; if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_LogisticRegression) { model = resourceManager.GetString("String104"); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_ANN) { model = resourceManager.GetString("String102"); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_DT) { model = resourceManager.GetString("String103"); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Optimization_Area) { model = resourceManager.GetString("String167"); } VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String82") + model + resourceManager.GetString("String101") + DateTime.Now.ToShortTimeString()); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String58")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String58")); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_LogisticRegression) { //ArcGIS操作在另一线程中执行效率降低很多,因此把数据读取及刷新操作在线程外执行 //首先读取模拟起始时刻和/或终止时刻影像 ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String12")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String12") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName + ".....\n"); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImage = ArcGISOperator.ReadRasterAndGetMetaData(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName), out structRasterMetaData); if (VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName != "") { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String13")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String13") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName + ".....\n"); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName), -9999f); } //然后读取各变量影像 if (VariableMaintainer.CurrentFormLogisticCAWizard.IsUsingDefault) { foreach (string layerName in VariableMaintainer.CurrentFormLogisticCAWizard.ListVariableLayersName) { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String14") + layerName + "....."); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String14") + layerName + ".....\n"); VariableMaintainer.CurrentFormLogisticCAWizard.VaribaleImages.Add( ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName(layerName), -9999f)); } //获取最小空间范围 IRasterLayer rasterLayerStartImage = ArcGISOperator.GetRasterLayerByName(VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName); IRasterLayer rasterLayerEndImage = ArcGISOperator.GetRasterLayerByName(VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName); List <IRasterLayer> listVariablesLayers = new List <IRasterLayer>(); for (int i = 0; i < VariableMaintainer.CurrentFormLogisticCAWizard.ListVariableLayersName.Count; i++) { listVariablesLayers.Add(ArcGISOperator.GetRasterLayerByName(VariableMaintainer.CurrentFormLogisticCAWizard.ListVariableLayersName[i])); } ArcGISOperator.GetSmallestBound(rasterLayerStartImage, rasterLayerEndImage, listVariablesLayers, ref structRasterMetaData); VariableMaintainer.CurrentFormLogisticCAWizard.CurrentStructRasterMetaData = structRasterMetaData; } //最后用模拟起始时刻影像创建模拟影像 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "sim" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String37")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String37") + rasterName + ".....\n"); IRasterLayer simulationStartImageLayer = ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormLogisticCAWizard.SimulationStartImageName); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)simulationStartImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder + @"\" + rasterName); simulationImageLayer.Renderer = simulationStartImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)simulationImageLayer); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationImage = ArcGISOperator.ReadRaster(simulationImageLayer, -9999f); VariableMaintainer.CurrentFormLogisticCAWizard.SimulationLayerName = rasterName; LogisticRegreesionCA lrCA = new LogisticRegreesionCA(); lrCA.DockableWindowGraphy = VariableMaintainer.CurrentDockableWindowGraphy; lrCA.DockableWindowOutput = VariableMaintainer.CurrentDockableWindowOutput; thread = new Thread(new ThreadStart(lrCA.DoSimulation)); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_ANN) { //今后应使用父类和接口进行重构 //首先读取模拟起始时刻和/或终止时刻影像 ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String12")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String12") + VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImageName + ".....\n"); VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImage = ArcGISOperator.ReadRasterAndGetMetaData(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImageName), out structRasterMetaData); //VariableMaintainer.CurrentANNCAWizard.CurrentStructRasterMetaData = structRasterMetaData; if (VariableMaintainer.CurrentFormANNCAWizard.SimulationEndImageName != "") { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String13")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String13") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName + ".....\n"); VariableMaintainer.CurrentFormANNCAWizard.SimulationEndImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormANNCAWizard.SimulationEndImageName), -9999f); } //最后用模拟起始时刻影像创建模拟影像 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "sim" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String37")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String37") + rasterName + ".....\n"); IRasterLayer simulationStartImageLayer = ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormANNCAWizard.SimulationStartImageName); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.CurrentFormANNCAWizard.OutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)simulationStartImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormANNCAWizard.OutputFolder + @"\" + rasterName); simulationImageLayer.Renderer = simulationStartImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)simulationImageLayer); VariableMaintainer.CurrentFormANNCAWizard.SimulationImage = ArcGISOperator.ReadRaster(simulationImageLayer, -9999f); VariableMaintainer.CurrentFormANNCAWizard.SimulationLayerName = rasterName; ANNCA annCA = new ANNCA(); annCA.DockableWindowGraphy = VariableMaintainer.CurrentDockableWindowGraphy; annCA.DockableWindowOutput = VariableMaintainer.CurrentDockableWindowOutput; thread = new Thread(new ThreadStart(annCA.DoSimulation)); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Simulation_CA_DT) { //今后应使用父类和接口进行重构 //首先读取模拟起始时刻和/或终止时刻影像 ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String12")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String12") + VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImageName + ".....\n"); VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImage = ArcGISOperator.ReadRasterAndGetMetaData(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImageName), out structRasterMetaData); //VariableMaintainer.CurrentDTCAWizard.CurrentStructRasterMetaData = structRasterMetaData; if (VariableMaintainer.CurrentFormDTCAWizard.SimulationEndImageName != "") { ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String13")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String13") + VariableMaintainer.CurrentFormLogisticCAWizard.SimulationEndImageName + ".....\n"); VariableMaintainer.CurrentFormDTCAWizard.SimulationEndImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormDTCAWizard.SimulationEndImageName), -9999f); } //20170619添加限制层数据 //VariableMaintainer.CurrentDockableWindowOutput.AppendText("Add Restriction Layer " + // "ACOres" + ".....\n"); //VariableMaintainer.RestrictImage = ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName( // "ACOres"), -9999f); //最后用模拟起始时刻影像创建模拟影像 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "sim" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, resourceManager.GetString("String37")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(resourceManager.GetString("String37") + rasterName + ".....\n"); IRasterLayer simulationStartImageLayer = ArcGISOperator.GetRasterLayerByName( VariableMaintainer.CurrentFormDTCAWizard.SimulationStartImageName); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.CurrentFormDTCAWizard.OutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)simulationStartImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.CurrentFormDTCAWizard.OutputFolder + @"\" + rasterName); simulationImageLayer.Renderer = simulationStartImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)simulationImageLayer); VariableMaintainer.CurrentFormDTCAWizard.SimulationImage = ArcGISOperator.ReadRaster(simulationImageLayer, -9999f); VariableMaintainer.CurrentFormDTCAWizard.SimulationLayerName = rasterName; DecisionTreeCA dtCA = new DecisionTreeCA(); dtCA.DockableWindowGraphy = VariableMaintainer.CurrentDockableWindowGraphy; dtCA.DockableWindowOutput = VariableMaintainer.CurrentDockableWindowOutput; thread = new Thread(new ThreadStart(dtCA.DoSimulation)); } else if (VariableMaintainer.CurrentModel == EnumCurrentModel.Optimization_Area) { if (!VariableMaintainer.IsACOUtilitySet || !VariableMaintainer.IsACOParametersSet) { MessageBox.Show(resourceManager.GetString("String166"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } AreaOptimizationACO areaOptimizationACO = new AreaOptimizationACO(); areaOptimizationACO.Initialize(VariableMaintainer.CurrentStructACOParameters, 1, false, VariableMaintainer.CurrentDockableWindowOutput, VariableMaintainer.CurrentDockableWindowGraphy, true); thread = new Thread(new ThreadStart(areaOptimizationACO.Run)); } else { MessageBox.Show(resourceManager.GetString("String168"), resourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } VariableMaintainer.SimulationThread = thread; thread.SetApartmentState(ApartmentState.STA); thread.Start(); VariableMaintainer.CurrentTimer.Interval = 500; VariableMaintainer.CurrentTimer.Tick += new EventHandler(t_Tick); VariableMaintainer.CurrentTimer.Enabled = true; VariableMaintainer.CurrentTimer.Start(); ArcMap.Application.CurrentTool = null; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 更新信息素,同时更新最优状态 /// </summary> /// <param name="Ants"></param> private void UpdatePheromoneData(Ant[] Ants) { for (int i = 0; i < structRasterMetaData.RowCount; i++) { for (int j = 0; j < structRasterMetaData.ColumnCount; j++) { if (suitabilityData[i, j] != structRasterMetaData.NoDataValue) { //计算剩下的信息素 pheromoneData[i, j] = (float)(pheromoneData[i, j] * (1 - rho)); if (goalUtilityInMicroSearch > goalUtilityInAllIterations) { goalUtilityAntsStatusInAllIterations[i, j] = 0; } } } } double onePheromon = q * goalUtilityInMicroSearch; int conNN = 5; if (currentIteration > 200 && currentIteration <= 700) { conNN = 5; /*Beita=3;*/ } if (currentIteration > 700) { conNN = 3; /*Beita=3;*/ } for (int i = 0; i < Ants.Length; i++) { int x = Ants[i].X; int y = Ants[i].Y; //-------------计算增加的信息素----------------------------------------------- pheromoneData[x, y] += (float)onePheromon; //更新信息素 UpdateNeighbour(pheromoneData, conNN, onePheromon, structRasterMetaData.ColumnCount, structRasterMetaData.RowCount, y, x); //更新邻域信息素; //------------------------------------------------------------------------- //判断是否需要更新最优状态 if (goalUtilityInMicroSearch > goalUtilityInAllIterations) { goalUtilityAntsStatusInAllIterations[x, y] = 1; } } if (goalUtilityInMicroSearch > goalUtilityInAllIterations) { goalUtilityInAllIterations = goalUtilityInMicroSearch; isNeedUpdate = true; needFinishIterationCount = 1; currentRefreshIteration += 1; } else { needFinishIterationCount += 1; } currentIteration += 1; dockableWindowOutput.AppendText("CurrentInteration=" + currentIteration + " CurrentRefreshIteration=" + currentRefreshIteration + " NeedUpdate=" + isNeedUpdate + " NeedFinishIterationCount=" + needFinishIterationCount + " GoalUtilityValueInAllIterations=" + goalUtilityInAllIterations + "\r\n"); dockableWindowOutput.AppendText(("\n")); dockableWindowOutput.ScrollTextbox(); if (currentIteration == 1) { dockableWindowGraphy.CreateGraph(currentIteration, goalUtilityInAllIterations, ""); dockableWindowGraphy.RefreshGraph(); } else { dockableWindowGraphy.UpdateData(currentIteration, goalUtilityInAllIterations, 0); dockableWindowGraphy.RefreshGraph(); } float[,] currentOccpied = new float[structRasterMetaData.RowCount, structRasterMetaData.ColumnCount]; for (int i = 0; i < structRasterMetaData.RowCount; i++) { for (int j = 0; j < structRasterMetaData.ColumnCount; j++) { if (suitabilityData[i, j] == -9999f) { currentOccpied[i, j] = 255; } else { if (occupiedStatus[i, j] == 1) { currentOccpied[i, j] = Convert.ToSingle(occupiedStatus[i, j]); } else { currentOccpied[i, j] = 0; } } } } int mapRefreshInterval = VariableMaintainer.CurrentStructACOParameters.MapRefreshInterval; if (mapRefreshInterval == 0) { mapRefreshInterval = 5; } if (currentIteration % mapRefreshInterval == 0) { string simulationLayerName = VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name; IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.DefaultOutputFolder + @"\" + simulationLayerName); ArcGISOperator.WriteRaster(simulationImageLayer, currentOccpied); IRasterLayer l = ArcGISOperator.GetRasterLayerByName(simulationLayerName); ((IRasterEdit)l.Raster).Refresh(); IActiveView activeView = VariableMaintainer.CurrentFoucsMap as IActiveView; activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); } //保存每次迭代的目标值,如果需要保存 if (isNeedSave == true) { goalUtilityArray[currentIteration + 1] = currentIteration + "," + currentRefreshIteration + "," + isNeedUpdate + "," + needFinishIterationCount + "," + goalUtilityInAllIterations; if (currentIteration == totalItearationCount) { string outResult = outputPath + outGoalName; //CommonOperator.writeGoalData(outResult, goalSave); } } //判断是否需要把结果保存成文件 if (isNeedSave == true && needFinishIterationCount == 1) { outFileName = outPreFileName + currentRefreshIteration + "_s" + currentIteration + ".txt"; String outResult = outputPath + outFileName; dockableWindowOutput.AppendText("Writing file:" + outResult + "\r\n"); dockableWindowOutput.ScrollTextbox(); //CommonOperator.WriteData(outResult, allOptStatus, rows, cols, xllcorner, yllcorner, cellsize, NODATA_value); dockableWindowOutput.AppendText("Writing file finished\r\n"); dockableWindowOutput.ScrollTextbox(); } }
//-------------------------------------------------------------------------------------------------------------- //------------------------------------------------方法---------------------------------------------------------- /// <summary> /// 方法 /// </summary> #region 方法 /// <summary> /// 初始化方法 /// </summary> #region ----------------初始化方法------------------------ public void Initialize(StructACOParameters structACOParameters, int microSearchIterationCountValue, Boolean isNeedSaveValue, DockableWindowOutput currentDockableWindowOutput, DockableWindowGraphy currentDockableWindowGraphy, Boolean isUseCompactnessValue) { q = structACOParameters.Q; //信息素强度 rho = structACOParameters.Rho; //挥发因子 alpha = structACOParameters.Alpha; //信息素权重 beta = structACOParameters.Beta; //启发函数权重 weightSutiable = structACOParameters.WeightSuitable; //阻抗性权重 weightCompact = structACOParameters.WeightCompact; //紧凑性权重 totalItearationCount = structACOParameters.InterationCount; //总迭代次数 currentIteration = 0; //当前迭代次数 currentRefreshIteration = 0; //更新次数 needFinishIterationCount = 0; microSearchIterationCount = microSearchIterationCountValue; //小搜索次数 goalUtilityAntsStatusInMicroSearch = new Ant[structACOParameters.AntCount]; //小搜索内最优状态 currentIterationInMicroSearch = 0; goalUtilityInMicroSearch = 0; isNeedSave = isNeedSaveValue; //判断是否需要保存结果 isNeedUpdate = false; //初始化判断是否需要更新最优状态 isInitialStatusSave = false; //判断是否已经保存初始状态数据 //rows = rrows; //网格行数 //cols = ccols; //网格列数 //xllcorner = xxllcorner; //输出文件左上角横坐标 //yllcorner = yyllcorner; //输出文件左上角纵坐标 //cellsize = ccellsize; //栅格大小 //noDataValue = nnodata_value; //无数据值 outputPath = structACOParameters.OutputFolder; //结果输出路径 outInitName = "_Init.txt"; //结果输出初始状态文件名 outFileName = ""; //结果输出文件名 outPreFileName = "g"; //结果输出文件名前面部分 outGoalName = "GoalFunction.txt"; //结果输出目标函数名 antsCount = structACOParameters.AntCount; //智能体个数 //cellSize = bbianChang; //网格边长 //cellArea = cellSize * cellSize * antsCount; //智能体面积 goalUtilityInAllIterations = 0; randomBound = 1; goalUtilityArray = new string[totalItearationCount + 2]; //保存目标函数值数据 suitabilityData = GetSuitabilityData(VariableMaintainer.OptimizationExpression); InitializeOccupiedAndGoalUtilityAntsStatusInAllIterations(); //初始化挖空 InitializeAnts(); //初始化智能体 InitializePheromone(); //初始化信息素 InitializeHeuristicFunction(); //初始化启发函数 string simulationLayerName = VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name; IRasterLayer simulationImageLayer = ArcGISOperator.GetRasterLayerByName(simulationLayerName); string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "ACOArea" + dateTime + ".img"; IRasterDataset rst = ArcGISOperator.CreateRasterDataset(VariableMaintainer.DefaultOutputFolder, rasterName, simulationImageLayer, structRasterMetaData, occupiedStatus, 0); IRasterLayer n = new RasterLayerClass(); n.CreateFromDataset(rst); IColorRamp colorRamp = new RandomColorRampClass(); ArcGISOperator.UniqueValueRenderer(colorRamp, n, "Value"); ArcGISOperator.FoucsMap.AddLayer((ILayer)n); double pixelWidth = ((IRasterDefaultProps)n.Raster).DefaultPixelWidth; double pixelHeight = ((IRasterDefaultProps)n.Raster).DefaultPixelHeight; cellArea = pixelWidth * pixelHeight * antsCount; cellSize = pixelWidth; random = new Random(); dockableWindowOutput = currentDockableWindowOutput; dockableWindowGraphy = currentDockableWindowGraphy; stringBuilderMessage = new StringBuilder(); isUseCompactness = isUseCompactnessValue; dockableWindowGraphy.GraphTitle = "Goal Utility"; dockableWindowGraphy.XAxisTitle = "Iteration"; dockableWindowGraphy.YAxisTitle = "Goal Utility Value"; }
public float[,] GetSuitabilityData(string expression) { string[] splitedExpressionArray; bool isSplited = SplitExpression(expression, out splitedExpressionArray); if (isSplited == false) { MessageBox.Show("Suitibility Function Express Error", VariableMaintainer.CurrentResourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } //根据获取的文件名字符串去读取相应的栅格文件 List <float[, ]> listLayers = new List <float[, ]>(); structRasterMetaData = new StructRasterMetaData(); for (int i = 0; i < splitedExpressionArray.Length; i++) { if (i > 0 && i % 2 > 0) { string layerName = splitedExpressionArray[i]; if (i == 1) { listLayers.Add(ArcGISOperator.ReadRasterAndGetMetaData( ArcGISOperator.GetRasterLayerByName(layerName), out structRasterMetaData)); } else { listLayers.Add(ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName(layerName), structRasterMetaData.NoDataValue)); } } } if (listLayers.Count == 0) { MessageBox.Show("Please select layers for calculation!", VariableMaintainer.CurrentResourceManager.GetString("String2"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(null); } //读取全部文件后进行计算,生成适宜性图层数据,并进行归一化 float[,] suitabilityData = new float[structRasterMetaData.RowCount, structRasterMetaData.ColumnCount]; float min = 1, max = 0; Expression ex = new Expression("1+1"); //MathParser mathParser = new MathParser(); for (int i = 0; i < structRasterMetaData.RowCount; i++) { for (int j = 0; j < structRasterMetaData.ColumnCount; j++) { bool isNullData = false; for (int k = 0; k < listLayers.Count; k++) { if (listLayers[k][i, j] == structRasterMetaData.NoDataValue) { isNullData = true; break; } } if (isNullData) { suitabilityData[i, j] = structRasterMetaData.NoDataValue; } else { string calculateExpression = ""; for (int w = 0; w < splitedExpressionArray.Length; w++) { if (w > 0 && w % 2 == 1) { calculateExpression += listLayers[w / 2][i, j]; } else { calculateExpression += splitedExpressionArray[w]; } } ex = new Expression(calculateExpression); suitabilityData[i, j] = Convert.ToSingle(ex.Evaluate()); //suitabilityData[i, j] = Convert.ToSingle(mathParser.Parse(calculateExpression, false)); if (suitabilityData[i, j] < min) { min = suitabilityData[i, j]; } if (suitabilityData[i, j] > max) { max = suitabilityData[i, j]; } } } } float[,] suitabilityData2 = new float[structRasterMetaData.RowCount, structRasterMetaData.ColumnCount]; for (int i = 0; i < structRasterMetaData.RowCount; i++) { for (int j = 0; j < structRasterMetaData.ColumnCount; j++) { if (suitabilityData[i, j] == structRasterMetaData.NoDataValue) { suitabilityData2[i, j] = structRasterMetaData.NoDataValue; } else { suitabilityData2[i, j] = (suitabilityData[i, j] - min) / (max - min); } } } //将其他图层关闭,以免影响蚁群优化的刷新效果 for (int i = 0; i < VariableMaintainer.CurrentFoucsMap.LayerCount; i++) { if (VariableMaintainer.CurrentFoucsMap.get_Layer(i).Visible) { VariableMaintainer.CurrentFoucsMap.get_Layer(i).Visible = false; } } //显示适宜性图层 string dateTime = GeneralOpertor.GetDataTimeFullString(DateTime.Now); string rasterName = "suitability" + dateTime + ".img"; ArcMap.Application.StatusBar.set_Message(0, VariableMaintainer.CurrentResourceManager.GetString("String169")); VariableMaintainer.CurrentDockableWindowOutput.AppendText(VariableMaintainer.CurrentResourceManager.GetString("String169") + rasterName + ".....\n"); VariableMaintainer.CurrentDockableWindowOutput.AppendText("\n"); IRasterLayer templateImageLayer = ArcGISOperator.GetRasterLayerByName( splitedExpressionArray[1].ToString()); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(VariableMaintainer.DefaultOutputFolder, 0); ISaveAs2 saveAs2 = (ISaveAs2)templateImageLayer.Raster; saveAs2.SaveAs(rasterName, workspace, "IMAGINE Image"); IRasterLayer sutiabilityImageLayer = new RasterLayerClass(); sutiabilityImageLayer.CreateFromFilePath(VariableMaintainer.DefaultOutputFolder + @"\" + rasterName); //sutiabilityImageLayer.Renderer = templateImageLayer.Renderer; ArcGISOperator.FoucsMap.AddLayer((ILayer)sutiabilityImageLayer); IRasterLayer simulationImageLayer = new RasterLayerClass(); simulationImageLayer.CreateFromFilePath(VariableMaintainer.DefaultOutputFolder + @"\" + rasterName); ArcGISOperator.WriteRaster(simulationImageLayer, suitabilityData2); IRasterLayer l = ArcGISOperator.GetRasterLayerByName(rasterName); IRaster2 raster = simulationImageLayer.Raster as IRaster2; IPnt fromPnt = new PntClass(); fromPnt.SetCoords(0, 0); IPnt blockSize = new PntClass(); blockSize.SetCoords(simulationImageLayer.ColumnCount, simulationImageLayer.RowCount); IPixelBlock pixelBlock = ((IRaster)raster).CreatePixelBlock(blockSize); l.Raster.Read(fromPnt, pixelBlock); ((IRasterEdit)l.Raster).Refresh(); IActiveView activeView = VariableMaintainer.CurrentFoucsMap as IActiveView; activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); return(suitabilityData2); }
/// <summary> /// 当向导页的新一页出现前可以做的该页初始化工作。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wizardLogistcCA_AfterSwitchPages(object sender, CristiPotlog.Controls.Wizard.AfterSwitchPagesEventArgs e) { //切换至逻辑回归计算页时,应首先读取地图图层信息,填写部分控件 if (e.OldIndex == 1 && e.NewIndex == 2) { //如果不是第一次打开窗体,则再次读取地图数据 application = ArcMap.Application; document = application.Document as IMxDocument; map = document.FocusMap; ArcGISOperator.FoucsMap = document.FocusMap; //如果图层选择框为空 if (comboBoxTrainingStartImage.Items.Count == 0) { for (int i = 0; i < map.LayerCount; i++) { string layerName = map.get_Layer(i).Name; comboBoxTrainingStartImage.Items.Add(layerName); comboBoxTrainingEndImage.Items.Add(layerName); comboBoxSimStartImage.Items.Add(layerName); comboBoxSimEndImage.Items.Add(layerName); } } } //切换到土地利用类型设置页时首先获取图层信息,然后填充土地利用类型 else if (e.OldIndex == 2 && e.NewIndex == 3) { listVariableLayersName.Clear(); trainingStartImageName = comboBoxTrainingStartImage.SelectedItem.ToString(); trainingEndImageName = comboBoxTrainingEndImage.SelectedItem.ToString(); for (int i = 0; i < dataGridViewVariableDatas.Rows.Count; i++) { listVariableLayersName.Add(dataGridViewVariableDatas.Rows[i].Cells[0].Value.ToString()); } //如果已经完成了回归,则不再进行 if (isRegressed) { return; } dataGridViewLandUse.Rows.Clear(); IRasterLayer rasterLayer = ArcGISOperator.GetRasterLayerByName(trainingStartImageName); IRasterUniqueValueRenderer rasterUniqueValueRenderer = (IRasterUniqueValueRenderer)rasterLayer.Renderer; IRasterRendererUniqueValues rasterRendererUniqueValues = (IRasterRendererUniqueValues)rasterUniqueValueRenderer; IUniqueValues uniqueValues = rasterRendererUniqueValues.UniqueValues; List <object> listUniqueValues = new List <object>(); for (int i = 0; i < uniqueValues.Count; i++) { listUniqueValues.Add(uniqueValues.get_UniqueValue(i)); } int classCount = rasterUniqueValueRenderer.get_ClassCount(0); for (int i = 0; i < classCount; i++) { dataGridViewLandUse.Rows.Add(); dataGridViewLandUse.Rows[i].Cells[0].Value = listUniqueValues[i]; dataGridViewLandUse.Rows[i].Cells[1].Value = rasterUniqueValueRenderer.get_Label(0, i); ISymbol symbol = rasterUniqueValueRenderer.get_Symbol(0, i); IFillSymbol fillSymbol = symbol as IFillSymbol; //ISimpleFillSymbol simpleFillSymbol = (ISimpleFillSymbol)symbol; //IColor esriColor = simpleFillSymbol.Color; IColor esriColor = fillSymbol.Color; IRgbColor rgbColor = new RgbColorClass(); rgbColor.CMYK = esriColor.CMYK; Color color = Color.FromArgb(rgbColor.Red, rgbColor.Green, rgbColor.Blue); dataGridViewLandUse.Rows[i].Cells[3].Value = GeneralOpertor.GetBitmap(15, 15, color); } ColumnLUCharacter.Items.Clear(); ColumnLUCharacter.Items.Add(resourceManager.GetString("String6")); ColumnLUCharacter.Items.Add(resourceManager.GetString("String7")); ColumnLUCharacter.Items.Add(resourceManager.GetString("String8")); } //切换到逻辑回归计算页面时进行计算 if (e.OldIndex == 3 && e.NewIndex == 4) { if (isRegressed) { return; } dataGridViewLogisticRegressionCoeff.Rows.Clear(); labelCalculte.Text = resourceManager.GetString("String9"); labelCalculte.Visible = true; progressBarCalculate.Visible = true; Application.DoEvents(); //1.读取起始图像、终止图像、各变量图像为数组 IRasterLayer rasterLayerStartImage = ArcGISOperator.GetRasterLayerByName(comboBoxTrainingStartImage.SelectedItem.ToString()); IRasterLayer rasterLayerEndImage = ArcGISOperator.GetRasterLayerByName(comboBoxTrainingEndImage.SelectedItem.ToString()); RasterSampling rasterSampling = new RasterSampling(); labelCalculte.Text = resourceManager.GetString("String12"); Application.DoEvents(); List <int> notNullRows; List <int> notNullColumns; trainingStartImage = ArcGISOperator.ReadRasterAndGetNotNullRowColumn(rasterLayerStartImage, out structRasterMetaData, out notNullRows, out notNullColumns); //获取最小空间范围 List <IRasterLayer> listVariablesLayers = new List <IRasterLayer>(); for (int i = 0; i < listVariableLayersName.Count; i++) { listVariablesLayers.Add(ArcGISOperator.GetRasterLayerByName(listVariableLayersName[i])); } ArcGISOperator.GetSmallestBound(rasterLayerStartImage, rasterLayerEndImage, listVariablesLayers, ref structRasterMetaData); labelCalculte.Text = resourceManager.GetString("String13"); Application.DoEvents(); trainingEndImage = ArcGISOperator.ReadRaster(rasterLayerEndImage, structRasterMetaData.NoDataValue); float[,] changeImage = GeneralOpertor.GetBinaryImageByTwoImages(trainingStartImage, trainingEndImage, structRasterMetaData.RowCount, structRasterMetaData.ColumnCount, structRasterMetaData.NoDataValue); //GeneralOpertor.WriteDataFloat(GetOutputFolder() + @"\lr_change.txt", changeImage, structRasterMetaData.RowCount, structRasterMetaData.ColumnCount); foreach (string layerName in listVariableLayersName) { labelCalculte.Text = resourceManager.GetString("String14") + layerName + "....."; Application.DoEvents(); varibaleImages.Add(ArcGISOperator.ReadRaster(ArcGISOperator.GetRasterLayerByName(layerName), structRasterMetaData.NoDataValue)); } //2.按设置的比例进行随机抽样,得到抽样结果,然后计算 //1.进行抽样 labelCalculte.Text = resourceManager.GetString("String11"); Application.DoEvents(); int samplingCellsCount = (int)(structRasterMetaData.RowCount * structRasterMetaData.ColumnCount * numericUpDownSamplingPrecent.Value / 100); float[,] datas = new float[samplingCellsCount, listVariableLayersName.Count + 1]; //抽取真值的比例默认设置为一半 datas = rasterSampling.SamplingData(varibaleImages, changeImage, (double)numericUpDownSamplingPrecent.Value, 50, structRasterMetaData, notNullRows, notNullColumns); //2.进行计算 labelCalculte.Text = resourceManager.GetString("String9"); Application.DoEvents(); //输出抽样结果数据 //GeneralOpertor.WriteDataFloat(GetOutputFolder() + @"\lrSamplingData.txt", datas, // rasterSampling.SamplingCellsCount, listVariableLayersName.Count + 1); //3.使用Accord.NET进行逻辑回归计算 labelCalculte.Text = resourceManager.GetString("String9"); Application.DoEvents(); LogisticRegression lr = new LogisticRegression(); double[] odds; double[] stde; double[] min; double[] max; lr.LogisticRegresssionAanlysis(datas, rasterSampling.SamplingCellsCount, listVariableLayersName.Count + 1, out coef, out odds, out stde, out min, out max); for (int i = 0; i < listVariableLayersName.Count + 1; i++) { dataGridViewLogisticRegressionCoeff.Rows.Add(); if (i == 0) { dataGridViewLogisticRegressionCoeff.Rows[i].Cells[0].Value = resourceManager.GetString("String15"); } else { dataGridViewLogisticRegressionCoeff.Rows[i].Cells[0].Value = listVariableLayersName[i - 1]; } dataGridViewLogisticRegressionCoeff.Rows[i].Cells[1].Value = coef[i]; dataGridViewLogisticRegressionCoeff.Rows[i].Cells[2].Value = odds[i]; dataGridViewLogisticRegressionCoeff.Rows[i].Cells[3].Value = stde[i]; dataGridViewLogisticRegressionCoeff.Rows[i].Cells[4].Value = max[i]; dataGridViewLogisticRegressionCoeff.Rows[i].Cells[5].Value = min[i]; } labelCalculte.Visible = false; progressBarCalculate.Visible = false; Application.DoEvents(); isRegressed = true; } //切换到模拟参数设置页时给定控件初始值,同时保存模拟数据信息 else if (e.OldIndex == 4 && e.NewIndex == 5) { if (comboBoxSimEndImage.SelectedIndex == -1) { buttonCalConvertCells.Enabled = false; } else { buttonCalConvertCells.Enabled = true; } } //切换到模拟过程参数设置页时给定控件初始值,同时保存模拟参数信息 else if (e.OldIndex == 5 && e.NewIndex == 6) { simulationStartImageName = comboBoxSimStartImage.SelectedItem.ToString(); if (comboBoxSimEndImage.SelectedIndex != -1) { simulationEndImageName = comboBoxSimEndImage.SelectedItem.ToString(); } convertCount = Convert.ToInt32(numericUpDownConvertCount.Value); simulationIterations = Convert.ToInt32(numericUpDownIterations.Value); delta = Convert.ToInt32(numericUpDownDelta.Value); numericUpDownRefresh.Value = 10; numericUpDownOutputImage.Value = 10; outputFolder = GetOutputFolder(); textBoxOutputFolder.Text = outputFolder; } //切换到完成页时填充摘要,同时保存模拟过程输出参数的信息 else if (e.OldIndex == 6 && e.NewIndex == 7) { refreshInterval = Convert.ToInt32(numericUpDownRefresh.Value); outputImageInterval = Convert.ToInt32(numericUpDownOutputImage.Value); if (radioButtonOutput.Checked) { isOutput = true; } else { isOutput = false; } outputFolder = textBoxOutputFolder.Text; textBoxSummay.Text = WriteSummay(); } }