Beispiel #1
0
        public void DoSimulation()
        {
            try
            {
                //0准备开始模拟
                ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager;
                FormANNCAWizard formANNCAWizard = VariableMaintainer.CurrentFormANNCAWizard;
                Random          random          = new Random();
                Stopwatch       stopWatch       = new Stopwatch();
                stopWatch.Start();
                //0.1获得数据
                int rowCount    = formANNCAWizard.CurrentStructRasterMetaData.RowCount;
                int columnCount = formANNCAWizard.CurrentStructRasterMetaData.ColumnCount;
                float[,] simulationStartImage = formANNCAWizard.SimulationStartImage;
                float[,] simulationEndImage   = formANNCAWizard.SimulationEndImage;
                float[,] simulationImage      = formANNCAWizard.SimulationImage;

                //0.2计算初始每种土地利用类型的单元数量
                List <StructLanduseInfoAndCount> listLanduseInfoAndCount;   //记录每种土地利用类型的单元数
                listLanduseInfoAndCount = new List <StructLanduseInfoAndCount>();
                StructLanduseInfoAndCount landuseInfoAndCount;
                foreach (StructLanduseInfo structLanduseInfo in formANNCAWizard.LandUseClassificationInfo.AllTypes)
                {
                    landuseInfoAndCount = new StructLanduseInfoAndCount();
                    landuseInfoAndCount.structLanduseInfo = structLanduseInfo;
                    landuseInfoAndCount.LanduseTypeCount  = 0;
                    listLanduseInfoAndCount.Add(landuseInfoAndCount);
                }
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        CommonLibrary.GeneralOpertor.ChangeLandUseCount(simulationStartImage[i, j], -10000, listLanduseInfoAndCount);
                    }
                }

                //0.3显示输出结果窗体和图表窗体
                dockableWindowGraphy.GraphTitle = resourceManager.GetString("String40");
                dockableWindowGraphy.XAxisTitle = resourceManager.GetString("String41");
                dockableWindowGraphy.YAxisTitle = resourceManager.GetString("String42");
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String43"));
                Application.DoEvents();
                //0.4绘制初始的图表
                List <string> listPointPairListName = new List <string>();
                List <string> notToDrawList         = new List <string>();
                notToDrawList.Add(resourceManager.GetString("String44"));
                dockableWindowGraphy.CreateGraph(listLanduseInfoAndCount, notToDrawList, out listPointPairListName);
                dockableWindowGraphy.RefreshGraph();

                int          convertedCellCount = 0;                                                                 //模拟中总共转换的元胞数量
                int          randomRow, randomColumn;                                                                //Monte Carlo方法选取的随机行和随机列
                int          convertCountInOneIteration = formANNCAWizard.ConvertCount / formANNCAWizard.Iterations; //每次迭代应转换的数量
                int          convertCountOnce = 0;                                                                   //每次迭代已经转换的数量
                float        oldValue, newValue;                                                                     //每次转换前土地利用类型的新值和旧值
                int          iteration = 0;                                                                          //迭代的次数
                List <float> listLanduseValues = new List <float>();                                                 //记录土地利用类型值的List
                for (int j = 0; j < formANNCAWizard.LandUseClassificationInfo.AllTypesCount; j++)
                {
                    listLanduseValues.Add(formANNCAWizard.LandUseClassificationInfo.AllTypes[j].LanduseTypeValue);
                }
                int neiWindowSize      = formANNCAWizard.NeighbourWindowSize;
                int inputNeuronsCount  = formANNCAWizard.InputNeuronsCount;
                int outputNeuronsCount = formANNCAWizard.OutputNeuronsCount;
                //2.开始进行转换
                while (convertedCellCount < formANNCAWizard.ConvertCount)
                {
                    convertCountOnce = 0;

                    //2.3选择元胞与随机比较进行转换
                    //完成一次迭代
                    while (convertCountOnce < convertCountInOneIteration)
                    {
                        //随机选择一个栅格进行计算
                        randomRow    = random.Next(0, rowCount);
                        randomColumn = random.Next(0, columnCount);

                        //计算逻辑为:
                        //这里需要首先获取当前元胞的输入值
                        //然后通过神经网络计算每种土地利用类型的概率,乘以随机量
                        //然后选出最高的概率
                        //再查看是否是同样的土地利用类型,如果不是则转变
                        //如果不是并且概率大于一个值,则进行转变(目前先不用)

                        //如果是空值,则不进行计算
                        if (simulationImage[randomRow, randomColumn] == -9999f)
                        {
                            continue;
                        }

                        double[] tempInputsArray  = new double[inputNeuronsCount];
                        double[] tempOutputsArray = new double[outputNeuronsCount];
                        //获取该栅格的空间变量值
                        for (int i = 0; i < formANNCAWizard.ListVaribaleImages.Count; i++)
                        {
                            tempInputsArray[i] = formANNCAWizard.ListVaribaleImages[i][randomRow, randomColumn];
                        }
                        //获取该栅格的邻域值
                        NeighbourOperator neighbourOperator = new NeighbourOperator();
                        float[]           counts            = neighbourOperator.GetNeighbourCount(simulationImage, randomRow, randomColumn, neiWindowSize,
                                                                                                  rowCount, columnCount, formANNCAWizard.LandUseClassificationInfo.AllTypesCount, listLanduseValues);
                        for (int z = 0; z < counts.Length; z++)
                        {
                            tempInputsArray[formANNCAWizard.ListVaribaleImages.Count + z] = counts[z] / (neiWindowSize * neiWindowSize - 1);
                        }
                        //获取该栅格的土地利用类型
                        tempInputsArray[inputNeuronsCount - 1] = simulationImage[randomRow, randomColumn];

                        //计算神经网络输出的概率值
                        double[] output    = formANNCAWizard.ANN.ANNActivationNetwork.Compute(tempInputsArray);
                        double   maxOutput = 0;
                        int      maxIndex  = -1;
                        Random   r         = new Random(1);
                        double   gamma;
                        double   disturbance;
                        double   probability;
                        double[] probabilityArray = new double[output.Length];
                        for (int k = 0; k < output.Length; k++)
                        {
                            gamma               = random.NextDouble();
                            disturbance         = 1 + Math.Pow((-Math.Log(gamma)), formANNCAWizard.Delta);
                            probabilityArray[k] = disturbance * output[k];
                            if (maxOutput < probabilityArray[k])
                            {
                                maxOutput = probabilityArray[k];
                                maxIndex  = k;
                            }
                        }
                        probability = maxOutput;  //计算最高值的最终概率

                        //未使用邻域因素模拟较为散,所以加入邻域因素。但可能导致难以达到需要的转换数量,模拟时间过长。
                        double neiValue = 0f;
                        for (int t = 0; t < listLanduseValues.Count; t++)
                        {
                            if (listLanduseValues[t] == formANNCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue)
                            {
                                neiValue = Convert.ToDouble(counts[t]) / (neiWindowSize * neiWindowSize - 1);
                                break;
                            }
                        }
                        probability = probability * neiValue;

                        //得到应转变为的土地利用类型值,以及当前土地利用类型值
                        newValue = formANNCAWizard.LandUseClassificationInfo.AllTypes[maxIndex].LanduseTypeValue;
                        oldValue = simulationImage[randomRow, randomColumn];
                        //oldValue有时取到0值等不正确的值
                        bool isOldValueCorrect = false;
                        for (int w = 0; w < formANNCAWizard.LandUseClassificationInfo.AllTypes.Count; w++)
                        {
                            if (oldValue == formANNCAWizard.LandUseClassificationInfo.AllTypes[w].LanduseTypeValue)
                            {
                                isOldValueCorrect = true;
                            }
                        }
                        if (!isOldValueCorrect)
                        {
                            continue;
                        }
                        //根据转换矩阵进行判断是否可以转换
                        DataTable dtMatrix      = formANNCAWizard.DTMatrix;
                        int       oldValueIndex = -1;
                        for (int k = 0; k < formANNCAWizard.LandUseClassificationInfo.AllTypesCount; k++)
                        {
                            if (formANNCAWizard.LandUseClassificationInfo.AllTypes[k].LanduseTypeValue == oldValue)
                            {
                                oldValueIndex = k;
                                break;
                            }
                        }
                        string canConvert = dtMatrix.Rows[oldValueIndex][maxIndex].ToString();
                        if (canConvert == "0")
                        {
                            continue;
                        }

                        //与设定的阈值进行比较
                        double convertThreshold = formANNCAWizard.ConvertThreshold;
                        if ((oldValue != newValue) && (probability >= convertThreshold))
                        {
                            simulationImage[randomRow, randomColumn] = newValue;
                            CommonLibrary.GeneralOpertor.ChangeLandUseCount(newValue, oldValue, listLanduseInfoAndCount);
                            //以城市用地的转变量为总转变量的标准
                            for (int w = 0; w < formANNCAWizard.LandUseClassificationInfo.UrbanValues.Count; w++)
                            {
                                if (newValue == formANNCAWizard.LandUseClassificationInfo.UrbanValues[w].LanduseTypeValue)
                                {
                                    convertCountOnce++;
                                    convertedCellCount++;
                                }
                            }
                            //System.Diagnostics.Debug.WriteLine(convertedCellCount + " - Old: " + oldValue + " New: " + newValue);
                        }
                    }
                    iteration++;
                    System.Diagnostics.Debug.WriteLine("iteration: " + iteration);

                    //2.4.刷新外部界面并输出中间结果数据
                    if (convertedCellCount == 1 || (iteration % formANNCAWizard.RefreshInterval == 0 && convertedCellCount != 0))
                    {
                        //刷新图像
                        formANNCAWizard.SimulationImage  = simulationImage;
                        VariableMaintainer.IsNeedRefresh = true;

                        //刷新图表窗体
                        string landuseTypeName = "";
                        for (int k = 0; k < listLanduseInfoAndCount.Count; k++)
                        {
                            for (int l = 0; l < listPointPairListName.Count; l++)
                            {
                                if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHS")
                                {
                                    landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChsName;
                                }
                                else if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHT")
                                {
                                    landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChtName;
                                }
                                else
                                {
                                    landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeEnName;
                                }
                                if (landuseTypeName == listPointPairListName[l])
                                {
                                    dockableWindowGraphy.UpdateData(iteration, listLanduseInfoAndCount[k].LanduseTypeCount, l);
                                }
                            }
                        }
                        dockableWindowGraphy.RefreshGraph();

                        //刷新输出结果窗体
                        dockableWindowOutput.AppendText("\n");
                        dockableWindowOutput.AppendText(resourceManager.GetString("String45") + iteration.ToString()
                                                        + resourceManager.GetString("String46"));
                        dockableWindowOutput.AppendText("\n");
                        dockableWindowOutput.AppendText(resourceManager.GetString("String47") + convertedCellCount.ToString());
                        dockableWindowOutput.AppendText("\n");
                        dockableWindowOutput.ScrollTextbox();
                        Application.DoEvents();
                    }
                    //输出中间结果
                    if (formANNCAWizard.IsOutput && (iteration % formANNCAWizard.OutputImageInterval == 0))
                    {
                        GeneralOpertor.WriteDataFloat(formANNCAWizard.OutputFolder + @"\" + GeneralOpertor.GetNowString()
                                                      + "_ann_iterate_" + iteration.ToString() + @".txt", simulationImage, rowCount, columnCount);
                    }
                }

                //3.完成模拟,输出结果。
                stopWatch.Stop();
                VariableMaintainer.IsSimulationFinished = true;
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String48"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String49") +
                                                GeneralOpertor.GetElapsedTimeString(stopWatch.Elapsed));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText("\n");

                //修改结果栅格的属性表
                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IRasterWorkspace  rasterWorkspace  = workspaceFactory.OpenFromFile(
                    VariableMaintainer.CurrentFormANNCAWizard.OutputFolder, 0) as IRasterWorkspace;
                IRasterDataset      rasterDataset      = rasterWorkspace.OpenRasterDataset(VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name);
                IRasterDatasetEdit3 rasterDatasetEdit3 = rasterDataset as IRasterDatasetEdit3;
                rasterDatasetEdit3.BuildAttributeTable();
                IRasterDataset3 rasterDataset3 = rasterDataset as IRasterDataset3;
                rasterDataset3.Refresh();

                if (formANNCAWizard.SimulationEndImageName != "")
                {
                    //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\CA_ANN_Reslut" + GeneralOpertor.GetNowString() + ".txt",
                    //    simulationImage, rowCount,columnCount);

                    DataTable dtMatrixNumber = GeneralOpertor.GetMultiTypesMatrix(
                        simulationImage, simulationEndImage, rowCount, columnCount, formANNCAWizard.LandUseClassificationInfo);
                    double overallAccuracy = 0d;
                    double kappa           = 0d;
                    GeneralOpertor.GetMultiTypesAccuracy(dtMatrixNumber, ref overallAccuracy, ref kappa, formANNCAWizard.LandUseClassificationInfo);
                    FormConfusionMatrix formConfusionMatrix = new FormConfusionMatrix();
                    formConfusionMatrix.DataTableValues = dtMatrixNumber;
                    DataTable dtMatrixPercent = dtMatrixNumber.Clone();
                    GeneralOpertor.CopyDataTableValues(dtMatrixNumber, dtMatrixPercent);
                    formConfusionMatrix.DataTablePercents = dtMatrixPercent;
                    formConfusionMatrix.DataGridViewConfusionMatrix.DataSource = dtMatrixNumber;
                    formConfusionMatrix.LabelOverallAccuracy.Text = (overallAccuracy * 100).ToString("0.00") + " %";
                    formConfusionMatrix.LabelKappa.Text           = kappa.ToString("0.000");

                    float[] fomValues = GeneralOpertor.GetMultiFoMAccuracy(simulationStartImage, simulationEndImage, simulationImage, rowCount, columnCount);
                    formConfusionMatrix.LabelFoMValues.Text = "A: " + fomValues[0] + "\nB: " + fomValues[1] +
                                                              "\nC: " + fomValues[2] + "\nD: " + fomValues[3];
                    formConfusionMatrix.LabelFoM.Text = fomValues[4].ToString("0.000");
                    formConfusionMatrix.LabelPA.Text  = fomValues[5].ToString("0.000");
                    formConfusionMatrix.LabelUA.Text  = fomValues[6].ToString("0.000");

                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String84"));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(GeneralOpertor.WriteCoufusionMatrix(dtMatrixPercent));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String83"));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String85") + (overallAccuracy * 100).ToString("0.00") + " %");
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String86") + kappa.ToString("0.000"));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String87") + fomValues[4].ToString("0.000"));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String88") + fomValues[5].ToString("0.000"));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String89") + fomValues[6].ToString("0.000"));
                    dockableWindowOutput.AppendText("\n");
                    formConfusionMatrix.Text = resourceManager.GetString("String105") + " - " + formANNCAWizard.SimulationLayerName;
                    formConfusionMatrix.ShowDialog();
                }
                dockableWindowOutput.AppendText("-------------------------------------------");
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.ScrollTextbox();
                Application.DoEvents();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #2
