private static async void SetRasterColorByAttributeField(RasterLayer raster, string fieldName, StyleProjectItem styleProjItem) { await QueuedTask.Run(() => { var ramps = styleProjItem.SearchColorRamps("Green Blues"); CIMColorRamp colorRamp = ramps[0].ColorRamp; var colorizerDef = new UniqueValueColorizerDefinition(fieldName, colorRamp); var colorizer = raster.CreateColorizer(colorizerDef); // fix up colorizer ... due to a problem with getting the values for different attribute table fields: // we use the Raster's attribute table to collect a dictionary with the correct replacement values Dictionary <string, string> landuseToFieldValue = new Dictionary <string, string>(); if (colorizer is CIMRasterUniqueValueColorizer uvrColorizer) { var rasterTbl = raster.GetRaster().GetAttributeTable(); var cursor = rasterTbl.Search(); while (cursor.MoveNext()) { var row = cursor.Current; var correctField = row[fieldName].ToString(); var key = row[uvrColorizer.Groups[0].Heading].ToString(); landuseToFieldValue.Add(key.ToLower(), correctField); } uvrColorizer.Groups[0].Heading = fieldName; for (var idxGrp = 0; idxGrp < uvrColorizer.Groups[0].Classes.Length; idxGrp++) { var grpClass = uvrColorizer.Groups[0].Classes[idxGrp]; var oldValue = grpClass.Values[0].ToLower(); var correctField = landuseToFieldValue[oldValue]; grpClass.Values[0] = correctField; grpClass.Label = $@"{correctField}"; } } raster.SetColorizer(colorizer); }); }
private static CIMRasterColorizer RecalculateColorizer(RasterLayer rasterLayer, CIMRasterColorizer colorizer, string fieldName) { // fix up colorizer ... turns out the values are wrong ... the landuse value is always inserted // we use the Raster's attribute table to collect a dictionary with the correct replacement values Dictionary <string, string> landuseToFieldValue = new Dictionary <string, string>(); if (colorizer is CIMRasterUniqueValueColorizer uvrColorizer) { var rasterTbl = rasterLayer.GetRaster().GetAttributeTable(); var cursor = rasterTbl.Search(); while (cursor.MoveNext()) { var row = cursor.Current; var correctField = row[fieldName].ToString(); var key = row[uvrColorizer.Groups[0].Heading].ToString(); landuseToFieldValue.Add(key, correctField); } uvrColorizer.Groups[0].Heading = fieldName; for (var idxGrp = 0; idxGrp < uvrColorizer.Groups[0].Classes.Length; idxGrp++) { var grpClass = uvrColorizer.Groups[0].Classes[idxGrp]; var oldValue = grpClass.Values[0]; var correctValue = landuseToFieldValue[oldValue]; grpClass.Values[0] = correctValue; grpClass.Label = $@"{correctValue}"; } } return(colorizer); }
private async void sensitivity_Click(object sender, EventArgs e) { if ((combo1.SelectedIndex == -1) || (combo2.SelectedIndex == -1)) { MessageBox.Show("Cannot Perform SA unless criteria and simulations are selected"); return; } Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "csv file (*.csv)|*.csv|txt file (*.txt)|*.txt|All files (*.*)|*.*"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; saveFileDialog1.OverwritePrompt = true; saveFileDialog1.AddExtension = true; saveFileDialog1.InitialDirectory = @"D:\"; saveFileDialog1.Title = "Save your Weights"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { myStream.Close(); } } else if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) { MessageBox.Show("Save your csv file"); } string fp = saveFileDialog1.FileName; // Defining new array rowSum1 with length as rowSum double[] rowSum1 = new double[rowSum.Length]; for (int i = -Convert.ToInt16(combo2.SelectedItem) / 2; i <= Convert.ToInt16(combo2.SelectedItem) / 2; i++) { //Copy contents of rowSum to rowSum1 starting from 0 rowSum.CopyTo(rowSum1, 0); if (i == 0) { continue; } for (int j = 0; j < combo1.Items.Count; j++) { //Positive Increment if (i > 0) { rowSum1[combo1.SelectedIndex] = rowSum1[combo1.SelectedIndex] * (1 + 0.01 * i); if (j != combo1.SelectedIndex) { System.Diagnostics.Debug.WriteLine(i); rowSum1[j] = rowSum1[j] * (1 - 0.01 * i); } } //Negative increment else { rowSum1[combo1.SelectedIndex] = rowSum1[combo1.SelectedIndex] * (1 + 0.01 * i); if (j != combo1.SelectedIndex) { System.Diagnostics.Debug.WriteLine(i); rowSum1[j] = rowSum1[j] * (1 - 0.01 * i); } } //Skip iteration when i=0 } // Writing to a csv file string delimiter = ","; int length = rowSum1.Length; //using (TextWriter writer = File.CreateText(filepath)) using (TextWriter writer = File.AppendText(fp)) //StringBuilder csv = new StringBuilder(); { if (i == -Convert.ToInt16(combo2.SelectedItem) / 2) { writer.Write(string.Join(delimiter, "% Change", "\t")); for (int a = 0; a < combo1.Items.Count; a++) { writer.Write(string.Join(delimiter, combo1.Items[a], "\t")); } } writer.Write("\n"); writer.Write(string.Join(delimiter, i, "\t")); for (int index = 0; index < length; index++) { writer.Write(string.Join(delimiter, Math.Round(rowSum1[index], 3), "\t")); } } List <string> paths = new List <string>(); List <string> myinputs = new List <string>(); TreeNode test = Goal.TopNode; //Geoprocessing starts here await QueuedTask.Run(() => // Task t = QueuedTask.Run(() => { for (int k = 0; k < test.Nodes.Count; k++) { var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>(); //All raster layers in Map View //System.Diagnostics.Debug.WriteLine(test.Nodes[k].Tag.ToString()); for (int m = 0; m < rlyrs.Count(); m++) { RasterLayer rlyr = rlyrs.ElementAt(m); //raster layer at specific position Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource if (test.Nodes[k].Tag.ToString() == rlyr.Name) { paths.Add(dataStore.GetPath().AbsolutePath);//getting path System.Diagnostics.Debug.WriteLine(rlyr.Name); System.Diagnostics.Debug.WriteLine(paths); // adding paths to input array, value and weights myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum1[k], 3)); System.Diagnostics.Debug.WriteLine(rowSum1); } } } }); //t.Wait(); System.Diagnostics.Debug.WriteLine(i); if (i < 0) { string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "down"); System.Diagnostics.Debug.WriteLine(output_raster); var param_values = Geoprocessing.MakeValueArray(myinputs, output_raster); string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None); progressLabel.Text = "Reclassification Started for " + Math.Abs(i).ToString() + " % decrease"; List <string> remap = new List <string>(); remap.Add("0 0.6 1"); remap.Add("0.6 0.8 2"); remap.Add("0.8 1 3"); string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "downreclass"); var kufli = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2); //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Finished for " + Math.Abs(i).ToString() + " % decrease. Check in TOC"; } else { string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + i + "up"); System.Diagnostics.Debug.WriteLine(output_raster); var param_values = Geoprocessing.MakeValueArray(myinputs, output_raster); string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None); progressLabel.Text = "Reclassification Started for " + Math.Abs(i).ToString() + " % increase"; List <string> remap = new List <string>(); remap.Add("0 0.6 1"); remap.Add("0.6 0.8 2"); remap.Add("0.8 1 3"); string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + Math.Abs(i) + "upreclass"); var kufli = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2); //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Finished for " + Math.Abs(i).ToString() + " % increase. Check in TOC"; } foreach (var Item in rowSum1) { System.Diagnostics.Debug.WriteLine(Item.ToString()); } // Clear the array so that new values will be populated based on original Array.Clear(rowSum1, 0, rowSum1.Length); //Clear inputs myinputs.Clear(); } }
//Click to create suitability map private async void Map_Click(object sender, EventArgs e) { var mapView = MapView.Active; List <string> paths = new List <string>(); List <string> myinputs = new List <string>(); TreeNode test = Goal.TopNode; //using await instead of .wait() for asynchronous execution (Wait for the results) await QueuedTask.Run(() => { for (int k = 0; k < test.Nodes.Count; k++) { var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>(); //All raster layers for (int m = 0; m < rlyrs.Count(); m++) { RasterLayer rlyr = rlyrs.ElementAt(m); //raster layer at specific position Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource if (test.Nodes[k].Tag.ToString() == rlyr.Name) { paths.Add(dataStore.GetPath().AbsolutePath); myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum[k], 2)); } } } }); //t.Wait(); //For Showing Progress Window (Optional) var progDlgWS = new ProgressDialog("Weighted Sum Progress", "Cancel", 100, true); progDlgWS.Show(); var progSrc = new CancelableProgressorSource(progDlgWS); string weightedSumRaster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster"); var param_values = Geoprocessing.MakeValueArray(myinputs, weightedSumRaster); //use toolBoxNameAlias.toolName.Alias string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); //Uncomment below line if you want GP tool to open in Pro //Geoprocessing.OpenToolDialog(toolpath, param_values); progressLabel.Text = "Performing Weighted Sum, please wait..."; //Not adding weighted sum result to map since its intermediate result await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, new CancelableProgressorSource(progDlgWS).Progressor, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Weighted Sum processing complete. Reclassification started"; //Hide the progress once done. progDlgWS.Hide(); //----Use this if you want to see GP result messages---// //---The flow doesnt progress forward unless you close this box-----// //Geoprocessing.ShowMessageBox(wsresult.Messages, "GP Messages", //wsresult.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default); //Creating a list string to store reclass values List <string> remap = new List <string>(); //Classifying into 3 classes, values can be modified as per user needs. remap.Add("0 0.6 1"); //Least Suitable remap.Add("0.6 0.8 2"); //Moderately Suitable remap.Add("0.8 1 3"); //Highly Suitable string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + "reclass0"); var reclassedRaster = Geoprocessing.MakeValueArray(weightedSumRaster, "VALUE", remap, output_raster2); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", reclassedRaster, env, null, null, GPExecuteToolFlags.AddOutputsToMap); progressLabel.Text = "Reclassification Completed. Check in TOC"; //Geoprocessing.OpenToolDialog("sa.Reclassify", reclassedRaster); }
/// <summary> /// Mask raster pixels based on the rectangle given and save the output in the /// current project folder. /// </summary> /// <param name="geometry">Rectangle to use to mask raster pixels.</param> public static async void MaskRaster(Geometry geometry) { try { // Check if there is an active map view. if (MapView.Active != null) { // Get the active map view. var mapView = MapView.Active; // Get the list of selected layers. IReadOnlyList <Layer> selectedLayerList = mapView.GetSelectedLayers(); if (selectedLayerList.Count == 0) { // If no layers are selected show a message box with the appropriate message. MessageBox.Show("No Layers selected. Please select one Raster layer."); } else { // Get the most recently selected layer. Layer firstSelectedLayer = mapView.GetSelectedLayers().First(); if (firstSelectedLayer is RasterLayer) { // Working with rasters requires the MCT. await QueuedTask.Run(() => { #region Get the raster dataset from the currently selected layer // Get the raster layer from the selected layer. RasterLayer currentRasterLayer = firstSelectedLayer as RasterLayer; // Get the raster from the current selected raster layer. Raster inputRaster = currentRasterLayer.GetRaster(); // Get the basic raster dataset from the raster. BasicRasterDataset basicRasterDataset = inputRaster.GetRasterDataset(); if (!(basicRasterDataset is RasterDataset)) { // If the dataset is not a raster dataset, show a message box with the appropriate message. MessageBox.Show("No Raster Layers selected. Please select one Raster layer."); return; } // Get the input raster dataset from the basic raster dataset. RasterDataset rasterDataset = basicRasterDataset as RasterDataset; #endregion #region Save a copy of the raster dataset in the project folder and open it // Create a full raster from the input raster dataset. inputRaster = rasterDataset.CreateFullRaster(); // Setup the paths and name of the output file and folder inside the project folder. string ouputFolderName = "MaskedOuput"; string outputFolder = Path.Combine(Project.Current.HomeFolderPath, ouputFolderName);; string outputName = "MaskedRaster.tif"; // Delete the output directory if it exists and create it. // Note: You will need write access to the project directory for this sample to work. if (Directory.Exists(outputFolder)) { Directory.Delete(outputFolder, true); } Directory.CreateDirectory(outputFolder); // Create a new file system connection path to open raster datasets using the output folder path. FileSystemConnectionPath outputConnectionPath = new FileSystemConnectionPath( new System.Uri(outputFolder), FileSystemDatastoreType.Raster); // Create a new file system data store for the connection path created above. FileSystemDatastore outputFileSytemDataStore = new FileSystemDatastore(outputConnectionPath); // Create a new raster storage definition. RasterStorageDef rasterStorageDef = new RasterStorageDef(); // Set the pyramid level to 0 meaning no pyramids will be calculated. This is required // because we are going to change the pixels after we save the raster dataset and if the // pyramids are calculated prior to that, the pyramids will be incorrect and will have to // be recalculated. rasterStorageDef.SetPyramidLevel(0); // Save a copy of the raster using the file system data store and the raster storage definition. inputRaster.SaveAs(outputName, outputFileSytemDataStore, "TIFF", rasterStorageDef); // Open the raster dataset you just saved. rasterDataset = OpenRasterDataset(outputFolder, outputName); // Create a full raster from it so we can modify pixels. Raster outputRaster = rasterDataset.CreateFullRaster(); #endregion #region Get the Min/Max Row/Column to mask // If the map spatial reference is different from the spatial reference of the input raster, // set the map spatial reference on the input raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != inputRaster.GetSpatialReference().Name) { inputRaster.SetSpatialReference(mapView.Map.SpatialReference); } // Use the MapToPixel method of the input raster to get the row and column values for the // points of the rectangle. Tuple <int, int> tlcTuple = inputRaster.MapToPixel(geometry.Extent.XMin, geometry.Extent.YMin); Tuple <int, int> lrcTuple = inputRaster.MapToPixel(geometry.Extent.XMax, geometry.Extent.YMax); int minCol = (int)tlcTuple.Item1; int minRow = (int)tlcTuple.Item2; int maxCol = (int)lrcTuple.Item1; int maxRow = (int)lrcTuple.Item2; // Ensure the min's are less than the max's. if (maxCol < minCol) { int temp = maxCol; maxCol = minCol; minCol = temp; } if (maxRow < minRow) { int temp = maxRow; maxRow = minRow; minRow = temp; } // Ensure the mins and maxs are within the raster. minCol = (minCol < 0) ? 0 : minCol; minRow = (minRow < 0) ? 0 : minRow; maxCol = (maxCol > outputRaster.GetWidth()) ? outputRaster.GetWidth() : maxCol; maxRow = (maxRow > outputRaster.GetHeight()) ? outputRaster.GetHeight() : maxRow; #endregion #region Mask pixels based on the rectangle drawn by the user // Calculate the width and height of the pixel block to create. int pbWidth = maxCol - minCol; int pbHeight = maxRow - minRow; // Check to see if the output raster can be edited. if (!outputRaster.CanEdit()) { // If not, show a message box with the appropriate message. MessageBox.Show("Cannot edit raster :("); return; } // Create a new pixel block from the output raster of the height and width calculated above. PixelBlock currentPixelBlock = outputRaster.CreatePixelBlock(pbWidth, pbHeight); // Iterate over the bands of the output raster. for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++) { // For each band, clear the pixel block. currentPixelBlock.Clear(plane); //Array noDataMask = currentPixelBlock.GetNoDataMask(plane, true); //for (int i = 0; i < noDataMask.GetLength(0); i++) // noDataMask.SetValue(Convert.ToByte(0), i); //currentPixelBlock.SetNoDataMask(plane, noDataMask); } // Write the cleared pixel block to the output raster dataset. outputRaster.Write(minCol, minRow, currentPixelBlock); // Refresh the properties of the output raster dataset. outputRaster.Refresh(); #endregion // Create a new layer from the masked raster dataset and add it to the map. LayerFactory.Instance.CreateLayer(new Uri(Path.Combine(outputFolder, outputName)), mapView.Map); // Disable the layer representing the original raster dataset. firstSelectedLayer.SetVisibility(false); }); } else { // If the selected layer is not a raster layer show a message box with the appropriate message. MessageBox.Show("No Raster layers selected. Please select one Raster layer."); } } } } catch (Exception exc) { MessageBox.Show("Exception caught in MaskRaster: " + exc.Message); } }
private async void Map_Click(object sender, EventArgs e) { var mapView = MapView.Active; //string[,] input_rasters = new string[3, 1] { { @"G:\AdvancedRemoteSensing\LabData\Test\charleston12-8-90tm.img VALUE 0.5" }, { @"G:\AdvancedRemoteSensing\LabData\Test\cola_1-15-91tm.img VALUE 0.5" }, { @"G:\AdvancedRemoteSensing\LabData\Test\cola_10-7-97atlas.img VALUE 0.5" } }; //node1.Tagb //myinputs.Add(RasterLayer(i) + " VALUE " + rowSum[i]); //Goal.TopNode.Nodes[i].Text.Split("-->") = x[0] + "-->" + Math.Round(rowSum[i], 3); System.Diagnostics.Debug.WriteLine(Goal.TopNode.Nodes[1].Tag.GetType()); List <string> paths = new List <string>(); List <string> myinputs = new List <string>(); TreeNode test = Goal.TopNode; //double[] rs = rowSum; Task t = QueuedTask.Run(() => { for (int k = 0; k < test.Nodes.Count; k++) { var rlyrs = MapView.Active.Map.Layers.OfType <RasterLayer>(); //All raster layers //System.Diagnostics.Debug.WriteLine(test.Nodes[k].Tag.ToString()); for (int m = 0; m < rlyrs.Count(); m++) { RasterLayer rlyr = rlyrs.ElementAt(m); //raster layer at specific position Datastore dataStore = rlyr.GetRaster().GetRasterDataset().GetDatastore(); //getting datasource if (test.Nodes[k].Tag.ToString() == rlyr.Name) { paths.Add(dataStore.GetPath().AbsolutePath); System.Diagnostics.Debug.WriteLine(rlyr.Name); System.Diagnostics.Debug.WriteLine(paths); myinputs.Add(paths.ElementAt(k) + "/" + rlyr.GetRaster().GetRasterDataset().GetName() + " VALUE " + Math.Round(rowSum[k], 2)); } } } }); t.Wait(); string output_raster = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster"); var param_values = Geoprocessing.MakeValueArray(myinputs, output_raster); string toolpath = "sa.WeightedSum"; var env = Geoprocessing.MakeEnvironmentArray(scratchWorkspace: Project.Current.DefaultGeodatabasePath); await Geoprocessing.ExecuteToolAsync(toolpath, param_values, env, null, null, GPExecuteToolFlags.None); //Geoprocessing.OpenToolDialog("sa.WeightedSum", param_values); List <string> remap = new List <string>(); remap.Add("0 0.6 1"); remap.Add("0.6 0.8 2"); remap.Add("0.8 1 3"); string output_raster2 = System.IO.Path.Combine(Project.Current.DefaultGeodatabasePath, "SuitedRaster" + "reclass0"); var kufli = Geoprocessing.MakeValueArray(output_raster, "VALUE", remap, output_raster2); await Geoprocessing.ExecuteToolAsync("sa.Reclassify", kufli, env, null, null, GPExecuteToolFlags.AddOutputsToMap); //Geoprocessing.OpenToolDialog("sa.Reclassify", kufli); }