0
        public void DoSimulation()
        {
            //0准备开始模拟
            ResourceManager      resourceManager      = VariableMaintainer.CurrentResourceManager;
            FormLogisticCAWizard formLogisticCAWizard = VariableMaintainer.CurrentFormLogisticCAWizard;
            Random    random    = new Random();
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            //0.1获得数据
            int rowCount    = formLogisticCAWizard.CurrentStructRasterMetaData.RowCount;
            int columnCount = formLogisticCAWizard.CurrentStructRasterMetaData.ColumnCount;

            float[,] simulationStartImage = formLogisticCAWizard.SimulationStartImage;
            float[,] simulationEndImage   = formLogisticCAWizard.SimulationEndImage;
            float[,] simulationImage      = formLogisticCAWizard.SimulationImage;

            //0.2计算初始每种土地利用类型的单元数量
            List <StructLanduseInfoAndCount> listLanduseInfoAndCount;   //记录每种土地利用类型的单元数

            listLanduseInfoAndCount = new List <StructLanduseInfoAndCount>();
            StructLanduseInfoAndCount landuseInfoAndCount;

            foreach (StructLanduseInfo structLanduseInfo in formLogisticCAWizard.LandUseClassificationInfo.AllTypes)
            {
                landuseInfoAndCount = new StructLanduseInfoAndCount();
                landuseInfoAndCount.structLanduseInfo = structLanduseInfo;
                landuseInfoAndCount.LanduseTypeCount  = 0;
                listLanduseInfoAndCount.Add(landuseInfoAndCount);
            }
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    CommonLibrary.GeneralOpertor.ChangeLandUseCount(simulationStartImage[i, j], -10000, listLanduseInfoAndCount);
                }
            }

            //0.3显示输出结果窗体和图表窗体
            dockableWindowGraphy.GraphTitle = resourceManager.GetString("String40");
            dockableWindowGraphy.XAxisTitle = resourceManager.GetString("String41");
            dockableWindowGraphy.YAxisTitle = resourceManager.GetString("String42");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText(resourceManager.GetString("String43"));
            Application.DoEvents();
            //0.4绘制初始的图表
            List <string> listPointPairListName = new List <string>();
            List <string> notToDrawList         = new List <string>();

            notToDrawList.Add(resourceManager.GetString("String44"));
            dockableWindowGraphy.CreateGraph(listLanduseInfoAndCount, notToDrawList, out listPointPairListName);
            dockableWindowGraphy.RefreshGraph();

            //1.计算Pg
            float[,] pg = new float[rowCount, columnCount];
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    if (simulationStartImage[i, j] == formLogisticCAWizard.LandUseClassificationInfo.NullValue.LanduseTypeValue)
                    {
                        pg[i, j] = formLogisticCAWizard.LandUseClassificationInfo.NullValue.LanduseTypeValue;
                    }
                    else
                    {
                        pg[i, j] += Convert.ToSingle(formLogisticCAWizard.Coefficents[0]);
                        for (int k = 0; k < formLogisticCAWizard.ListVariableLayersName.Count; k++)
                        {
                            pg[i, j] += Convert.ToSingle(formLogisticCAWizard.Coefficents[k + 1]) *
                                        formLogisticCAWizard.VaribaleImages[k][i, j];
                        }
                    }
                    pg[i, j] = 1 / (1 + Convert.ToSingle(Math.Exp(-1 * pg[i, j])));
                }
            }
            //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\pg.txt", pg, rowCount, columnCount);

            int          convertedCellCount = 0; //模拟中总共转换的元胞数量
            List <float> neighbours;             //Moore领域的元胞
            float        omega;                  //扩散系数
            float        conSuitable;            //适应度函数
            float        maxPct;                 //每次迭代时最大的Pct值

            float[,] pct;
            float[,] pst;
            float sumPtt = 0;                                                                                       //Ptt的总和
            int   randomRow, randomColumn;                                                                          //Monte Carlo方法选取的随机行和随机列
            int   convertCountInOneIteration = formLogisticCAWizard.ConvertCount / formLogisticCAWizard.Iterations; //每次迭代应转换的数量
            int   convertCountOnce = 0;                                                                             //每次迭代已经转换的数量
            float oldValue, newValue;                                                                               //每次转换前土地利用类型的新值和旧值

            int[,] changeCells = new int[rowCount, columnCount];                                                    //记录每次转换为城市的单元。
            int iteration = 0;                                                                                      //迭代的次数

            //2.开始进行转换
            while (convertedCellCount < formLogisticCAWizard.ConvertCount)
            {
                if (convertedCellCount % formLogisticCAWizard.OutputImageInterval == 0 && convertedCellCount != 0)
                {
                    changeCells = new int[rowCount, columnCount];
                }
                convertCountOnce = 0;

                //2.1每次迭代先得到Pct和MaxPct
                maxPct = float.MinValue;
                pct    = new float[rowCount, columnCount];
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        neighbours = CommonLibrary.GeneralOpertor.GetMooreNeighbors(i, j, simulationImage, rowCount, columnCount);
                        omega      = Convert.ToSingle(CommonLibrary.GeneralOpertor.GetUrbanCount(neighbours, formLogisticCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue)) / (neighbours.Count - 1);
                        if (formLogisticCAWizard.LandUseClassificationInfo.IsExistInConvertValue(simulationImage[i, j]))
                        {
                            conSuitable = 1f;
                        }
                        else
                        {
                            conSuitable = 0f;
                        }
                        pct[i, j] = pg[i, j] * conSuitable * omega;
                        if (pct[i, j] > maxPct)
                        {
                            maxPct = pct[i, j];
                        }
                    }
                }
                //CommonOperator.WriteData(Application.StartupPath + @"\\OutputData\pct.txt", pct, structAsciiImageFileMetaData);

                //2.2再得到Pst
                pst    = new float[rowCount, columnCount];
                sumPtt = 0;
                //2.2.1先得到ptt和Ptt的总和
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        pst[i, j] = pct[i, j] * Convert.ToSingle(Math.Exp(-1f * formLogisticCAWizard.Delta * (1f - pct[i, j] / maxPct)));
                        sumPtt   += pst[i, j];
                    }
                }
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        pst[i, j] = convertCountInOneIteration * pst[i, j] / sumPtt;
                    }
                }
                //CommonOperator.WriteData(Application.StartupPath + @"\\OutputData\pst.txt", pst, structAsciiImageFileMetaData);

                //2.3选择元胞与随机比较进行转换
                //完成一次迭代
                while (convertCountOnce < convertCountInOneIteration)
                {
                    randomRow    = random.Next(0, rowCount);
                    randomColumn = random.Next(0, columnCount);
                    if (pst[randomRow, randomColumn] > Convert.ToSingle(random.NextDouble()))
                    {
                        oldValue = simulationImage[randomRow, randomColumn];
                        newValue = formLogisticCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue;
                        simulationImage[randomRow, randomColumn] = newValue;
                        CommonLibrary.GeneralOpertor.ChangeLandUseCount(newValue, oldValue, listLanduseInfoAndCount);
                        convertCountOnce++;
                        convertedCellCount++;
                        changeCells[randomRow, randomColumn] = 1;
                    }
                }
                iteration++;

                //2.4.刷新外部界面并输出中间结果数据
                if (convertedCellCount == 1 || (iteration % formLogisticCAWizard.RefreshInterval == 0 && convertedCellCount != 0))
                {
                    //刷新图像
                    formLogisticCAWizard.SimulationImage = simulationImage;
                    VariableMaintainer.IsNeedRefresh     = true;

                    //刷新图表窗体
                    string landuseTypeName = "";
                    for (int k = 0; k < listLanduseInfoAndCount.Count; k++)
                    {
                        for (int l = 0; l < listPointPairListName.Count; l++)
                        {
                            if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHS")
                            {
                                landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChsName;
                            }
                            else if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHT")
                            {
                                landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChtName;
                            }
                            else
                            {
                                landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeEnName;
                            }
                            if (landuseTypeName == listPointPairListName[l])
                            {
                                dockableWindowGraphy.UpdateData(iteration, listLanduseInfoAndCount[k].LanduseTypeCount, l);
                            }
                        }
                    }
                    dockableWindowGraphy.RefreshGraph();

                    //刷新输出结果窗体
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String45") + iteration.ToString()
                                                    + resourceManager.GetString("String46"));
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.AppendText(resourceManager.GetString("String47") + convertedCellCount.ToString());
                    dockableWindowOutput.AppendText("\n");
                    dockableWindowOutput.ScrollTextbox();
                    Application.DoEvents();
                }
                //输出中间结果
                if (formLogisticCAWizard.IsOutput && (iteration % formLogisticCAWizard.OutputImageInterval == 0))
                {
                    GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\" + GeneralOpertor.GetNowString()
                                                  + "_lr_iterate_" + iteration.ToString() + @".txt", simulationImage, rowCount, columnCount);
                }
            }

            //3.完成模拟,输出结果。
            stopWatch.Stop();
            VariableMaintainer.IsSimulationFinished = true;
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText(resourceManager.GetString("String48"));
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText(resourceManager.GetString("String49") +
                                            GeneralOpertor.GetElapsedTimeString(stopWatch.Elapsed));
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText("\n");

            //修改结果栅格的属性表
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IRasterWorkspace  rasterWorkspace  = workspaceFactory.OpenFromFile(
                VariableMaintainer.CurrentFormLogisticCAWizard.OutputFolder, 0) as IRasterWorkspace;
            IRasterDataset      rasterDataset      = rasterWorkspace.OpenRasterDataset(VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name);
            IRasterDatasetEdit3 rasterDatasetEdit3 = rasterDataset as IRasterDatasetEdit3;

            rasterDatasetEdit3.BuildAttributeTable();
            IRasterDataset3 rasterDataset3 = rasterDataset as IRasterDataset3;

            rasterDataset3.Refresh();

            if (formLogisticCAWizard.SimulationEndImageName != "")
            {
                //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\CA_LR_Reslut" + GeneralOpertor.GetNowString() + ".txt",
                //    simulationImage, rowCount, columnCount);

                StructBinaryConfusionMatrix structConfusionMatrix = GeneralOpertor.GetBinaryAccuracy(
                    simulationImage, simulationEndImage, rowCount, columnCount, formLogisticCAWizard.LandUseClassificationInfo);
                string accuracyString = GeneralOpertor.GetBinaryAccuracyReportString(structConfusionMatrix, convertedCellCount);
                dockableWindowOutput.AppendText(accuracyString);

                DataTable dtMatrixNumber = GeneralOpertor.GetMultiTypesMatrix(
                    simulationImage, simulationEndImage, rowCount, columnCount, formLogisticCAWizard.LandUseClassificationInfo);
                double overallAccuracy = 0d;
                double kappa           = 0d;
                GeneralOpertor.GetMultiTypesAccuracy(dtMatrixNumber, ref overallAccuracy, ref kappa, formLogisticCAWizard.LandUseClassificationInfo);
                FormConfusionMatrix formConfusionMatrix = new FormConfusionMatrix();
                formConfusionMatrix.DataTableValues = dtMatrixNumber;
                DataTable dtMatrixPercent = dtMatrixNumber.Clone();
                GeneralOpertor.CopyDataTableValues(dtMatrixNumber, dtMatrixPercent);
                formConfusionMatrix.DataTablePercents = dtMatrixPercent;
                formConfusionMatrix.DataGridViewConfusionMatrix.DataSource = dtMatrixNumber;
                formConfusionMatrix.LabelOverallAccuracy.Text = (overallAccuracy * 100).ToString("0.00") + " %";
                formConfusionMatrix.LabelKappa.Text           = kappa.ToString("0.000");

                float[] fomValues = GeneralOpertor.GetBinaryFoMAccuracy(simulationStartImage, simulationEndImage, simulationImage,
                                                                        rowCount, columnCount, formLogisticCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue);
                formConfusionMatrix.LabelFoMValues.Text = "A: " + fomValues[0] + "\nB: " + fomValues[1] +
                                                          "\nC: " + fomValues[2] + "\nD: " + fomValues[3];
                formConfusionMatrix.LabelFoM.Text = fomValues[4].ToString("0.000");
                formConfusionMatrix.LabelPA.Text  = fomValues[5].ToString("0.000");
                formConfusionMatrix.LabelUA.Text  = fomValues[6].ToString("0.000");

                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String84"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(GeneralOpertor.WriteCoufusionMatrix(dtMatrixPercent));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String83"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String85") + (overallAccuracy * 100).ToString("0.00") + " %");
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String86") + kappa.ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String87") + fomValues[4].ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String88") + fomValues[5].ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String89") + fomValues[6].ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                formConfusionMatrix.Text = resourceManager.GetString("String105") + " - " + formLogisticCAWizard.SimulationLayerName;
                formConfusionMatrix.ShowDialog();

                dockableWindowOutput.ScrollTextbox();
                Application.DoEvents();
            }
            dockableWindowOutput.AppendText("-------------------------------------------");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.ScrollTextbox();
            Application.DoEvents();
        }
Beispiel #3
0
        public void DoSimulation()
        {
            //0准备开始模拟
            ResourceManager resourceManager = VariableMaintainer.CurrentResourceManager;
            FormDTCAWizard  formDTCAWizard  = VariableMaintainer.CurrentFormDTCAWizard;
            Random          random          = new Random();
            Stopwatch       stopWatch       = new Stopwatch();

            stopWatch.Start();
            //0.1获得数据
            int rowCount    = formDTCAWizard.CurrentStructRasterMetaData.RowCount;
            int columnCount = formDTCAWizard.CurrentStructRasterMetaData.ColumnCount;

            float[,] simulationStartImage = formDTCAWizard.SimulationStartImage;
            float[,] simulationEndImage   = formDTCAWizard.SimulationEndImage;
            float[,] simulationImage      = formDTCAWizard.SimulationImage;

            //0.2计算初始每种土地利用类型的单元数量
            List <StructLanduseInfoAndCount> listLanduseInfoAndCount;   //记录每种土地利用类型的单元数

            listLanduseInfoAndCount = new List <StructLanduseInfoAndCount>();
            StructLanduseInfoAndCount landuseInfoAndCount;

            foreach (StructLanduseInfo structLanduseInfo in formDTCAWizard.LandUseClassificationInfo.AllTypes)
            {
                landuseInfoAndCount = new StructLanduseInfoAndCount();
                landuseInfoAndCount.structLanduseInfo = structLanduseInfo;
                landuseInfoAndCount.LanduseTypeCount  = 0;
                listLanduseInfoAndCount.Add(landuseInfoAndCount);
            }
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    CommonLibrary.GeneralOpertor.ChangeLandUseCount(simulationStartImage[i, j], -10000, listLanduseInfoAndCount);
                }
            }

            //0.3显示输出结果窗体和图表窗体
            dockableWindowGraphy.GraphTitle = resourceManager.GetString("String40");
            dockableWindowGraphy.XAxisTitle = resourceManager.GetString("String41");
            dockableWindowGraphy.YAxisTitle = resourceManager.GetString("String42");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText(resourceManager.GetString("String43"));
            Application.DoEvents();
            //0.4绘制初始的图表
            List <string> listPointPairListName = new List <string>();
            List <string> notToDrawList         = new List <string>();

            notToDrawList.Add(resourceManager.GetString("String44"));
            dockableWindowGraphy.CreateGraph(listLanduseInfoAndCount, notToDrawList, out listPointPairListName);
            dockableWindowGraphy.RefreshGraph();

            int   convertedCellCount = 0;                                                               //模拟中总共转换的元胞数量
            int   randomRow, randomColumn;                                                              //Monte Carlo方法选取的随机行和随机列
            int   convertCountInOneIteration = formDTCAWizard.ConvertCount / formDTCAWizard.Iterations; //每次迭代应转换的数量
            int   convertCountOnce = 0;                                                                 //每次迭代已经转换的数量
            float oldValue, newValue;                                                                   //每次转换前土地利用类型的新值和旧值
            int   iteration = 0;                                                                        //迭代的次数

            //float gamma = 1f / formDTCAWizard.Iterations;
            //float gamma = 0.4f;
            DecisionTree decisionTree    = formDTCAWizard.CurrentDecisionTree;
            List <float> listUrbanValues = new List <float>();

            for (int j = 0; j < formDTCAWizard.LandUseClassificationInfo.UrbanValues.Count; j++)
            {
                listUrbanValues.Add(formDTCAWizard.LandUseClassificationInfo.UrbanValues[j].LanduseTypeValue);
            }
            int neiWindowSize = formDTCAWizard.NeighbourWindowSize;

            try
            {
                //2.开始进行转换
                while (convertedCellCount < formDTCAWizard.ConvertCount)
                {
                    convertCountOnce = 0;

                    while (convertCountOnce < convertCountInOneIteration)
                    {
                        //随机选择一个栅格进行计算
                        randomRow    = random.Next(0, rowCount);
                        randomColumn = random.Next(0, columnCount);

                        //计算逻辑为:
                        //这里需要首先获取当前元胞的输入值
                        //然后通过决策树计算是否发生转变
                        //然后看随机数是否小于等于预定值,则进行转变

                        //如果是空值,则不进行计算
                        if (simulationImage[randomRow, randomColumn] == -9999f)
                        {
                            continue;
                        }
                        //如果模拟影像该栅格是空值,也不进行计算
                        if (formDTCAWizard.ListVaribaleImages[formDTCAWizard.ListVaribaleImages.Count - 1][randomRow, randomColumn] == -9999f)
                        {
                            continue;
                        }
                        //如果已经是城市用地,则不计算
                        if (simulationImage[randomRow, randomColumn] == formDTCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue)
                        {
                            continue;
                        }

                        double[] tempInputsArray = new double[formDTCAWizard.ListVaribaleImages.Count];
                        //获取该栅格的各空间变量值和其他输入变量
                        for (int i = 0; i < formDTCAWizard.ListVaribaleImages.Count; i++)
                        {
                            tempInputsArray[i] = formDTCAWizard.ListVaribaleImages[i][randomRow, randomColumn];
                        }
                        //获取该栅格的邻域中城市用地数量
                        tempInputsArray[formDTCAWizard.ListVaribaleImages.Count - 2] =
                            CommonLibrary.GeneralOpertor.GetNeighbors(randomRow, randomColumn, simulationImage,
                                                                      rowCount, columnCount, neiWindowSize, listUrbanValues);
                        //获取该栅格当前的土地利用类型值
                        tempInputsArray[formDTCAWizard.ListVaribaleImages.Count - 1] = simulationImage[randomRow, randomColumn];

                        //计算决策树输出的转换值
                        int output = formDTCAWizard.CurrentDecisionTree.Compute(tempInputsArray);
                        //如果计算为不转换,则不进行转换
                        if (output == 0)
                        {
                            continue;
                        }
                        //如果可以转换为城市用地
                        if (!formDTCAWizard.LandUseClassificationInfo.IsExistInConvertValue(simulationImage[randomRow, randomColumn]))
                        {
                            continue;
                        }

                        Random r = new Random(1);
                        double convertThreshold = random.NextDouble();
                        //得到应转变为的土地利用类型值,以及当前土地利用类型值
                        newValue = formDTCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue;
                        oldValue = simulationImage[randomRow, randomColumn];
                        //未使用邻域因素模拟较为散,所以加入邻域因素
                        double neighbourValue = tempInputsArray[formDTCAWizard.ListVaribaleImages.Count - 2] / (neiWindowSize * neiWindowSize - 1);
                        //double probability = convertThreshold * neighbourValue;

                        //if ((oldValue != newValue) && (convertThreshold <= gamma))
                        //if ((oldValue != newValue) && (probability >= gamma))
                        //20170619添加限制层数据
                        // if ((VariableMaintainer.RestrictImage[randomRow, randomColumn] == 2) || (VariableMaintainer.RestrictImage[randomRow, randomColumn] == 1))
                        //if (VariableMaintainer.RestrictImage[randomRow, randomColumn] == 1)
                        //    continue;

                        //引入随机因素,如果邻域因素大于随机数
                        if ((oldValue != newValue) && (neighbourValue > convertThreshold))
                        {
                            simulationImage[randomRow, randomColumn] = newValue;
                            CommonLibrary.GeneralOpertor.ChangeLandUseCount(newValue, oldValue, listLanduseInfoAndCount);
                            convertCountOnce++;
                            convertedCellCount++;
                            //System.Diagnostics.Debug.WriteLine(convertedCellCount + " - Old: " + oldValue + " New: " + newValue);
                        }
                    }
                    iteration++;

                    //2.4.刷新外部界面并输出中间结果数据
                    if (convertedCellCount == 1 || (iteration % formDTCAWizard.RefreshInterval == 0 && convertedCellCount != 0))
                    {
                        //刷新图像
                        formDTCAWizard.SimulationImage   = simulationImage;
                        VariableMaintainer.IsNeedRefresh = true;

                        //刷新图表窗体
                        string landuseTypeName = "";
                        for (int k = 0; k < listLanduseInfoAndCount.Count; k++)
                        {
                            for (int l = 0; l < listPointPairListName.Count; l++)
                            {
                                if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHS")
                                {
                                    landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChsName;
                                }
                                else if (System.Globalization.CultureInfo.CurrentCulture.Parent.Name == "zh-CHT")
                                {
                                    landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeChtName;
                                }
                                else
                                {
                                    landuseTypeName = listLanduseInfoAndCount[k].structLanduseInfo.LanduseTypeEnName;
                                }
                                if (landuseTypeName == listPointPairListName[l])
                                {
                                    dockableWindowGraphy.UpdateData(iteration, listLanduseInfoAndCount[k].LanduseTypeCount, l);
                                }
                            }
                        }
                        dockableWindowGraphy.RefreshGraph();

                        //刷新输出结果窗体
                        dockableWindowOutput.AppendText("\n");
                        dockableWindowOutput.AppendText(resourceManager.GetString("String45") + iteration.ToString()
                                                        + resourceManager.GetString("String46"));
                        dockableWindowOutput.AppendText("\n");
                        dockableWindowOutput.AppendText(resourceManager.GetString("String47") + convertedCellCount.ToString());
                        dockableWindowOutput.AppendText("\n");
                        dockableWindowOutput.ScrollTextbox();
                        Application.DoEvents();
                    }
                    //输出中间结果
                    if (formDTCAWizard.IsOutput && (iteration % formDTCAWizard.OutputImageInterval == 0))
                    {
                        GeneralOpertor.WriteDataFloat(formDTCAWizard.OutputFolder + @"\" + GeneralOpertor.GetNowString()
                                                      + "_ann_iterate_" + iteration.ToString() + @".txt", simulationImage, rowCount, columnCount);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DTCA: " + ex.Message);
            }

            //3.完成模拟,输出结果。
            stopWatch.Stop();
            //isFinished = true;
            VariableMaintainer.IsSimulationFinished = true;
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText(resourceManager.GetString("String48"));
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText(resourceManager.GetString("String49") +
                                            GeneralOpertor.GetElapsedTimeString(stopWatch.Elapsed));
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText("\n");

            //修改结果栅格的属性表
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IRasterWorkspace  rasterWorkspace  = workspaceFactory.OpenFromFile(
                VariableMaintainer.CurrentFormDTCAWizard.OutputFolder, 0) as IRasterWorkspace;
            IRasterDataset      rasterDataset      = rasterWorkspace.OpenRasterDataset(VariableMaintainer.CurrentFoucsMap.get_Layer(0).Name);
            IRasterDatasetEdit3 rasterDatasetEdit3 = rasterDataset as IRasterDatasetEdit3;

            rasterDatasetEdit3.BuildAttributeTable();
            IRasterDataset3 rasterDataset3 = rasterDataset as IRasterDataset3;

            rasterDataset3.Refresh();

            if (formDTCAWizard.SimulationEndImageName != "")
            {
                //GeneralOpertor.WriteDataFloat(formLogisticCAWizard.OutputFolder + @"\CA_ANN_Reslut" + GeneralOpertor.GetNowString() + ".txt",
                //    simulationImage, rowCount,columnCount);
                StructBinaryConfusionMatrix structConfusionMatrix = GeneralOpertor.GetBinaryAccuracy(
                    simulationImage, simulationEndImage, rowCount, columnCount, formDTCAWizard.LandUseClassificationInfo);
                string accuracyString = GeneralOpertor.GetBinaryAccuracyReportString(structConfusionMatrix, convertedCellCount);
                dockableWindowOutput.AppendText(accuracyString);

                DataTable dtMatrixNumber = GeneralOpertor.GetMultiTypesMatrix(
                    simulationImage, simulationEndImage, rowCount, columnCount, formDTCAWizard.LandUseClassificationInfo);
                double overallAccuracy = 0d;
                double kappa           = 0d;
                GeneralOpertor.GetMultiTypesAccuracy(dtMatrixNumber, ref overallAccuracy, ref kappa, formDTCAWizard.LandUseClassificationInfo);
                FormConfusionMatrix formConfusionMatrix = new FormConfusionMatrix();
                formConfusionMatrix.DataTableValues = dtMatrixNumber;
                DataTable dtMatrixPercent = dtMatrixNumber.Clone();
                GeneralOpertor.CopyDataTableValues(dtMatrixNumber, dtMatrixPercent);
                formConfusionMatrix.DataTablePercents = dtMatrixPercent;
                formConfusionMatrix.DataGridViewConfusionMatrix.DataSource = dtMatrixNumber;
                formConfusionMatrix.LabelOverallAccuracy.Text = (overallAccuracy * 100).ToString("0.00") + " %";
                formConfusionMatrix.LabelKappa.Text           = kappa.ToString("0.000");

                float[] fomValues = GeneralOpertor.GetBinaryFoMAccuracy(simulationStartImage, simulationEndImage, simulationImage,
                                                                        rowCount, columnCount, formDTCAWizard.LandUseClassificationInfo.UrbanValues[0].LanduseTypeValue);
                formConfusionMatrix.LabelFoMValues.Text = "A: " + fomValues[0] + "\nB: " + fomValues[1] +
                                                          "\nC: " + fomValues[2] + "\nD: " + fomValues[3];
                formConfusionMatrix.LabelFoM.Text = fomValues[4].ToString("0.000");
                formConfusionMatrix.LabelPA.Text  = fomValues[5].ToString("0.000");
                formConfusionMatrix.LabelUA.Text  = fomValues[6].ToString("0.000");

                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String84"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(GeneralOpertor.WriteCoufusionMatrix(dtMatrixPercent));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String83"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String85") + (overallAccuracy * 100).ToString("0.00") + " %");
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String86") + kappa.ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String87") + fomValues[4].ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String88") + fomValues[5].ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                dockableWindowOutput.AppendText(resourceManager.GetString("String89") + fomValues[6].ToString("0.000"));
                dockableWindowOutput.AppendText("\n");
                formConfusionMatrix.Text = resourceManager.GetString("String105") + " - " + formDTCAWizard.SimulationLayerName;
                formConfusionMatrix.ShowDialog();
            }
            dockableWindowOutput.AppendText("-------------------------------------------");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.AppendText("\n");
            dockableWindowOutput.ScrollTextbox();
            Application.DoEvents();
        }
Beispiel #4
0
        public void ChangeRasterValue(IRasterDataset2 pRasterDatset, double dbScale, double dbOffset)
        {
            try
            {
                IRaster2 pRaster2 = pRasterDatset.CreateFullRaster() as IRaster2;

                IPnt pPntBlock = new PntClass();

                pPntBlock.X = 128;
                pPntBlock.Y = 128;

                IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(pPntBlock);
                IRasterEdit   pRasterEdit   = pRaster2 as IRasterEdit;

                if (pRasterEdit.CanEdit())
                {
                    IRasterBandCollection pBands       = pRasterDatset as IRasterBandCollection;
                    IPixelBlock3          pPixelblock3 = null;
                    int          pBlockwidth           = 0;
                    int          pBlockheight          = 0;
                    System.Array pixels;
                    IPnt         pPnt = null;
                    object       pValue;
                    long         pBandCount = pBands.Count;

                    //获取Nodata
                    IRasterProps pRasterPro = pRaster2 as IRasterProps;
                    object       pNodata    = pRasterPro.NoDataValue;
                    //double dbNoData = Convert.ToDouble(((double[])pNodata)[0]);
                    double dbNoData = getNoDataValue(pNodata);

                    do
                    {
                        pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3;
                        pBlockwidth  = pPixelblock3.Width;
                        pBlockheight = pPixelblock3.Height;

                        for (int k = 0; k < pBandCount; k++)
                        {
                            pixels = (System.Array)pPixelblock3.get_PixelData(k);
                            for (int i = 0; i < pBlockwidth; i++)
                            {
                                for (int j = 0; j < pBlockheight; j++)
                                {
                                    pValue = pixels.GetValue(i, j);
                                    double ob = Convert.ToDouble(pValue);
                                    if (ob != dbNoData)
                                    {
                                        ob *= dbScale;  //翻转
                                        ob += dbOffset; //Z方向偏移
                                    }

                                    IRasterProps pRP = pRaster2 as IRasterProps;
                                    if (pRP.PixelType == rstPixelType.PT_CHAR)
                                    {
                                        pixels.SetValue(Convert.ToChar(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_UCHAR)
                                    {
                                        pixels.SetValue(Convert.ToByte(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_FLOAT)
                                    {
                                        pixels.SetValue(Convert.ToSingle(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_DOUBLE)
                                    {
                                        pixels.SetValue(Convert.ToDouble(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_ULONG)
                                    {
                                        pixels.SetValue(Convert.ToInt32(ob), i, j);
                                    }
                                    else
                                    {
                                        ;
                                    }
                                }
                            }
                            pPixelblock3.set_PixelData(k, pixels);

                            System.Array textPixel = null;
                            textPixel = (System.Array)pPixelblock3.get_PixelData(k);
                        }

                        pPnt = pRasterCursor.TopLeft;
                        pRasterEdit.Write(pPnt, (IPixelBlock)pPixelblock3);
                    }while (pRasterCursor.Next());

                    //改变了Z值,重新统计下直方图
                    //IRasterDataset2 prd = pRaster2 as IRasterDataset2;
                    IRasterDatasetEdit3 pRedtit = pRasterDatset as IRasterDatasetEdit3;
                    pRedtit.DeleteStats();//This method is avaliable only on raster datasets in File and ArcSDE geodatabases.
                    pRedtit.ComputeStatisticsHistogram(1, 1, null, true);

                    pRasterEdit.Refresh();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit);
                }
            }
            catch (System.Exception ex)
            {
            }
        }
Beispiel #5
0
        //private rstPixelType GetRasterPixelType(string strType)
        //{
        //    if (strType == rstPixelType.PT_CHAR.ToString())
        //    {
        //        return rstPixelType.PT_CHAR;
        //    }
        //    else if (strType == rstPixelType.PT_UCHAR.ToString())
        //    {
        //        return rstPixelType.PT_UCHAR;
        //    }
        //    else if (strType == rstPixelType.PT_SHORT.ToString())
        //    {
        //        return rstPixelType.PT_SHORT;
        //    }
        //    else if (strType == rstPixelType.PT_USHORT.ToString())
        //    {
        //        return rstPixelType.PT_USHORT;
        //    }
        //    else if (strType == rstPixelType.PT_LONG.ToString())
        //    {
        //        return rstPixelType.PT_LONG;
        //    }
        //    else if (strType == rstPixelType.PT_ULONG.ToString())
        //    {
        //        return rstPixelType.PT_ULONG;
        //    }
        //    else if (strType == rstPixelType.PT_CSHORT.ToString())
        //    {
        //        return rstPixelType.PT_CSHORT;
        //    }
        //    else if (strType == rstPixelType.PT_CLONG.ToString())
        //    {
        //        return rstPixelType.PT_CLONG;
        //    }
        //    else if (strType == rstPixelType.PT_FLOAT.ToString())
        //    {
        //        return rstPixelType.PT_FLOAT;
        //    }
        //    else if (strType == rstPixelType.PT_DOUBLE.ToString())
        //    {
        //        return rstPixelType.PT_DOUBLE;
        //    }

        //    return rstPixelType.PT_CHAR;
        //}
        //private rstResamplingTypes GetRasterResample(string strType)
        //{
        //    if (strType == "NearestNeighbor")
        //    {
        //        return rstResamplingTypes.RSP_NearestNeighbor;
        //    }
        //    else if (strType == "BilinearInterpolation")
        //    {
        //        return rstResamplingTypes.RSP_BilinearInterpolation;
        //    }
        //    else if (strType == "CubicConvolution")
        //    {
        //        return rstResamplingTypes.RSP_CubicConvolution;
        //    }
        //    else if (strType == "Majority")
        //    {
        //        return rstResamplingTypes.RSP_Majority;
        //    }
        //    return rstResamplingTypes.RSP_NearestNeighbor;
        //}

        #endregion

        private bool ExportToTif()
        {
            if (!txtOutData.Text.EndsWith("tif"))
            {
                MessageBox.Show("输出文件名不是tif文件!");
                return(false);
            }

            String strFullName = txtOutData.Text;
            string strPath     = System.IO.Path.GetDirectoryName(strFullName); //导出文件路径
            string strName     = System.IO.Path.GetFileName(strFullName);      //导出文件名

            try
            {
                IRasterBandCollection bandsOut    = m_pRaster as IRasterBandCollection;
                IRasterBandCollection rasterBands = m_pRaster.RasterDataset as IRasterBandCollection;
                double[] dNodata;
                int      nBandOut = 1;
                //IRaster pRasterOut = null;
                IRasterBand pBand = null;

                if (comboBoxExBands.SelectedIndex == 0)//所有波段
                {
                    //添加其他波段
                    for (int i = 3; i < rasterBands.Count; i++)
                    {
                        pBand = rasterBands.Item(i);
                        bandsOut.AppendBand(pBand);
                    }
                    nBandOut = rasterBands.Count;
                }
                else
                {
                    #region 原代码
                    //pRasterOut = new RasterClass();
                    //IRasterBandCollection pRB2 = pRasterOut as IRasterBandCollection;
                    //pRB2.AppendBand(rasterBands.Item(comboBoxExBands.SelectedIndex - 1));
                    //m_pRasterProps = pRasterOut as IRasterProps;
                    #endregion
                    //导出单波段时,不能用Clear(),会清除图层的几何校正属性
                    int nOut = bandsOut.Count;
                    for (int i = 0; i < nOut; i++)
                    {
                        bandsOut.Remove(i);
                    }
                    pBand = rasterBands.Item(comboBoxExBands.SelectedIndex - 1);
                    bandsOut.AppendBand(pBand);
                }
                //重新设置NoData
                dNodata = new double[nBandOut];
                if (!string.IsNullOrEmpty(textNoData.Text))
                {
                    for (int i = 0; i < nBandOut; i++)
                    {
                        dNodata[i] = Convert.ToDouble(textNoData.Text);
                    }
                    m_pRasterProps.NoDataValue = dNodata;
                }
                //else
                //{
                //    for (int i = 0; i < nBandOut; i++)
                //    {
                //        dNodata[i] = ClsGDBDataCommon.getNoDataValue((rasterBands.Item(i) as IRasterProps).NoDataValue);// Convert.ToDouble((rasterBands.Item(i) as IRasterProps).NoDataValue);
                //    }
                //    m_pRasterProps.NoDataValue = dNodata;
                //}


                IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass();
                IWorkspace        pWS  = pWSF.OpenFromFile(System.IO.Path.GetDirectoryName(txtOutData.Text), 0);

                //导出时要保持分辨率和行列数
                m_pRasterProps.Width  = Convert.ToInt32(txtOutColumns.Text);
                m_pRasterProps.Height = Convert.ToInt32(txtOutRows.Text);
                double dcellSizeX = double.Parse(txtCellSizeX.Text);
                double dcellSizeY = double.Parse(txtCellSizeY.Text);

                IEnvelope pEnvelope = new EnvelopeClass();
                pEnvelope.XMin        = m_pRasterProps.Extent.UpperLeft.X;
                pEnvelope.YMax        = m_pRasterProps.Extent.UpperLeft.Y;
                pEnvelope.XMax        = m_pRasterProps.Extent.UpperLeft.X + m_pRasterProps.Width * dcellSizeX;
                pEnvelope.YMin        = m_pRasterProps.Extent.UpperLeft.Y - m_pRasterProps.Height * dcellSizeY;
                m_pRasterProps.Extent = pEnvelope;
                //设置存储位数
                m_pRasterProps.PixelType = (rstPixelType)cmbPixelType.SelectedIndex;

                ISaveAs2 pSaveAs = m_pRasterProps as ISaveAs2;

                IRasterStorageDef  pRSDef  = new RasterStorageDefClass();
                IRasterStorageDef2 pRsDef2 = pRSDef as IRasterStorageDef2;
                //将存储栅格的分辨率设置为与原始图像相同,其实经过上面行列计算之后已经是相同的
                IPnt pPntdec = new PntClass();
                pPntdec.X                   = dcellSizeX;
                pPntdec.Y                   = dcellSizeY;
                pRsDef2.CellSize            = pPntdec;
                pRsDef2.PyramidResampleType = (rstResamplingTypes)cmbResample.SelectedIndex;
                IRasterDataset      pDataset    = pSaveAs.SaveAsRasterDataset(System.IO.Path.GetFileName(txtOutData.Text), pWS, "TIFF", pRSDef);
                IRasterDatasetEdit3 rasterEdit3 = pDataset as IRasterDatasetEdit3;
                //rasterEdit3.DeleteStats();//This method is avaliable only on raster datasets in File and ArcSDE geodatabases.
                rasterEdit3.ComputeStatisticsHistogram(1, 1, null, true);


                //导出数据之后要恢复图像的原始属性
                m_pRasterProps.SpatialReference = m_pSpatialRef;
                m_pRasterProps.Extent           = m_Envelope;
                m_pRasterProps.Width            = m_nCols;
                m_pRasterProps.Height           = m_nRows;
                //加到当前地图中
                IRasterLayer layerNew = new RasterLayerClass();
                layerNew.CreateFromDataset(pDataset);
                m_pMap.AddLayer(layerNew);
                IActiveView activeView = m_pMap as IActiveView;
                activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);

                return(true);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }
        }
Beispiel #6
0
        //拉伸到灰度图像
        private bool stretchToGrayImage(IRaster pSrcRaster, string szOutputFilename, double dbMinThreshold = 0.02, double dbMaxThreshold = 0.98)
        {
            try
            {
                if (pSrcRaster == null || szOutputFilename == null)
                {
                    return(false);
                }

                //深拷贝
                IClone       pSrcClone    = pSrcRaster as IClone;
                IClone       pDstClone    = pSrcClone.Clone();
                IRaster      pDstRaster   = pDstClone as IRaster;
                IRaster2     pDstRaster2  = pDstRaster as IRaster2;
                IRasterProps pRasterProps = pDstRaster as IRasterProps;

                //原始统计信息
                bool        bFlag       = false;
                IRasterBand pRasterBand = (pDstRaster as IRasterBandCollection).Item(0);
                pRasterBand.HasStatistics(out bFlag);
                if (!bFlag)
                {
                    pRasterBand.ComputeStatsAndHist();
                }

                //得到原始栅格影像的最大最小值和步长
                double dbSrcMaxValue     = pRasterBand.Statistics.Maximum;
                double dbSrcMinValue     = pRasterBand.Statistics.Minimum;
                double dbSrcStep         = (dbSrcMaxValue - dbSrcMinValue) / 256;
                double dbStretchMaxValue = pRasterBand.Statistics.Maximum;
                double dbStretchMinValue = pRasterBand.Statistics.Minimum;

                #region 灰度映射,利用重分类来做

                //第一次重分类
                IReclassOp   reclassOp   = new RasterReclassOpClass();
                INumberRemap numberRemap = new NumberRemapClass();
                for (int i = 0; i < 256; i++)
                {
                    numberRemap.MapRange(dbSrcMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i);
                }
                IRaster      pRasterTemp      = reclassOp.ReclassByRemap((IGeoDataset)(pDstRaster2.RasterDataset), (IRemap)numberRemap, true) as IRaster;
                IRaster2     pRasterTemp2     = pRasterTemp as IRaster2;
                IRasterProps pRasterTempProps = pRasterTemp as IRasterProps;

                //得到属性表
                IRasterDatasetEdit3 pRasterDatasetEdit3 = pRasterTemp2.RasterDataset as IRasterDatasetEdit3;
                pRasterDatasetEdit3.ComputeStatisticsHistogram(1, 1, null, true);
                IRasterBand       rasterBand       = (pRasterTempProps as IRasterBandCollection).Item(0);
                IRasterHistogram  rasterHistogram  = rasterBand.Histogram;
                IRasterStatistics rasterStatistics = rasterBand.Statistics;

                double[] pHistogramCount = (double[])rasterHistogram.Counts;

                int nCurrentCount = 0;
                int nIndex        = 0;
                int nPixelCount   = 0;//pRasterProps.Width * pRasterProps.Height;
                //double dSum = 0.0;
                for (int i = 0; i < 256; i++)
                {
                    nPixelCount += (int)pHistogramCount[i];
                }
                //得到拉伸的最大最小值
                while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMinThreshold)
                {
                    nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]);
                }
                dbStretchMinValue = nIndex * dbSrcStep + dbSrcMinValue;

                while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMaxThreshold)
                {
                    nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]);
                }
                dbStretchMaxValue = nIndex * dbSrcStep + dbSrcMinValue;

                dbSrcStep = (dbStretchMaxValue - dbStretchMinValue) / 256;
                #endregion

                #region 拉伸
                INumberRemap numberRemapForStretch = new NumberRemapClass();

                numberRemapForStretch.MapRange(dbSrcMinValue, dbStretchMinValue + dbSrcStep, 0);
                for (int i = 1; i < 255; i++)
                {
                    numberRemapForStretch.MapRange(dbStretchMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i);
                }
                numberRemapForStretch.MapRange(dbStretchMinValue + 255 * dbSrcStep, dbSrcMaxValue, 255);

                IRaster      pRasterStretch      = reclassOp.ReclassByRemap((IGeoDataset)((pDstRaster as IRaster2).RasterDataset), (IRemap)numberRemapForStretch, true) as IRaster;
                IRasterProps pRasterStretchProps = pRasterStretch as IRasterProps;

                #region 注释代码
                ////拉伸
                //IPixelBlock3 pixelBlock3 = null;
                //IRasterCursor rasterCursor = (pDstRaster as IRaster2).CreateCursorEx(null);//null时为128*128

                //do
                //{
                //    pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3;
                //    int nWidth = pixelBlock3.Width;
                //    int nHeight = pixelBlock3.Height;

                //    System.Array pixels = (System.Array)pixelBlock3.get_PixelData(0);
                //    for (int m = 0; m < nWidth; m++)
                //    {
                //        for (int n = 0; n < nHeight; n++)
                //        {
                //            double dbSrcValue = Convert.ToDouble(pixels.GetValue(m, n));
                //            if (double.IsNaN(dbSrcValue) || dbSrcValue == dbNoDataValue)
                //                continue;

                //            if (dbSrcValue >= dbStretchMaxValue)
                //                pixels.SetValue(255, m, n);
                //            else if (dbSrcValue <= dbStretchMinValue)
                //                pixels.SetValue(0, m, n);
                //            else
                //            {
                //                byte dbDstValue = Convert.ToByte((dbSrcValue - dbStretchMinValue) / (dbStretchMaxValue - dbStretchMinValue) * 255);
                //                pixels.SetValue(dbDstValue, m, n);
                //            }
                //        }
                //    }
                //    pixelBlock3.set_PixelData(0, (System.Array)pixels);

                //    //修改数据
                //    pRasterEdit.Write(rasterCursor.TopLeft, pixelBlock3 as IPixelBlock);
                //    pRasterEdit.Refresh();
                //} while (rasterCursor.Next() == true);
                #endregion

                #endregion

                #region 存储数据
                IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace        inmemWor          = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szOutputFilename), 0);
                pRasterStretchProps.PixelType = rstPixelType.PT_UCHAR;
                ISaveAs2 pSaveAs = pRasterStretchProps as ISaveAs2;
                if (pSaveAs == null)
                {
                    return(false);
                }

                IRasterStorageDef pRSDef   = new RasterStorageDefClass();
                IRasterDataset    pDataset = pSaveAs.SaveAsRasterDataset(System.IO.Path.GetFileName(szOutputFilename), inmemWor, "TIFF", pRSDef);
                (pDataset as IRasterDataset3).Refresh();
                //IRasterEdit pRasterEdit = pDstRaster as IRasterEdit;

                IRasterEdit pRasterTempEdit = pRasterTemp as IRasterEdit;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterTempEdit);
                IRasterEdit pRasterStretchEdit = pRasterStretch as IRasterEdit;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterStretchEdit);
                #endregion

                return(true);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }