public override bool New(ICancelProgressHandler progress) { string parafile = Path.Combine(BaseModel.ConfigPath, "heiflow.param"); var succ = true; if (File.Exists(parafile)) { File.Copy(parafile, _mmsPackage.FileName, true); succ = _mmsPackage.Load(progress); if (succ) { ResolveLoadedParameters(false); ResolveModules(); _mmsPackage.FileName = this.ControlFileName; succ = _inputPackage.New(); succ = _outputPackage.New(); } else { var msg = string.Format("\r\n Failed to load {0}. Error: {1}", Name, _mmsPackage.Message); progress.Progress(this.Name, 1, msg); } } else { succ = false; var msg = string.Format("The template parameter file {0} is missing. Please repair the software.", parafile); progress.Progress(this.Name, 1, msg); } return(succ); }
public override bool Load(ICancelProgressHandler progress) { string masterfile = ControlFileName; var succ = true; if (File.Exists(masterfile)) { Subscribe(masterfile, ModelService.WorkDirectory); succ = LoadGrid(progress); if (succ) { LoadPackages(progress); } else { progress.Progress("Modflow", 100, "\tFailed to load model grid."); } return(succ); } else { progress.Progress("Modflow", 100, "\tThe modflow name file dose not exist: " + ControlFileName); return(false); } }
public override bool Load(ICancelProgressHandler progress) { bool succ = true; if (File.Exists(ControlFileName)) { succ = _mmsPackage.Load(progress); if (succ) { ResolveLoadedParameters(true); ResolveModules(); foreach (var pck in Packages.Values) { pck.AfterLoad(); } progress.Progress("PRMS", 1, "Parameters loaded."); } else { progress.Progress("PRMS", 1, string.Format("\r\n Failed to load parameter file. Error message: {1}", _mmsPackage.Message)); } } else { succ = false; progress.Progress("PRMS", 1, string.Format("\r\n Failed to load {0}. The parameter file does not exist: {1}", Name, ControlFileName)); } return(succ); }
/// <summary> /// Executes the ClipPolygonWithPolygon tool with programatic input /// </summary> /// <param name="input">The input feature set to clip</param> /// <param name="input2">The input polygon feature set to clip with</param> /// <param name="output">The output feature set</param> /// <param name="cancelProgressHandler">The progress handler for progress message updates</param> /// <returns></returns> /// Ping delete "static" for external testing public bool Execute( IFeatureSet input, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || input2 == null || output == null) { cancelProgressHandler.Progress(string.Empty, 100, TextStrings.Oneparameterinnull); return(false); } if (input2.FeatureType != FeatureType.Polygon) { cancelProgressHandler.Progress(string.Empty, 100, TextStrings.secondinputlayer); return(false); } output.FeatureType = input.FeatureType; // we add all the old features to output IFeatureSet tempoutput = input.Intersection(input2, FieldJoinType.LocalOnly, cancelProgressHandler); // We add all the fields foreach (DataColumn inputColumn in tempoutput.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } foreach (var fe in tempoutput.Features) { output.Features.Add(fe); } output.SaveAs(output.Filename, true); return(true); }
public override void Save(ICancelProgressHandler progress) { string msg = ""; if (_MFNameManager.IsDirty) { _MFNameManager.Save(ControlFileName); progress.Progress("Modflow", 1, "\tNam file saved"); } foreach (var pck in Packages.Values) { if (pck is IMFPackage) { if (pck.IsDirty && pck.State == ModelObjectState.Ready) { pck.Save(progress); } else { if (!pck.IsDirty) { msg = string.Format("\t{0} unchanged.", pck.Name); progress.Progress("Modflow", 1, msg); } if (pck.State != ModelObjectState.Ready) { msg = string.Format("\ttSkipped to save {0}, it is not ready", pck.Name); progress.Progress("Modflow", 1, msg); } } } } }
public override bool New(ICancelProgressHandler progress) { bool succ = true; _MasterPackage.FileName = ControlFileName; _MasterPackage.Initialize(); succ = _MasterPackage.New(); if (!succ) { var msg = string.Format("Failed to create Control file. Error message: {0}", _MasterPackage.Message); progress.Progress(this.Name, 1, msg); } AddInSilence(_MasterPackage); _ExtensionManPackage.FileName = _MasterPackage.ExtensionManagerFile; succ = _ExtensionManPackage.New(); if (!succ) { var msg = string.Format("Failed to create extension manager file. Error message: {0}", _ExtensionManPackage.Message); progress.Progress(this.Name, 5, msg); } AddInSilence(_ExtensionManPackage); _PRMS.WorkDirectory = this.WorkDirectory; _PRMS.ControlFileName = _MasterPackage.ParameterFilePath; _PRMS.TimeService = _MasterPackage.TimeService; _PRMS.MasterPackage = _MasterPackage; _PRMS.Initialize(); _Modflow.WorkDirectory = this.WorkDirectory; _Modflow.ControlFileName = string.Format("{0}{1}.nam", Modflow.InputDic, Project.Name); _Modflow.Initialize(); _PRMS.Grid = _Modflow.Grid; this.Grid = _Modflow.Grid; succ = _PRMS.New(progress); if (!succ) { var msg = string.Format("Failed to create PRMS."); if (progress != null) { progress.Progress(this.Name, 1, msg); } } succ = _Modflow.New(progress); _Modflow.IOLogFile = _ExtensionManPackage.MF_IOLOG_File; if (!succ) { var msg = string.Format("Failed to create MODFLOW."); if (progress != null) { progress.Progress(this.Name, 1, msg); } } _IsDirty = true; return(succ); }
public override void Save(ICancelProgressHandler progress) { _MasterPackage.Save(progress); _ExtensionManPackage.Save(progress); progress.Progress(this.Name, 1, "Saving PRMS input files..."); _PRMS.Save(progress); progress.Progress(this.Name, 1, "Saving MODFLOW input files..."); _Modflow.Save(progress); }
/// <summary> /// Executes the Erase Opaeration tool programaticaly /// </summary> /// <param name="self">The input feature that is to be erased</param> /// <param name="other">The other feature defining the area to remove</param> /// <param name="output">The resulting erased content</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns>Boolean, true if the operation was a success</returns> public static bool Execute( IFeatureSet self, IFeatureSet other, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (self == null || other == null || output == null) { return(false); } int previous; int max = self.Features.Count * other.Features.Count; output.CopyTableSchema(self); // Fill the 1st Featureset fields IFeatureSet tempSet = self.CombinedFields(other); // go through every feature in 1st featureSet for (int i = 0; i < self.Features.Count; i++) { // go through every feature in 2nd featureSet for (int j = 0; j < other.Features.Count; j++) { self.Features[i].Difference(other.Features[j], tempSet, FieldJoinType.All); previous = Convert.ToInt32(Math.Round(i * j * 50D / max)); if (cancelProgressHandler.Cancel) { return(false); } cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } } // Add to the Output Feature Set for (int a = 0; a < tempSet.Features.Count; a++) { output.Features.Add(tempSet.Features[a]); previous = Convert.ToInt32(Math.Round((a * 50D / tempSet.Features.Count) + 50D)); if (cancelProgressHandler.Cancel) { return(false); } cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } output.SaveAs(output.Filename, true); // add to map? return(true); }
/// <summary> /// Buffer test /// </summary> /// <param name="input"></param> /// <param name="bufferDistance"></param> /// <param name="output"></param> /// <param name="cancelProgressHandler"></param> /// <returns></returns> public static bool GetBuffer( IFeatureSet input, double bufferDistance, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { int previous = 0; int maxNo = input.Features.Count; for (int i = 0; i < maxNo; i++) { input.Features[i].Buffer(bufferDistance, output); // Here we update the progress int current = Convert.ToInt32(i * 100 / maxNo); if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); previous = current; } if (cancelProgressHandler.Cancel) { return(false); } } output.Save(); return(true); }
/// <summary> /// Creates a new project. /// </summary> public bool New(string prjName, string prjDir, IProject project, ICancelProgressHandler progress, bool ImportFromExistingModel) { bool succ = true; if (!Directory.Exists(prjDir)) { Directory.CreateDirectory(prjDir); } SetCurrentProjectDirectory(prjDir); project.Name = prjName; project.AbsolutePathToProjectFile = prjDir; project.RelativeModelWorkDirectory = ".\\"; project.Clear(); project.Initialize(); if (project.New(progress, ImportFromExistingModel)) { App.SerializationManager.New(); CurrentProject = project; CurrentProject.Map = App.Map; } else { succ = false; if (progress != null) { progress.Progress("Project", 100, "Failed to create project."); } } return(succ); }
/// <summary> /// Executes the overwrite feature Opaeration tool programaticaly. /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="index">The Index to overwrite</param> /// <param name="input2">The input2 featureSet which has the new feature to overwrite.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute(IFeatureSet input1, int index, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return(false); } if (cancelProgressHandler.Cancel) { return(false); } IFeature newFeature = input2.Features[0]; output.FeatureType = input1.FeatureType; foreach (IFeature f in input1.Features) { output.Features.Add(f); } if (index > -1) { if (index < output.Features.Count) { output.Features.RemoveAt(index); output.Features.Insert(index, newFeature); } } output.SaveAs(output.Filename, true); cancelProgressHandler.Progress(string.Empty, 100, 100 + TextStrings.progresscompleted); return(true); }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="cancelProgressHandler"></param> /// <returns></returns> public bool Execute(IFeatureSet input, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || output == null) { return(false); } // We add all the fields foreach (DataColumn inputColumn in input.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } // We add the area field bool addField = true; string fieldCount = string.Empty; int i = 0; while (addField) { if (output.DataTable.Columns.Contains(TextStrings.Area + fieldCount) == false) { output.DataTable.Columns.Add(new DataColumn(TextStrings.Area + fieldCount, typeof(double))); addField = false; } else { fieldCount = i.ToString(); i++; } } // we add all the old features to output for (int j = 0; j < input.Features.Count; j++) { Feature newFeature = new Feature(input.Features[j].BasicGeometry, output); foreach (DataColumn colSource in input.DataTable.Columns) { newFeature.DataRow[colSource.ColumnName] = input.Features[j].DataRow[colSource.ColumnName]; } newFeature.DataRow[TextStrings.Area + fieldCount] = MultiPolygon.FromBasicGeometry(output.Features[j].BasicGeometry).Area; // Status updates is done here cancelProgressHandler.Progress( string.Empty, Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(input.Features.Count)) * 100), input.Features[j].DataRow[0].ToString()); if (cancelProgressHandler.Cancel) { return(false); } } output.AttributesPopulated = true; output.Save(); return(true); }
public bool Execute(string CSVFilePath, string CSVDestination, ICancelProgressHandler cancelProgressHandler) { DataTable tblDataTable = new DataTable(); tblDataTable = ParseCSVFile(CSVFilePath); DataTable tblSourceData = new DataTable(); tblSourceData = ParseCSVFile(CSVFilePath); DataTable LagValueTable = new DataTable(); LagValueTable = LagTable(tblSourceData, GetMinMaxValue(tblDataTable, cancelProgressHandler)); DataTable2CSV(LagValueTable, CSVDestination, ","); for (int j = 0; j < LagValueTable.Rows.Count; j++) { cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(LagValueTable.Rows.Count)) * 100), LagValueTable.Rows[j][0].ToString() + ":" + LagValueTable.Rows[j][1].ToString()); if (cancelProgressHandler.Cancel) { return(false); } } return(true); }
/// <summary> /// Executes the Erase Opaeration tool programmatically /// Ping Yang deleted static for external testing 01/2010 /// </summary> /// <param name="input">The input raster</param> /// <param name="oldValue">The original double value representing no-data</param> /// <param name="newValue">The new double value representing no-data</param> /// <param name="output">The output raster</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns>True, if executed successfully.</returns> public bool Execute(IRaster input, double oldValue, double newValue, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || newValue == 0 || output == null) { return(false); } Extent envelope = input.Bounds.Extent; int noOfCol = input.NumColumns; int noOfRow = input.NumRows; int previous = 0; Type dataType = input.DataType; // create output raster output = Raster.CreateRaster(output.Filename, string.Empty, noOfCol, noOfRow, 1, dataType, new[] { string.Empty }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = newValue; // Loop throug every cell int max = output.Bounds.NumRows + 1; for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { if (input.Value[i, j] == oldValue) { output.Value[i, j] = newValue; } else { output.Value[i, j] = input.Value[i, j]; } if (cancelProgressHandler.Cancel) { return(false); } } int current = Convert.ToInt32(Math.Round(i * 100D / max)); // only update when increment in persentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } // output = Temp; output.Save(); return(true); }
public bool Execute(string TemperatureFile, string PrecipitationFile, string StreamflowFile, string CSVDestination, ICancelProgressHandler cancelProgressHandler) { DataTable tblTempTable = new DataTable(); DataTable tblPrecipitationTable = new DataTable(); DataTable tblStreamFlowTable = new DataTable(); tblTempTable = ParseCSVFile(TemperatureFile); tblPrecipitationTable = ParseCSVFile(PrecipitationFile); tblStreamFlowTable = ParseCSVFile(StreamflowFile); DataTable InputTable = new DataTable(); InputTable = LagTable(tblTempTable, tblPrecipitationTable, tblStreamFlowTable); DataTable2CSV(InputTable, CSVDestination, " "); for (int j = 0; j < InputTable.Rows.Count; j++) { cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(InputTable.Rows.Count)) * 100), InputTable.Rows[j][0].ToString() + ":" + InputTable.Rows[j][1].ToString()); if (cancelProgressHandler.Cancel) { return(false); } } return(true); }
public bool Execute(string ForecastingResults, string ResultsSave, string StreamFlowSource, ICancelProgressHandler cancelProgressHandler) { DataTable tblForecastingResult = new DataTable(); DataTable tblStreamFlowSource = new DataTable(); tblForecastingResult = ParseCSVFile(ForecastingResults); tblStreamFlowSource = ParseCSVFile(StreamFlowSource); List <double> MinMax = new List <double>(); MinMax = GetMinMaxValue(tblStreamFlowSource, cancelProgressHandler); DataTable dtDeNormalizedValue = new DataTable(); dtDeNormalizedValue = DenormalizedData(tblForecastingResult, MinMax); DataTable2CSV(dtDeNormalizedValue, ResultsSave, ","); for (int j = 0; j < dtDeNormalizedValue.Rows.Count; j++) { cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(dtDeNormalizedValue.Rows.Count)) * 100), dtDeNormalizedValue.Rows[j][0].ToString() + ":" + dtDeNormalizedValue.Rows[j][1].ToString()); if (cancelProgressHandler.Cancel) { return(false); } } return(true); }
/// <summary> /// Executes the generate centroid FeatureSet Opaeration tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute(IFeatureSet input1, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || output == null) { return(false); } bool multiPoint = false; foreach (IFeature f1 in input1.Features) { if (f1.Geometry.NumGeometries > 1) { multiPoint = true; } } output.FeatureType = multiPoint == false ? FeatureType.Point : FeatureType.MultiPoint; int previous = 0; int i = 0; int maxFeature = input1.Features.Count; output.CopyTableSchema(input1); foreach (IFeature f in input1.Features) { if (cancelProgressHandler.Cancel) { return(false); } IFeature fnew = new Feature(f.Geometry.Centroid); // Add the centroid to output output.Features.Add(fnew); fnew.CopyAttributes(f); int current = Convert.ToInt32(Math.Round(i * 100D / maxFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; i++; } output.AttributesPopulated = true; output.SaveAs(output.Filename, true); return(true); }
/// <summary> /// Executes the Erase Opaeration tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="input2">The input Expression string to select features to Delete.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, string input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return(false); } if (cancelProgressHandler.Cancel) { return(false); } int previous = 0; List <IFeature> fetList = input1.SelectByAttribute(input2); int noOfFeaturesToDelete = fetList.Count; int noOfFeatures = input1.Features.Count; output.FeatureType = input1.FeatureType; foreach (IFeature f in input1.Features) { output.Features.Add(f); } // Go through every item in the list for (int i = 0; i < noOfFeaturesToDelete; i++) { int current = Convert.ToInt32(Math.Round(i * 100D / noOfFeaturesToDelete)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; // loop through every item in the list for (int j = 0; j < noOfFeatures; j++) { // Select the Feature from Feature set to detlete if (fetList[i] == input1.Features[j]) { output.Features.Remove(input1.Features[j]); } } } output.SaveAs(output.Filename, true); return(true); }
/// <summary> /// Erase features from one feature set where they are intersected by another feature set. /// </summary> /// <param name="targetFeatures">Features which will be erased in part or whole.</param> /// <param name="sourceFeatures">Features which represent areas to erase.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet EraseFeatures(IFeatureSet targetFeatures, IFeatureSet sourceFeatures, ICancelProgressHandler cancelProgressHandler = null) { if (targetFeatures == null || sourceFeatures == null) { return(null); } // Erase features from one feature set where they are intersected by another feature set // Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. // The current version does not preserve any attribute info. // Dan Ames 2/27/2013 FeatureSet resultFeatures = new FeatureSet(); // the resulting featureset resultFeatures.CopyTableSchema(targetFeatures); // set up the data table in the new feature set for (short i = 0; i <= targetFeatures.ShapeIndices.Count - 1; i++) { var tf = targetFeatures.GetFeature(i); // get the full undifferenced feature for (short j = 0; j <= sourceFeatures.ShapeIndices.Count - 1; j++) { var sf = sourceFeatures.GetFeature(j); if (sf.Geometry.Envelope.Intersects(tf.Geometry.Envelope)) { tf = tf.Difference(sf.Geometry); // clip off any pieces of SF that overlap FR } if (tf == null) { // sometimes difference leaves nothing left of a feature break; } } if (tf != null) { resultFeatures.AddFeature(tf.Geometry).CopyAttributes(targetFeatures.GetFeature(i)); // add the fully clipped feature to the results } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return(null); } int progress = Convert.ToInt32(i * 100 / targetFeatures.ShapeIndices.Count); cancelProgressHandler.Progress(string.Empty, progress, string.Empty); } } return(resultFeatures); }
protected void OnLoadFailed(string msg, ICancelProgressHandler progress) { _IsUsed = false; State = ModelObjectState.Error; if (LoadFailed != null) { LoadFailed(this, msg); } if (progress != null) { progress.Progress(this.Name, 100, msg); } }
/// <summary> /// Executes the ClipPolygonWithPolygon tool with programatic input /// </summary> /// <param name="input">The input feature set to clip</param> /// <param name="input2">The input polygon feature set to clip with</param> /// <param name="output">The output feature set</param> /// <param name="cancelProgressHandler">The progress handler for progress message updates</param> /// <returns>True if executed successfully.</returns> public bool Execute(IFeatureSet input, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || input2 == null || output == null) { cancelProgressHandler.Progress(100, TextStrings.Oneparameterinnull); return(false); } if (input2.FeatureType != FeatureType.Polygon) { cancelProgressHandler.Progress(100, TextStrings.secondinputlayer); return(false); } output.FeatureType = input.FeatureType; // we add all the old features to output IFeatureSet tempoutput = input.Intersection(input2, FieldJoinType.LocalOnly, cancelProgressHandler); // We add all the fields foreach (DataColumn inputColumn in tempoutput.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } foreach (var fe in tempoutput.Features) { output.Features.Add(fe); } // Setting the AttributesPopulated to true here means the output shapefile will get attribute columns copied from // the source file. This problem occurs when using the ClipPolygonWithPolygon tool due to how the input/output files // are loaded. https://github.com/DotSpatial/DotSpatial/issues/892 output.AttributesPopulated = true; output.SaveAs(output.Filename, true); return(true); }
protected void OnSaved(ICancelProgressHandler progress) { if (Saved != null) { Saved(this, EventArgs.Empty); } IsDirty = false; string msg = string.Format("{0} saved", this.Name); if (progress != null) { progress.Progress(this.Name, 100, msg); } }
/// <summary> /// Executes the add features Opaeration tool programaticaly. /// Ping deleted "static" for external Testing /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="input2">The input2 featureSet which has the new features to add.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return(false); } int previous = 0; int i = 0; int maxFeature = input2.Features.Count; output.FeatureType = input1.FeatureType; foreach (IFeature f1 in input1.Features) { output.Features.Add(f1); } // go through new featureset that wanted to add. foreach (IFeature f in input2.Features) { if (cancelProgressHandler.Cancel) { return(false); } if (input1.FeatureType == input2.FeatureType) { output.Features.Add(f); } int current = Convert.ToInt32(Math.Round(i * 100D / maxFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; i++; } output.SaveAs(output.Filename, true); // cancelProgressHandler.Progress("", 100, 100.ToString() + TextStrings.progresscompleted); return(true); }
public override bool Save(ICancelProgressHandler progress) { if (IsDirty) { return(Save(FileName, progress)); } else { if (progress != null) { progress.Progress(this.Name, 1, "\tParameter file unchanged."); } return(true); } }
public bool Execute(string fileName, ICancelProgressHandler cancelProgressHandler) { string SeriesId = GetSeriesId(); DataTable dataValues = GetDataValues(SeriesId); DateTime startDate = Convert.ToDateTime(_inputParameters[3].Value); DateTime endDate = Convert.ToDateTime(_inputParameters[4].Value); DataTable UpdatedDatatable = new DataTable(); UpdatedDatatable.Columns.Add("DateTime"); UpdatedDatatable.Columns.Add("Value"); DataRow siteId = UpdatedDatatable.NewRow(); siteId[0] = SiteId[0].ToString(); siteId[1] = VarId; //Note this is variable Code UpdatedDatatable.Rows.Add(siteId); for (int k = 0; k < dataValues.Rows.Count; k++) { if (startDate < Convert.ToDateTime(dataValues.Rows[k][0].ToString()) && endDate > Convert.ToDateTime(dataValues.Rows[k][0].ToString())) { DataRow dr = UpdatedDatatable.NewRow(); dr[0] = dataValues.Rows[k][0].ToString(); dr[1] = dataValues.Rows[k][1].ToString(); UpdatedDatatable.Rows.Add(dr); } } if (UpdatedDatatable.Rows.Count > 1) { DataTable2CSV(UpdatedDatatable, fileName, ","); for (int j = 1; j < dataValues.Rows.Count; j++) { cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(dataValues.Rows.Count)) * 100), dataValues.Rows[j][0].ToString()); if (cancelProgressHandler.Cancel) { return(false); } } return(true); } else { return(false); } }
/// <summary> /// save to the default file /// </summary> /// <returns></returns> public virtual bool Save(ICancelProgressHandler progress) { if (IsDirty && State == ModelObjectState.Ready) { return(SaveAs(FileName, progress)); } else { if (progress != null) { string msg = string.Format("\t{0} unchanged", this.Name); progress.Progress(this.Name, 1, msg); } return(true); } }
/// <summary> /// Creates a specified number of random point features inside multiple polygon features in a feature set. /// </summary> /// <param name="constrainingFeatures">Random points will be generated inside all features in this feature set.</param> /// <param name="numberOfPoints">The number of points to be randomly generated.</param> /// <param name="fsOut">FeatureSet, the points should be added to.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static IFeatureSet RandomPoints(IFeatureSet constrainingFeatures, int numberOfPoints, IFeatureSet fsOut = null, ICancelProgressHandler cancelProgressHandler = null) { // This function generates random points within the boundaries of all polygon features in a feature set if (fsOut == null) { fsOut = new FeatureSet(); } fsOut.FeatureType = FeatureType.Point; Random r = new Random(); int i = 0; while (i < numberOfPoints) { // make a random point somewhere in the rectangular extents of the feature set double rndx = r.Next(0, 100000) / 100000.0; double rndy = r.Next(0, 100000) / 100000.0; var ext = constrainingFeatures.Extent; var c = new Coordinate { X = (rndx * (ext.MaxX - ext.MinX)) + ext.MinX, Y = (rndy * (ext.MaxY - ext.MinY)) + ext.MinY }; // check if the point falls within the polygon featureset Point p = new Point(c); if (constrainingFeatures.Features.Any(f => f.Geometry.Intersects(p))) { fsOut.AddFeature(p); i++; } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return(null); } int progress = Convert.ToInt32(i * 100 / numberOfPoints); cancelProgressHandler.Progress(string.Empty, progress, string.Empty); } } return(fsOut); }
/// <summary> /// Erase features from one feature set where they are intersected by another feature set. /// </summary> /// <param name="TargetFeatures">Features which will be erased in part or whole.</param> /// <param name="SourceFeatures">Features which represent areas to erase.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet EraseFeatures(IFeatureSet TargetFeatures, IFeatureSet SourceFeatures, ICancelProgressHandler cancelProgressHandler = null) { if (TargetFeatures == null || SourceFeatures == null) { return(null); } //Erase features from one feature set where they are intersected by another feature set //Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. //The current version does not preserve any attribute info. //Dan Ames 2/27/2013 FeatureSet ResultFeatures = new FeatureSet(); //the resulting featureset IFeature TF, SF; //a single output feature ResultFeatures.CopyTableSchema(TargetFeatures); //set up the data table in the new feature set for (Int16 i = 0; i <= TargetFeatures.ShapeIndices.Count - 1; i++) { TF = TargetFeatures.GetFeature(i); //get the full undifferenced feature for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++) { SF = SourceFeatures.GetFeature(j); if (SF.Envelope.Intersects(TF.Envelope)) { TF = TF.Difference(SF); //clip off any pieces of SF that overlap FR } if (TF == null) { //sometimes difference leaves nothing left of a feature break; } } if (TF != null) { ResultFeatures.AddFeature(TF).CopyAttributes(TargetFeatures.GetFeature(i)); //add the fully clipped feature to the results } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return(null); } int progress = Convert.ToInt32(i * 100 / TargetFeatures.ShapeIndices.Count); cancelProgressHandler.Progress(String.Empty, progress, String.Empty); } } return(ResultFeatures); }
private void LoadPackages(ICancelProgressHandler progress) { MFOutputPackage mfout = new MFOutputPackage() { Owner = this }; AddInSilence(mfout); foreach (var pck in Packages.Values) { if (pck is IMFPackage) { try { if (pck.State != ModelObjectState.Ready) { pck.Clear(); pck.Initialize(); var loaded = pck.Load(progress); if (loaded) { (pck as IMFPackage).CompositeOutput(mfout); pck.AfterLoad(); // progress.Progress("Modflow", 1, "\t" + pck.Name + " loaded"); } else { //var msg = string.Format("\tFailed to load {0}. Error message: {1}", pck.Name, pck.Message); //progress.Progress("Modflow", 1, msg); } } } catch (Exception ex) { var msg = string.Format("\tFailed to load {0}. Error message: {1}", pck.Name, ex.Message); progress.Progress("Modflow", 1, msg); } } } var oc = (Packages[OCPackage.PackageName] as OCPackage); oc.CompositeOutput(mfout); mfout.Initialize(); }
public override bool Load(ICancelProgressHandler progress) { string masterfile = ControlFileName; if (File.Exists(masterfile)) { ControlFileName = masterfile; _GHMSerializer = GHMSerializer.Open(masterfile); _GHMPackage = new GHMPackage() { Serializer = _GHMSerializer, GHModel = this }; AddInSilence(_GHMPackage); foreach (var layer in _GHMSerializer.Layers) { foreach (var mem in layer.Members) { foreach (var item in mem.Spatial) { item.FullPath = Path.Combine(ModelService.WorkDirectory, item.Path); item.Grid = this.Grid; } foreach (var item in mem.Spatiotemporal) { item.FullPath = Path.Combine(ModelService.WorkDirectory, item.Path); item.Grid = this.Grid; } foreach (var item in mem.TimeSeries) { item.FullPath = Path.Combine(ModelService.WorkDirectory, item.Path); item.Grid = this.Grid; } } } return(true); } { var msg = "\r\nThe model file dose not exist: " + ControlFileName; progress.Progress("GHModel", 1, msg); return(false); } }
/// <summary> /// Erase features from one feature set where they are intersected by another feature set. /// </summary> /// <param name="TargetFeatures">Features which will be erased in part or whole.</param> /// <param name="SourceFeatures">Features which represent areas to erase.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static FeatureSet EraseFeatures(IFeatureSet TargetFeatures, IFeatureSet SourceFeatures, ICancelProgressHandler cancelProgressHandler = null) { if (TargetFeatures == null || SourceFeatures == null) { return null; } //Erase features from one feature set where they are intersected by another feature set //Note: we use the ShapeIndices here rather than for each feature in featureset.features as a memory management technique. //The current version does not preserve any attribute info. //Dan Ames 2/27/2013 FeatureSet ResultFeatures = new FeatureSet(); //the resulting featureset IFeature TF, SF; //a single output feature ResultFeatures.CopyTableSchema(TargetFeatures); //set up the data table in the new feature set for (Int16 i = 0; i <= TargetFeatures.ShapeIndices.Count - 1; i++) { TF = TargetFeatures.GetFeature(i); //get the full undifferenced feature for (Int16 j = 0; j <= SourceFeatures.ShapeIndices.Count - 1; j++) { SF = SourceFeatures.GetFeature(j); if (SF.Envelope.Intersects(TF.Envelope)) { TF = TF.Difference(SF); //clip off any pieces of SF that overlap FR } if (TF == null) { //sometimes difference leaves nothing left of a feature break; } } if (TF != null) { ResultFeatures.AddFeature(TF).CopyAttributes(TargetFeatures.GetFeature(i)); //add the fully clipped feature to the results } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return null; } int progress = Convert.ToInt32(i * 100 / TargetFeatures.ShapeIndices.Count); cancelProgressHandler.Progress(String.Empty, progress, String.Empty); } } return ResultFeatures; }
public bool Execute(string fileName, ICancelProgressHandler cancelProgressHandler) { string SeriesId = GetSeriesId(); DataTable dataValues = GetDataValues(SeriesId); if (dataValues.Rows.Count > 1) { for (int j = 1; j < dataValues.Rows.Count; j++) { DataTable2CSV(dataValues, fileName, ","); cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(dataValues.Rows.Count)) * 100), dataValues.Rows[j][0].ToString()); if (cancelProgressHandler.Cancel) return false; } return true; } else { return false; } }
/// <summary> /// A static function to compute the buffer and return the result to the Execute function. /// </summary> /// <param name="input">The feature set that will be buffered.</param> /// <param name="bufferDistance">The distance of the buffer.</param> /// <param name="outputFeatures">The resulting feature set that will show the buffer.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel if needed.</param> /// <returns></returns> public static bool AddBuffer(IFeatureSet inputFeatures, double bufferDistance, IFeatureSet outputFeatures, ICancelProgressHandler cancelProgressHandler = null) { int numFeatures = inputFeatures.Features.Count; for (int i = 0; i < numFeatures; i++) { inputFeatures.Features[i].Buffer(bufferDistance, outputFeatures); // Here we update the progress if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return false; } int progress = Convert.ToInt32(i * 100 / numFeatures); cancelProgressHandler.Progress("buffer_tool", progress, "Buffering features."); } } return true; }
/// <summary> /// Creates a specified number of random point features inside multiple polygon features in a feature set. /// </summary> /// <param name="ConstrainingFeatures">Random points will be generated inside all features in this feature set.</param> /// <param name="NumberOfPoints">The number of points to be randomly generated.</param> /// <param name="cancelProgressHandler">Optional parameter to report progress and cancel entire process if needed.</param> /// <returns>A point feature set with the randomly created features.</returns> public static IFeatureSet RandomPoints(IFeatureSet ConstrainingFeatures, int NumberOfPoints, IFeatureSet fsOut = null, ICancelProgressHandler cancelProgressHandler = null) { //This function generates random points within the boundaries of all polygon features in a feature set if (fsOut == null) { fsOut = new FeatureSet(); } fsOut.FeatureType = FeatureType.Point; Coordinate c = new Coordinate(); Random r = new Random(); int i = 0; while (i < NumberOfPoints) { c = new Coordinate(); //make a random point somewhere in the rectangular extents of the feature set double rndx = r.Next(0, 100000) / 100000.0; double rndy = r.Next(0, 100000) / 100000.0; c.X = rndx * (ConstrainingFeatures.Extent.MaxX - ConstrainingFeatures.Extent.MinX) + ConstrainingFeatures.Extent.MinX; c.Y = rndy * (ConstrainingFeatures.Extent.MaxY - ConstrainingFeatures.Extent.MinY) + ConstrainingFeatures.Extent.MinY; //check if the point falls within the polygon featureset foreach (Feature f in ConstrainingFeatures.Features) { if (f.Intersects(c)) { fsOut.AddFeature(new Feature(c)); i++; } } if (cancelProgressHandler != null) { if (cancelProgressHandler.Cancel) { return null; } int progress = Convert.ToInt32(i * 100 / NumberOfPoints); cancelProgressHandler.Progress(String.Empty, progress, String.Empty); } } return fsOut; }
/// <summary> /// Create polygons from raster. /// </summary> /// <param name="input">The Polygon Raster(Grid file).</param> /// <param name="connectionGrid">Connection Grid.</param> /// <param name="output">The Polygon shapefile path.</param> /// <param name="cancelProgressHandler">The progress handler.</param> public bool Execute(IRaster input, IRaster connectionGrid, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { if (input == null || output == null) { return false; } output.DataTable.Columns.Add("Value", typeof(double)); var featureHash = new Dictionary<double, LineSegmentList>(); var previous = 0.0; var height = input.CellHeight; var width = input.CellWidth; var xMin = input.Xllcenter - width / 2.0; var yMin = input.Yllcenter - height / 2.0; var xMax = xMin + width * input.NumColumns; var yMax = yMin + height * input.NumRows; var numRows = input.NumRows; var numColumns = input.NumColumns; Func<int, int, double, bool> same = (y, x, value) => y >= 0 && y < numRows && x >= 0 && x < numColumns && input.Value[y, x] == value; Func<int, int, double> get = (y, x) => y >= 0 && y < numRows && x >= 0 && x < numColumns ? input.Value[y, x] : input.NoDataValue; Func<int, int, int, int, bool> eqValues = (y1, x1, y2, x2) => get(y1, x1) == get(y2, x2); var enableCon = connectionGrid != null; Func<int, int, int> connection = (y, x) => enableCon ? (int) connectionGrid.Value[y, x] : 0; for (int y = 0; y < numRows; y++) { int current = Convert.ToInt32((y * 100.0) / input.NumRows); if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); previous = current; } Debug.WriteLine("Row : " + y + " done."); for (int x = 0; x < numColumns; x++) { var value = input.Value[y, x]; if (value == input.NoDataValue) { continue; } LineSegmentList lineList; if (!featureHash.TryGetValue(value, out lineList)) { lineList = new LineSegmentList(); featureHash.Add(value, lineList); } var curCon = connection(y, x); /* 6 7 8 5 0 1 4 3 2 current cell (x,y)=0 */ var con_7 = same(y + 1, x, value); var con_5 = same(y, x - 1, value); var con_3 = same(y - 1, x, value); var con_1 = same(y, x + 1, value); var con_8l = enableCon && same(y + 1, x + 1, value) && !con_7 && (curCon == 8 || connection(y + 1, x + 1) == 4); var con_8r = enableCon && same(y + 1, x + 1, value) && !con_1 && (curCon == 8 || connection(y + 1, x + 1) == 4); var con_6l = enableCon && same(y + 1, x - 1, value) && !con_5 && (curCon == 6 || connection(y + 1, x - 1) == 2); var con_6r = enableCon && same(y + 1, x - 1, value) && !con_7 && (curCon == 6 || connection(y + 1, x - 1) == 2); var con_4l = enableCon && same(y - 1, x - 1, value) && !con_5 && (curCon == 4 || connection(y - 1, x - 1) == 8); var con_4r = enableCon && same(y - 1, x - 1, value) && !con_3 && (curCon == 4 || connection(y - 1, x - 1) == 8); var con_2l = enableCon && same(y - 1, x + 1, value) && !con_3 && (curCon == 2 || connection(y - 1, x + 1) == 6); var con_2r = enableCon && same(y - 1, x + 1, value) && !con_1 && (curCon == 2 || connection(y - 1, x + 1) == 6); /* Cell points: tl tc tr cl cr bl bc br */ var tl = new Coordinate(xMin + x*width, yMax - (y + 1)*height); var tc = new Coordinate(xMin + (x + 0.5)*width, yMax - (y + 1)*height); var tr = new Coordinate(xMin + (x + 1)*width, yMax - (y + 1)*height); var cl = new Coordinate(xMin + x*width, yMax - (y + 0.5)*height); var cr = new Coordinate(xMin + (x + 1)*width, yMax - (y + 0.5)*height); var bl = new Coordinate(xMin + x * width, yMax - y * height); var bc = new Coordinate(xMin + (x + 0.5)*width, yMax - y*height); var br = new Coordinate(xMin + (x + 1)*width, yMax - y*height); /* Cell edges: e_tl e_tr ----|---- e_lt | | e_rt - - e_lb | | e_rb ----|---- e_bl e_br */ bool e_tr = false, e_tl = false, e_lt = false, e_lb = false, e_rt = false, e_rb = false, e_br = false, e_bl = false; if (!con_7) { #region Check Cell 7 // top: right half if (!con_8l) { var a1 = con_6r && con_1; var a2 = !con_8r && !con_6l && con_4l && !con_2r; e_tr = a1 || a2; } // top: left half if (!con_6r) { var a1 = con_8l && con_5; var a2 = !con_8r && !con_6l && !con_4l && con_2r; e_tl = a1 || a2; } // top: full if (!con_8l && !con_6r && !con_4l && !con_2r) { e_tr = e_tl = true; } #endregion } if (!con_3) { #region Check Cell 3 // bottom: left half if (!con_4r) { var a1 = con_2l && con_5; var a2 = !con_2r && !con_4l && !con_6l && con_8r; e_bl = a1 || a2; } // bottom: right half if (!con_2l) { var a1 = con_4r && con_1; var a2 = !con_2r && !con_4l && !con_8r && con_6l; e_br = a1 || a2; } // bottom: full if (!con_4r && !con_2l && !con_8r && !con_6l) { e_bl = e_br = true; } #endregion } if (!con_1) { #region Check Cell 1 // right: bottom half if (!con_2r) { var a1 = con_8r && con_3; var a2 = !con_2l && !con_8l && !con_4r && con_6r; e_rb = a1 || a2; } // right: top half if (!con_8r) { var a1 = con_2r && con_7; var a2 = !con_2l && !con_8l && !con_6r && con_4r; e_rt = a1 || a2; } // right: full if (!con_2r && !con_8r && !con_4r && !con_6r) { e_rb = e_rt = true; } #endregion } if (!con_5) { #region Check Cell 5 // left: bottom half if (!con_4l) { var a1 = con_3 && con_6l; var a2 = !con_6r && !con_4r && con_8l && !con_2l; e_lb = a1 || a2; } // left: top half if (!con_6l) { var a1 = con_4l && con_7; var a2 = !con_6r && !con_4r && !con_8l && con_2l; e_lt = a1 || a2; } // left: full if (!con_4l && !con_6l && !con_8l && !con_2l) { e_lb = e_lt = true; } #endregion } // Smooth boundaries regarding to outer cells // Right top corner if (e_tr && e_rt) { if (eqValues(y + 1, x, y, x + 1)) { var a1 = connection(y + 1, x); var a2 = connection(y, x + 1); if ((a1 == 6 || a1 == 2 || a2 == 6 || a2 == 2) && !(a1 == 6 && a2 == 2)) { lineList.AddSegment(tc, cr); e_tr = e_rt = false; } } } // Left top corner if (e_tl && e_lt) { if (eqValues(y, x - 1, y + 1, x)) { var a1 = connection(y, x - 1); var a2 = connection(y + 1, x); if ((a1 == 8 || a1 == 4 || a2 == 8 || a2 == 4) && !(a1 == 8 && a2 == 4)) { lineList.AddSegment(tc, cl); e_tl = e_lt = false; } } } // Left bottom corner if (e_bl && e_lb) { if (eqValues(y - 1, x, y, x - 1)) { var a1 = connection(y - 1, x); var a2 = connection(y, x - 1); if ((a1 == 6 || a1 == 2 || a2 == 6 || a2 == 2) && !(a1 == 6 && a2 == 2)) { lineList.AddSegment(cl, bc); e_bl = e_lb = false; } } } // Right bottom corner if (e_br && e_rb) { if (eqValues(y, x + 1, y - 1, x)) { var a1 = connection(y, x + 1); var a2 = connection(y - 1, x); if ((a1 == 8 || a1 == 4 || a2 == 8 || a2 == 4) && !(a1 == 8 && a2 == 4)) { lineList.AddSegment(bc, cr); e_br = e_rb = false; } } } // Smooth boundaries regarding direction of current cell switch (curCon) { case 2: case 6: if (e_tr && e_rt) { lineList.AddSegment(tc, cr); e_tr = e_rt = false; } if (e_bl && e_lb) { lineList.AddSegment(bc, cl); e_bl = e_lb = false; } break; case 4: case 8: if (e_tl && e_lt) { lineList.AddSegment(cl, tc); e_tl = e_lt = false; } if (e_br && e_rb) { lineList.AddSegment(cr, bc); e_br = e_rb = false; } break; } // Add remaining edges // Top if (e_tl && e_tr) { lineList.AddSegment(tl, tr); } else if (e_tl) { lineList.AddSegment(tl, tc); } else if(e_tr) { lineList.AddSegment(tc, tr); } //Left if (e_lt && e_lb) { lineList.AddSegment(tl, bl); } else if (e_lt) { lineList.AddSegment(tl, cl); } else if (e_lb) { lineList.AddSegment(cl, bl); } // Bottom if (e_bl && e_br) { lineList.AddSegment(bl, br); } else if (e_bl) { lineList.AddSegment(bl, bc); } else if (e_br) { lineList.AddSegment(bc, br); } // Right if (e_rt && e_rb) { lineList.AddSegment(tr, br); } else if (e_rt) { lineList.AddSegment(tr, cr); } else if (e_rb) { lineList.AddSegment(cr, br); } // Right top out diagonals if (con_8l) { lineList.AddSegment(tc, new Coordinate(xMin + (x + 1)*width, yMax - (y + 1 + 0.5)*height)); } if (con_8r) { lineList.AddSegment(cr, new Coordinate(xMin + (x + 1 + 0.5) * width, yMax - (y + 1) * height)); } // Right in diagonals if (con_4l || con_8l) { if (!con_6r && !con_6l && !con_7 && !con_5) { lineList.AddSegment(tc, cl); } } if (con_4r || con_8r) { if (!con_2r && !con_2l && !con_1 && !con_3) { lineList.AddSegment(cr, bc); } } // Left Top out diagonals if (con_6r) { lineList.AddSegment(tc, new Coordinate(xMin + x*width, yMax - (y + 1 + 0.5)*height)); } if (con_6l) { lineList.AddSegment(cl, new Coordinate(xMin + (x - 0.5) * width, yMax - (y + 1) * height)); } // Left In diagonals if (con_6r || con_2r) { if (!con_8r && !con_8l && !con_7 && !con_1) { lineList.AddSegment(tc, cr); } } if (con_6l || con_2l) { if (!con_4r && !con_4l && !con_5 && !con_3) { lineList.AddSegment(cl, bc); } } if (cancelProgressHandler.Cancel) { return false; } } } var sw = new Stopwatch(); foreach (var pair in featureHash) { sw.Restart(); var key = pair.Key; var lineSegList = pair.Value.List; var polyList = new List<Polygon>(); var ind = 0; while (ind != lineSegList.Count) { var polyShell = new List<Coordinate>(); var start = lineSegList[ind++]; polyShell.Add(start.P0); polyShell.Add(start.P1); while (!polyShell[0].Equals2D(polyShell[polyShell.Count - 1])) { var last = polyShell[polyShell.Count - 1]; LineSegment segment = null; for (int i = ind; i < lineSegList.Count; i++) { var cur = lineSegList[i]; if (cur.P0.Equals2D(last) || cur.P1.Equals2D(last)) { segment = cur; if (ind != i) { var swap = lineSegList[ind]; lineSegList[ind] = cur; lineSegList[i] = swap; } ind++; break; } } Debug.Assert(segment != null); polyShell.Add(segment.P0.Equals2D(last) ? segment.P1 : segment.P0); } polyList.Add(new Polygon(polyShell)); } var geometry = polyList.Count == 1 ? (IBasicGeometry)polyList[0] : new MultiPolygon(polyList.ToArray()); var f = output.AddFeature(geometry); f.DataRow["Value"] = key; sw.Stop(); Debug.WriteLine(sw.ElapsedMilliseconds); } output.AttributesPopulated = true; output.Save(); return true; }
/// <summary> /// Executes the DP line simplefy tool programaticaly /// </summary> /// <param name="input">The input polygon feature set</param> /// <param name="tolerance">The tolerance to use when simplefiying</param> /// <param name="output">The output polygon feature set</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns></returns> public bool Execute(IFeatureSet input, double tolerance, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input == null || output == null) return false; //We copy all the fields foreach (DataColumn inputColumn in input.DataTable.Columns) output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); int numTotalOldPoints = 0; int numTotalNewPoints = 0; for (int j = 0; j < input.Features.Count; j++) { int numOldPoints = 0; int numNewPoints = 0; Geometry geom = input.Features[j].BasicGeometry as Geometry; if (geom != null) numOldPoints = geom.NumPoints; numTotalOldPoints += numOldPoints; if (geom != null) { for (int part = 0; part < geom.NumGeometries; part++) { Geometry geomPart = (Geometry)geom.GetGeometryN(part); //do the simplification IList<Coordinate> oldCoords = geomPart.Coordinates; IList<Coordinate> newCoords = MapWindow.Analysis.Topology.Simplify.DouglasPeuckerLineSimplifier.Simplify(oldCoords, tolerance); //convert the coordinates back to a geometry Geometry newGeom = new LineString(newCoords); numNewPoints += newGeom.NumPoints; numTotalNewPoints += numNewPoints; Feature newFeature = new Feature(newGeom, output); foreach (DataColumn colSource in input.DataTable.Columns) newFeature.DataRow[colSource.ColumnName] = input.Features[j].DataRow[colSource.ColumnName]; } } //Status updates is done here, shows number of old / new points cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(input.Features.Count)) * 100), numOldPoints + "-->" + numNewPoints); if (cancelProgressHandler.Cancel) return false; } cancelProgressHandler.Progress("", 100, TextStrings.Originalnumberofpoints + numTotalOldPoints + " " + TextStrings.Newnumberofpoints + numTotalNewPoints); output.Save(); return true; }
/// <summary> /// Finds the average slope in the given polygons with more user preferences. /// </summary> /// <param name="ras">The dem Raster(Grid file).</param> /// <param name="inZFactor">The scaler factor</param> /// <param name="slopeInPercent">The slope in percentage.</param> /// <param name="poly">The flow poly shapefile path.</param> /// <param name="fldInPolyToStoreSlope">The field name to store average slope in the attribute.</param> /// <param name="outerShpFile">The Featureset where we have the area of interest</param> /// <param name="outerShpIndex">The index of featureset which give paticular area of interest.</param> /// <param name="output">The path to save created slope Feature set.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IRaster ras, double inZFactor, bool slopeInPercent, IFeatureSet poly, string fldInPolyToStoreSlope, IFeatureSet outerShpFile, int outerShpIndex, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (ras == null || poly == null || outerShpFile == null || output == null) { return false; } if (poly.FeatureType != FeatureType.Polygon || outerShpFile.FeatureType != FeatureType.Polygon) { return false; } int previous = 0; IRaster slopegrid = new Raster(); int[] areaCount = new int[poly.Features.Count]; double[] areaTotal = new double[poly.Features.Count]; double[] areaAve = new double[poly.Features.Count]; Slope(ras, inZFactor, slopeInPercent, slopegrid, cancelProgressHandler); if (slopegrid == null) { throw new SystemException(TextStrings.Slopegridfileisnull); } foreach (IFeature f in poly.Features) { output.Features.Add(f); } for (int i = 0; i < slopegrid.NumRows; i++) { int current = Convert.ToInt32(Math.Round(i * 100D / slopegrid.NumRows)); // only update when increment in percentage if (current > previous + 5) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); previous = current; } for (int j = 0; j < slopegrid.NumColumns; j++) { Coordinate coordin = slopegrid.CellToProj(i, j); IPoint pt = new Point(coordin); IFeature point = new Feature(pt); if (!outerShpFile.Features[outerShpIndex].Covers(point)) { continue; // not found the point inside. } for (int c = 0; c < poly.Features.Count; c++) { if (output.Features[c].Covers(point)) { areaCount[c]++; areaTotal[c] += slopegrid.Value[i, j] / 100; } if (cancelProgressHandler.Cancel) { return false; } } } } // Add the column output.DataTable.Columns.Add("FID", typeof(int)); output.DataTable.Columns.Add(fldInPolyToStoreSlope, typeof(Double)); for (int c = 0; c < output.Features.Count; c++) { if (areaCount[c] == 0) { areaAve[c] = 0.0; } else { areaAve[c] = areaTotal[c] / areaCount[c]; } // Add the field values output.Features[c].DataRow["FID"] = c; output.Features[c].DataRow[fldInPolyToStoreSlope] = areaAve[c]; } output.SaveAs(output.Filename, true); slopegrid.Close(); ras.Close(); return true; }
public bool Execute(string CSVFilePath, string CSVDestination, ICancelProgressHandler cancelProgressHandler) { tblDataTable = ParseCSVFile(CSVFilePath); Decimal[] ForecastingValue = new decimal[tblDataTable.Rows.Count]; Decimal[] ActualValues = new decimal[tblDataTable.Rows.Count]; DateTime[] Date = new DateTime[tblDataTable.Rows.Count]; for (int j = 0; j < tblDataTable.Rows.Count; j++) { try { double t = Convert.ToDouble(tblDataTable.Rows[j][2]); //Here the forecasting value is gettting based on the actual value //ex: day t is forecasted based on the t-1 value forecastingValue = ForecastingValuefunction(tblDataTable, t); //Here forecasting is done based on the forecasted value //ex: t day is forecastedf based on the t-1 forecasted value //if (forecastingValue == 0) //{ // forecastingValue = ForecastingValuefunction(tblDataTable, t); // ForecastingValue[j] = forecastingValue; //} //else //{ // double dt = Convert.ToDouble(ForecastingValue[j-1]); // forecastingValue = ForecastingValuefunction(tblDataTable, dt); // ForecastingValue[j] = forecastingValue; //} // ForecastingValue[j] = forecastingValue; ActualValues[j] = Convert.ToDecimal(tblDataTable.Rows[j][1]); Date[j] = Convert.ToDateTime(tblDataTable.Rows[j][0]); cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(ActualValues[j])) * 100), ActualValues[j].ToString()); if (cancelProgressHandler.Cancel) return false; } catch { } } DataTable dt1 = new DataTable(); dt1.Columns.Add("Actual Values"); dt1.Columns.Add("Forecasting Values"); dt1.Columns.Add("Date"); for (int g = 0; g < ForecastingValue.Length; g++) { DataRow dr = dt1.NewRow(); dr[0] = Math.Pow(10, Convert.ToDouble(ActualValues[g])); dr[1] = Math.Pow(10, Convert.ToDouble(ForecastingValue[g])); //dr[0] = ActualValues[g]; //dr[1] = ForecastingValue[g]; dr[2] = Date[g]; dt1.Rows.Add(dr); } if (dt1.Rows.Count > 0) { for (int j = 0; j < dt1.Rows.Count; j++) { DataTable2CSV(dt1, CSVDestination, ","); cancelProgressHandler.Progress("", Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(dt1.Rows.Count)) * 100), dt1.Rows[j][0].ToString()); if (cancelProgressHandler.Cancel) return false; } } else { return false; } return true; //decimal testValue = ForecastingValue(tblDataTable, 2.250420002); }
/// <summary> /// Finds the average slope in the given polygons. /// Ping delete static for external testing /// </summary> /// <param name="input">The Polygon Raster(Grid file).</param> /// <param name="output">The Polygon shapefile path.</param> /// <param name="cancelProgressHandler">The progress handler.</param> public bool Execute(IRaster input, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { if ((input == null) || (output == null)) { return false; } output.DataTable.Columns.Add("Value", typeof(double)); Hashtable featureHash = new Hashtable(); double previous = 0.0; int current; double height = input.CellHeight; double width = input.CellWidth; int numRows = input.NumRows; int numColumns = input.NumColumns; double xMin = input.Xllcenter - (input.CellWidth / 2.0); double yMin = input.Yllcenter - (input.CellHeight / 2.0); double xMax = xMin + (height * input.NumColumns); double yMax = yMin + (width * input.NumRows); for (int y = 0; y < numRows; y++) { current = Convert.ToInt32((y * 100.0) / input.NumRows); if (current > previous) { cancelProgressHandler.Progress("", current, current + TextStrings.progresscompleted); previous = current; } Debug.WriteLine("Row : " + y + " done."); for (int x = 0; x < numColumns; x++) { double value = input.Value[y, x]; List<LineSegment> lineList = new List<LineSegment>(); if (!featureHash.Contains(value)) { featureHash.Add(value, lineList); } else { lineList = featureHash[value] as List<LineSegment>; } if (y == 0) { lineList.Add(new LineSegment(new Coordinate((x * width) + xMin, yMax), new Coordinate(((x + 1) * width) + xMin, yMax))); if (input.Value[y + 1, x] != value) { lineList.Add(new LineSegment(new Coordinate((x * width) + xMin, yMax - height), new Coordinate(((x + 1) * width) + xMin, yMax - height))); } } else if (y == (numRows - 1)) { lineList.Add(new LineSegment(new Coordinate((x * width) + xMin, yMin), new Coordinate(((x + 1) * width) + xMin, yMin))); if (input.Value[y - 1, x] != value) { lineList.Add(new LineSegment(new Coordinate((x * width) + xMin, yMin + height), new Coordinate(((x + 1) * width) + xMin, yMin + height))); } } else { if (input.Value[y + 1, x] != value) { lineList.Add(new LineSegment(new Coordinate((x * width) + xMin, yMax - ((y + 1) * height)), new Coordinate(((x + 1) * width) + xMin, yMax - ((y + 1) * height)))); } if (input.Value[y - 1, x] != value) { lineList.Add(new LineSegment(new Coordinate((x * width) + xMin, yMax - (y * height)), new Coordinate(((x + 1) * width) + xMin, yMax - (y * height)))); } } if (x == 0) { lineList.Add(new LineSegment(new Coordinate(xMin, yMax - (y * height)), new Coordinate(xMin, yMax - ((y + 1) * height)))); if (input.Value[y, x + 1] != value) { lineList.Add(new LineSegment(new Coordinate(xMin + width, yMax - (y * height)), new Coordinate(xMin + width, yMax - ((y + 1) * height)))); } } else if (x == (numColumns - 1)) { lineList.Add(new LineSegment(new Coordinate(xMax, yMax - (y * height)), new Coordinate(xMax, yMax - ((y + 1) * height)))); if (input.Value[y, x - 1] != value) { lineList.Add(new LineSegment(new Coordinate(xMax - width, yMax - (y * height)), new Coordinate(xMax - width, yMax - ((y + 1) * height)))); } } else { if (input.Value[y, x + 1] != value) { lineList.Add(new LineSegment(new Coordinate(xMin + ((x + 1) * width), yMax - (y * height)), new Coordinate(xMin + ((x + 1) * width), yMax - ((y + 1) * height)))); } if (input.Value[y, x - 1] != value) { lineList.Add(new LineSegment(new Coordinate(xMin + (x * width), yMax - (y * height)), new Coordinate(xMin + (x * width), yMax - ((y + 1) * height)))); } } if (cancelProgressHandler.Cancel) { return false; } } } Stopwatch sw = new Stopwatch(); foreach (double key in featureHash.Keys) { sw.Reset(); sw.Start(); List<LineSegment> lineSegList = featureHash[key] as List<LineSegment>; if (lineSegList == null) break; List<Polygon> polyList = new List<Polygon>(); while (lineSegList.Count != 0) { List<Coordinate> polyShell = new List<Coordinate>(); LineSegment start = lineSegList[0]; polyShell.Add(start.P0); polyShell.Add(start.P1); lineSegList.Remove(start); while (!polyShell[0].Equals2D(polyShell[polyShell.Count - 1])) { LineSegment segment = lineSegList.Find(delegate (LineSegment o) {return o.P0.Equals2D(polyShell[polyShell.Count - 1]) || o.P1.Equals2D(polyShell[polyShell.Count - 1]);}); if (segment.P0.Equals2D(polyShell[polyShell.Count - 1])) { polyShell.Add(segment.P1); } else { polyShell.Add(segment.P0); } lineSegList.Remove(segment); } polyList.Add(new Polygon(polyShell)); } if (polyList.Count == 1) { Feature feat = new Feature(polyList[0], output); feat.DataRow["Value"] = key; } sw.Stop(); Debug.WriteLine(sw.ElapsedMilliseconds); } output.Save(); return true; }
/// <summary> /// Executes the Erase Opaeration tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input raster.</param> /// <param name="input2">The input raster.</param> /// <param name="output">The output raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute(IRaster input1, IFeatureSet input2, IRaster output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } double cellWidth = input1.CellWidth; double cellHeight = input1.CellHeight; //Calculate the Intersect Envelope IEnvelope envelope1 = input1.Bounds.Envelope; IEnvelope envelope2 = input2.Envelope; envelope1 = envelope1.Intersection(envelope2); int noOfCol = Convert.ToInt32(envelope1.Height / cellHeight); int noOfRow = Convert.ToInt32(envelope1.Width / cellWidth); //create output raster output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, typeof(int), new[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope1); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex v1; // MapWindow.Analysis.Topology.Algorithm.PointLocator pointLocator1 = new MapWindow.Analysis.Topology.Algorithm.PointLocator(); int previous = 0; int max = (output.Bounds.NumRows + 1); for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { Coordinate cellCenter = output.CellToProj(i, j); //test if the coordinate is inside of the polygon bool isInside = false; IFeature pointFeat = new Feature(new Point(cellCenter)); foreach (IFeature f in input2.Features) { if (f.Contains(pointFeat)) { //output.Value[i, j] = val1; isInside = true; break; } } if (isInside) { v1 = input1.ProjToCell(cellCenter); double val1; if (v1.Row <= input1.EndRow && v1.Column <= input1.EndColumn && v1.Row > -1 && v1.Column > -1) val1 = input1.Value[v1.Row, v1.Column]; else val1 = output.NoDataValue; output.Value[i, j] = val1; } else { output.Value[i, j] = output.NoDataValue; } if (cancelProgressHandler.Cancel) return false; } int current = Convert.ToInt32(Math.Round(i * 100D / max)); //only update when increment in percentage if (current > previous) cancelProgressHandler.Progress("", current, current + TextStrings.progresscompleted); previous = current; } //output = Temp; output.Save(); return true; }
/// <summary> /// Executes the ReSample Opaeration tool programaticaly /// Ping deleted the static property for external testing /// </summary> /// <param name="input1">The input raster</param> /// <param name="oldCellSize">The size of the cells Hight</param> /// <param name="newCellSize">The size of the cells Width</param> /// <param name="output">The output raster</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns></returns> public bool Execute(IRaster input1, double newCellHeight, double newCellWidth, IRaster output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input1 == null || newCellWidth == 0 || output == null) { return false; } IEnvelope envelope = input1.Bounds.Envelope; //Calculate new number of columns and rows int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / newCellWidth)); int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / newCellHeight)); int previous = 0; //************OLD Method ////Create the new raster with the appropriate dimensions //Raster Temp = new Raster(); ////Temp.CreateNew(output.Filename, noOfRow, noOfCol, input1.DataType); //Temp.CreateNew(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new string[] { "" }); //Temp.CellWidth = newCellSize; //Temp.CellHeight = oldCellSize; //Temp.Xllcenter = input1.Bounds.Envelope.Minimum.X + (Temp.CellWidth / 2); //Temp.Yllcenter = input1.Bounds.Envelope.Minimum.Y + (Temp.CellHeight / 2); //*************** //create output raster output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex index1; //Loop throug every cell for new value int max = (output.Bounds.NumRows + 1); for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { //Projet the cell position to Map Coordinate cellCenter = output.CellToProj(i, j); index1=input1.ProjToCell(cellCenter); double val; if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1) { if (input1.Value[index1.Row, index1.Column] == input1.NoDataValue) val = output.NoDataValue; else val = input1.Value[index1.Row, index1.Column]; } else val = output.NoDataValue; output.Value[i, j] = val; if (cancelProgressHandler.Cancel) return false; } int current = Convert.ToInt32(Math.Round(i * 100D / max)); //only update when increment in persentage if (current > previous) cancelProgressHandler.Progress("", current, current + TextStrings.progresscompleted); previous = current; } //output = Temp; output.Save(); return true; }
/// <summary> /// Executes the Union Opaeration tool programaticaly /// </summary> /// <param name="self">The input are feature set</param> /// <param name="other">The second input feature set</param> /// <param name="output">The output feature set</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns></returns> public bool Execute( IFeatureSet self, IFeatureSet other, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (self == null || other == null || output == null) { return false; } IFeatureSet tempOutput = self.Intersection(other, FieldJoinType.All, null); IFeatureSet tempFeatureSet = self.CombinedFields(other); int previous = 0; int max = self.Features.Count; // Take (Self-Intersect Featureset) List<IFeature> intersectList; for (int i = 0; i < self.Features.Count; i++) { intersectList = other.Select(self.Features[i].Envelope.ToExtent()); foreach (IFeature feat in intersectList) { if (cancelProgressHandler.Cancel) { return false; } self.Features[i].Difference(feat, tempFeatureSet, FieldJoinType.LocalOnly); } if (Math.Round(i * 40D / max) <= previous) { continue; } previous = Convert.ToInt32(Math.Round(i * 40D / max)); cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } max = other.Features.Count; // Take (Other-Intersect Featureset) for (int i = 0; i < other.Features.Count; i++) { intersectList = self.Select(other.Features[i].Envelope.ToExtent()); foreach (IFeature feat in intersectList) { if (cancelProgressHandler.Cancel) { return false; } other.Features[i].Difference(feat, tempFeatureSet, FieldJoinType.LocalOnly); } if (Math.Round((i * 40D / max) + 40D) <= previous) { continue; } previous = Convert.ToInt32(Math.Round((i * 40D / max) + 40D)); cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } max = tempFeatureSet.Features.Count; output.CopyTableSchema(tempFeatureSet); // Add the individual feature to output for (int i = 0; i < tempFeatureSet.Features.Count; i++) { output.Features.Add(tempFeatureSet.Features[i]); if (Math.Round((i * 10D / max) + 80D) <= previous) { continue; } previous = Convert.ToInt32(Math.Round((i * 10D / max) + 80D)); if (cancelProgressHandler.Cancel) { return false; } cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } max = tempOutput.Features.Count; // Add the Intersect feature to output for (int i = 0; i < tempOutput.Features.Count; i++) { output.Features.Add(tempOutput.Features[i]); if (cancelProgressHandler.Cancel) { return false; } if (Math.Round((i * 10D / max) + 90D) <= previous) { continue; } previous = Convert.ToInt32(Math.Round((i * 10D / max) + 90D)); cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } output.SaveAs(output.Filename, true); return true; }
/// <summary> /// Finds the average slope in the given polygons. /// </summary> /// <param name="ras">The dem Raster(Grid file).</param> /// <param name="zFactor">The scaler factor</param> /// <param name="poly">The flow poly shapefile path.</param> /// <param name="output">The resulting DEM of slopes</param> /// <param name="cancelProgressHandler">The progress handler.</param> public bool Execute( IRaster ras, double zFactor, IFeatureSet poly, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (ras == null || poly == null || output == null) { return false; } output.FeatureType = poly.FeatureType; foreach (IFeature f in poly.Features) { output.Features.Add(f); } output.DataTable.Columns.Add("FID", typeof(int)); output.DataTable.Columns.Add(TextStrings.AveSlope, typeof(Double)); IRaster slopeGrid = new Raster { DataType = ras.DataType, Bounds = ras.Bounds }; // FeatureSet polyShape = new FeatureSet(); int previous = 0; if (Slope(ref ras, zFactor, false, ref slopeGrid, cancelProgressHandler) == false) { return false; } int shapeCount = output.Features.Count; int[] areaCount = new int[shapeCount]; double[] areaTotal = new double[shapeCount]; double[] areaAve = new double[shapeCount]; double dxHalf = slopeGrid.CellWidth / 2; double dyHalf = slopeGrid.CellHeight / 2; // check whether those two envelope are intersect if (ras.Extent.Intersects(output.Extent) == false) { return false; } RcIndex start = slopeGrid.ProjToCell(output.Extent.MinX, output.Extent.MaxY); RcIndex stop = slopeGrid.ProjToCell(output.Extent.MaxX, output.Extent.MinY); int rowStart = start.Row; int colStart = start.Column; int rowStop = stop.Row; int colStop = stop.Column; for (int row = rowStart - 1; row < rowStop + 1; row++) { int current = Convert.ToInt32((row - rowStart + 1) * 100.0 / (rowStop + 1 - rowStart + 1)); // only update when increment in percentage if (current > previous + 5) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); previous = current; } for (int col = colStart - 1; col < colStop + 1; col++) { Coordinate cent = slopeGrid.CellToProj(row, col); double xCent = cent.X; double yCent = cent.Y; for (int shpindx = 0; shpindx < output.Features.Count; shpindx++) { IFeature tempFeat = output.Features[shpindx]; Point pt1 = new Point(xCent, yCent); Point pt2 = new Point(xCent - dxHalf, yCent - dyHalf); Point pt3 = new Point(xCent + dxHalf, yCent - dyHalf); Point pt4 = new Point(xCent + dxHalf, yCent + dyHalf); Point pt5 = new Point(xCent - dxHalf, yCent + dyHalf); if ((((!tempFeat.Covers(pt1) && !tempFeat.Covers(pt2)) && !tempFeat.Covers(pt3)) && !tempFeat.Covers(pt4)) && !tempFeat.Covers(pt5)) { continue; } areaCount[shpindx]++; areaTotal[shpindx] += slopeGrid.Value[row, col] / 100; if (cancelProgressHandler.Cancel) { return false; } } } } for (int shpindx = 0; shpindx < output.Features.Count; shpindx++) { if (areaCount[shpindx] == 0) { areaAve[shpindx] = 0; } else { areaAve[shpindx] = areaTotal[shpindx] / areaCount[shpindx]; } output.Features[shpindx].DataRow["FID"] = shpindx; output.Features[shpindx].DataRow[TextStrings.AveSlope] = areaAve[shpindx]; } poly.Close(); slopeGrid.Close(); output.SaveAs(output.Filename, true); return true; }
/// <summary> /// Clips a raster with a polygon feature /// </summary> /// <param name="polygon">The clipping polygon feature</param> /// <param name="input">The input raster object</param> /// <param name="outputFileName">the output raster file name</param> /// <param name="cancelProgressHandler">Progress handler for reporting progress status and cancelling the operation</param> /// <remarks>We assume there is only one part in the polygon. /// Traverses the raster with a vertical scan line from left to right, bottom to top</remarks> /// <returns></returns> public static IRaster ClipRasterWithPolygon(IFeature polygon, IRaster input, string outputFileName, ICancelProgressHandler cancelProgressHandler = null) { //if the polygon is completely outside the raster if (!input.ContainsFeature(polygon)) return input; if (cancelProgressHandler != null) cancelProgressHandler.Progress(null, 16, "Retrieving the borders."); List<Border> borders = GetBorders(polygon); if (cancelProgressHandler != null) cancelProgressHandler.Progress(null, 33, "Copying raster."); //create output raster IRaster output = Raster.CreateRaster(outputFileName, input.DriverCode, input.NumColumns, input.NumRows, 1, input.DataType, new[] { string.Empty }); output.Bounds = input.Bounds.Copy(); output.NoDataValue = input.NoDataValue; if (input.CanReproject) { output.Projection = input.Projection; } // set all initial values of Output to NoData for (int i = 0; i < output.NumRows; i++) { for (int j = 0; j < output.NumColumns; j++) { output.Value[i, j] = output.NoDataValue; } } double xStart = GetXStart(polygon, output); int columnStart = GetStartColumn(polygon, output); //get the index of first column double xCurrent = xStart; ProgressMeter pm = new ProgressMeter(cancelProgressHandler, "Clipping Raster", output.NumColumns); pm.StepPercent = 5; pm.StartValue = 33; int col = 0; for (int columnCurrent = columnStart; columnCurrent < output.NumColumns; columnCurrent++) { xCurrent = xStart + col * output.CellWidth; var intersections = GetYIntersections(borders, xCurrent); intersections.Sort(); ParseIntersections(intersections, xCurrent, columnCurrent, output, input); // update progess meter pm.CurrentValue = xCurrent; //update counter col++; // cancel if requested if (cancelProgressHandler != null && cancelProgressHandler.Cancel) return null; } output.Save(); return output; }
/// <summary> /// Executes the Raster distance calculation /// Ping Yang deleted static for external testing 10/2010 /// </summary> /// <param name="input">The input raster</param> /// <param name="output">The output raster</param> /// <param name="maxDistance">The maximum distance value. Cells with a larger distance to nearest /// target cell than maxDistance will be assigned 'no data' value.</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns>true if execution successful, false otherwise</returns> public bool Execute(IRaster input, IRaster output, double maxDistance, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || output == null) { return false; } // Creates the output raster with the same bounds as the input RasterBounds bounds = (RasterBounds)input.Bounds.Copy(); output = Raster.CreateRaster( output.Filename, string.Empty, bounds.NumColumns, bounds.NumRows, 1, typeof(int), new[] { string.Empty }); // output.CreateNew(output.Filename, "", bounds.NumColumns, bounds.NumRows, 1, typeof(int), new string[] { "" }); // output = Raster.CreateNewRaster(output.Filename, bounds.NumRows, bounds.NumColumns, RasterDataTypes.INTEGER); output.Bounds = bounds; // internally we reference output as an integer type raster. Raster<int> outRaster = output as Raster<int>; if (outRaster != null) { int numColumns = outRaster.NumColumns; int numRows = outRaster.NumRows; int lastUpdate = 0; // declare two jagged arrays for storing the (Rx, Ry) vectors. // rX is distance from current cell to nearest target cell measured in the x-direction // rY is distance from current cell to nearest target cell measured in the y-direction // the actual distance can be calculated as sqrt(rX^2 + rY^2). // in the resulting distance raster we store the squared distance as well as the rX, rY relative coordinates // to improve computation speed int[][] aRx = new int[numRows][]; int[][] aRy = new int[numRows][]; int[][] aSqDist = new int[numRows][]; const int infD = int.MaxValue; const int targetVal = 0; // initialize the arrays for (int i = 0; i < numRows; i++) { aRx[i] = new int[numColumns]; aRy[i] = new int[numColumns]; aSqDist[i] = new int[numColumns]; ReadInputRow(input, i, aSqDist[i], targetVal, infD); } // ******************************************************************* // raster distance calculation pass one - top to bottom, left to right // ******************************************************************* // int[] row1 = new int[numColumns]; // int[] row2 = new int[numColumns]; int[] aNcels = new int[4]; // the values of four neighbouring cells (W, NW, N, NE) int[] aDiff = new int[4]; // the | y coordinate distances to nearest target cell for (int row = 1; row < numRows; row++) { ////read the row from input raster // ReadInputRow(input, rowIndex, row2, targetVal, infD); for (int col = 1; col < numColumns - 1; col++) { int val = aSqDist[row][col]; // Continue processing only if the current cell is not a target if (val == targetVal) { continue; } // read the values of the cell's neighbours aNcels[0] = aSqDist[row][col - 1]; // W aNcels[1] = aSqDist[row - 1][col - 1]; // NW aNcels[2] = aSqDist[row - 1][col]; // N aNcels[3] = aSqDist[row - 1][col + 1]; // NE // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell aDiff[0] = (aNcels[0] < infD) ? aNcels[0] + 2 * aRx[row][col - 1] + 1 : infD; aDiff[1] = (aNcels[1] < infD) ? aNcels[1] + 2 * (aRx[row - 1][col - 1] + aRy[row - 1][col - 1] + 1) : infD; aDiff[2] = (aNcels[2] < infD) ? aNcels[2] + 2 * aRy[row - 1][col] + 1 : infD; aDiff[3] = (aNcels[3] < infD) ? aNcels[3] + 2 * (aRx[row - 1][col + 1] + aRy[row - 1][col + 1] + 1) : infD; // find neighbouring cell with minimum distance difference int minDiff = aDiff[0]; int minDiffCell = 0; for (int i = 1; i < 4; i++) { if (aDiff[i] < minDiff) { minDiff = aDiff[i]; minDiffCell = i; } } // if a neighbouring cell with known distance was found: if (minDiff < infD) { // assign the minimum euclidean distance aSqDist[row][col] = minDiff; // update the (rX, rY) cell-to-nearest-target vector switch (minDiffCell) { case 0: // W aRx[row][col] = aRx[row][col - 1] + 1; aRy[row][col] = aRy[row][col - 1]; break; case 1: // NW aRx[row][col] = aRx[row - 1][col - 1] + 1; aRy[row][col] = aRy[row - 1][col - 1] + 1; break; case 2: // N aRx[row][col] = aRx[row - 1][col]; aRy[row][col] = aRy[row - 1][col] + 1; break; case 3: // NE aRx[row][col] = aRx[row - 1][col + 1] + 1; aRy[row][col] = aRy[row - 1][col + 1] + 1; break; } } // end of update (rX, rY) cell-to-nearest-target vector } // end or current row processing - report progress int percent = (int)(row / (double)numRows * 100f); if (percent > lastUpdate) { lastUpdate += 1; cancelProgressHandler.Progress( string.Empty, lastUpdate, TextStrings.Pass1 + lastUpdate + TextStrings.progresscompleted); if (cancelProgressHandler.Cancel) { return false; } } } // ******************************************************************* // end of first pass for loop // ******************************************************************* // ******************************************************************* // raster distance calculation PASS TWO - bottom to top, right to left // ******************************************************************* lastUpdate = 0; for (int row = numRows - 2; row > 0; row--) { for (int col = numColumns - 2; col > 0; col--) { int val = aSqDist[row][col]; // Continue processing only if the current cell is not a target if (val == targetVal) { continue; } // read the values of the cell's neighbours aNcels[0] = aSqDist[row][col + 1]; // E aNcels[1] = aSqDist[row + 1][col + 1]; // SE aNcels[2] = aSqDist[row + 1][col]; // S aNcels[3] = aSqDist[row + 1][col - 1]; // SW // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell aDiff[0] = (aNcels[0] < infD) ? aNcels[0] + 2 * aRx[row][col + 1] + 1 : infD; aDiff[1] = (aNcels[1] < infD) ? aNcels[1] + 2 * (aRx[row + 1][col + 1] + aRy[row + 1][col + 1] + 1) : infD; aDiff[2] = (aNcels[2] < infD) ? aNcels[2] + 2 * aRy[row + 1][col] + 1 : infD; aDiff[3] = (aNcels[3] < infD) ? aNcels[3] + 2 * (aRx[row + 1][col - 1] + aRy[row + 1][col - 1] + 1) : infD; // find neighbouring cell with minimum distance difference int minDiff = aDiff[0]; int minDiffCell = 0; for (int i = 1; i < 4; i++) { if (aDiff[i] < minDiff) { minDiff = aDiff[i]; minDiffCell = i; } } // if a neighbouring cell with known distance smaller than current known distance was found: if (minDiff < val) { // assign the minimum euclidean distance aSqDist[row][col] = minDiff; // update the (rX, rY) cell-to-nearest-target vector switch (minDiffCell) { case 0: // E aRx[row][col] = aRx[row][col + 1] + 1; aRy[row][col] = aRy[row][col + 1]; break; case 1: // SE aRx[row][col] = aRx[row + 1][col + 1] + 1; aRy[row][col] = aRy[row + 1][col + 1] + 1; break; case 2: // S aRx[row][col] = aRx[row + 1][col]; aRy[row][col] = aRy[row + 1][col] + 1; break; case 3: // SW aRx[row][col] = aRx[row + 1][col - 1] + 1; aRy[row][col] = aRy[row + 1][col - 1] + 1; break; } } // end of update (rX, rY) cell-to-nearest-target vector } // Write row to output raster WriteOutputRow(outRaster, row, aSqDist[row]); // Report progress int percent = (int)(row / (double)numRows * 100f); if (percent > lastUpdate) { lastUpdate += 1; cancelProgressHandler.Progress( string.Empty, lastUpdate, TextStrings.Pass2 + lastUpdate + TextStrings.progresscompleted); if (cancelProgressHandler.Cancel) { return false; } } } } // ******************************************************************* // end of second pass proximity calculation loop // ******************************************************************* // save output raster output.Save(); return true; }
/// <summary> /// Executes the Erase Opaeration tool programaticaly /// </summary> /// <param name="self">The input feature that is to be erased</param> /// <param name="other">The other feature defining the area to remove</param> /// <param name="output">The resulting erased content</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns>Boolean, true if the operation was a success</returns> public static bool Execute( IFeatureSet self, IFeatureSet other, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (self == null || other == null || output == null) { return false; } int previous; int max = self.Features.Count * other.Features.Count; output.CopyTableSchema(self); // Fill the 1st Featureset fields IFeatureSet tempSet = self.CombinedFields(other); // go through every feature in 1st featureSet for (int i = 0; i < self.Features.Count; i++) { // go through every feature in 2nd featureSet for (int j = 0; j < other.Features.Count; j++) { self.Features[i].Difference(other.Features[j], tempSet, FieldJoinType.All); previous = Convert.ToInt32(Math.Round(i * j * 50D / max)); if (cancelProgressHandler.Cancel) { return false; } cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } } // Add to the Output Feature Set for (int a = 0; a < tempSet.Features.Count; a++) { output.Features.Add(tempSet.Features[a]); previous = Convert.ToInt32(Math.Round((a * 50D / tempSet.Features.Count) + 50D)); if (cancelProgressHandler.Cancel) { return false; } cancelProgressHandler.Progress(string.Empty, previous, previous + TextStrings.progresscompleted); } output.SaveAs(output.Filename, true); // add to map? return true; }
/// <summary> /// Executes the generate centroid FeatureSet Opaeration tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute(IFeatureSet input1, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || output == null) { return false; } bool multiPoint = false; foreach (IFeature f1 in input1.Features) { if (f1.NumGeometries > 1) { multiPoint = true; } } output.FeatureType = multiPoint == false ? FeatureType.Point : FeatureType.MultiPoint; int previous = 0; int i = 0; int maxFeature = input1.Features.Count; output.CopyTableSchema(input1); foreach (IFeature f in input1.Features) { if (cancelProgressHandler.Cancel) { return false; } IFeature fnew = new Feature(f.Centroid()); // Add the centroid to output output.Features.Add(fnew); fnew.CopyAttributes(f); int current = Convert.ToInt32(Math.Round(i * 100D / maxFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; i++; } output.SaveAs(output.Filename, true); return true; }
/// <summary> /// Finds the average slope in the given polygons. /// </summary> /// <param name="poly">The Polygon.</param> /// <param name="output">The Raster.</param> /// <param name="progress">The progress handler.</param> public bool Execute(IFeatureSet poly, int noOfRow, int noOfCol, int selectionIndex, IRaster output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (poly == null || output == null) { return false; } if (poly.FeatureType != FeatureTypes.Polygon) return false; //double CellSize = poly.Envelope.Width / 255; //int noOfRow = Convert.ToInt32(poly.Envelope.Height / CellSize); //int noOfCol = Convert.ToInt32(poly.Envelope.Width / CellSize); output=Raster.Create(output.Filename,"",noOfCol,noOfRow,1,typeof(int),new string[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, poly.Envelope); output.Bounds=bound; output.NoDataValue = -1; int current, previous = 0; double area = 0.0, previousArea = 0.0; double hCellWidth = output.CellWidth / 2; double hCellHeight = output.CellHeight / 2; ICoordinate[] coordinateCell=new Coordinate[4]; int polyIndex = -1; bool cover = false; //IEnvelope env=null; for (int i = 0; i < output.NumRows; i++) { current = Convert.ToInt32(i*100 / output.NumRows); //only update when increment in percentage if (current > previous+5) { cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed"); previous = current; } for (int j = 0; j < output.NumColumns; j++) { polyIndex = -1; area = 0.0; previousArea = 0.0; cover=false; ICoordinate cordinate=null; cordinate = output.CellToProj(i, j); //make the center of cell as point geometry IPoint pt=new Point(cordinate); for(int f=0;f<poly.Features.Count;f++) { if (selectionIndex == 0) { if (poly.Features[f].Covers(pt)) { output.Value[i, j] = f; cover = true; break; } if (cancelProgressHandler.Cancel == true) return false; } else //process area based selection { ICoordinate tempCo = new Coordinate(cordinate.X - hCellWidth, cordinate.Y - hCellHeight); coordinateCell[0] = tempCo; tempCo = new Coordinate(cordinate.X + hCellWidth, cordinate.Y - hCellHeight); coordinateCell[1] = tempCo; tempCo = new Coordinate(cordinate.X + hCellWidth, cordinate.Y + hCellHeight); coordinateCell[2] = tempCo; tempCo = new Coordinate(cordinate.X - hCellWidth, cordinate.Y + hCellHeight); coordinateCell[3] = tempCo; List<ICoordinate> ListCellCordinate = new List<ICoordinate>(); ListCellCordinate = coordinateCell.ToList<ICoordinate>(); IFeature cell = new Feature(FeatureTypes.Polygon, ListCellCordinate); IFeature commonFeature=poly.Features[f].Intersection(cell); if (commonFeature == null) continue; area=commonFeature.Area(); if (area > previousArea) { polyIndex = f; cover = true; previousArea = area; } if (cancelProgressHandler.Cancel == true) return false; } } if (cover == true) { if (selectionIndex == 1) output.Value[i, j] = polyIndex; } else output.Value[i, j] = output.NoDataValue; } } //output.SaveAs(output.Filename); output.Save(); //output.SaveAs(output.Filename); return true; }
/// <summary> /// Executes the ClipPolygonWithPolygon tool with programatic input /// </summary> /// <param name="input">The input feature set to clip</param> /// <param name="input2">The input polygon feature set to clip with</param> /// <param name="output">The output feature set</param> /// <param name="cancelProgressHandler">The progress handler for progress message updates</param> /// <returns></returns> /// Ping delete "static" for external testing public bool Execute( IFeatureSet input, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || input2 == null || output == null) { cancelProgressHandler.Progress(string.Empty, 100, TextStrings.Oneparameterinnull); return false; } if (input2.FeatureType != FeatureType.Polygon) { cancelProgressHandler.Progress(string.Empty, 100, TextStrings.secondinputlayer); return false; } output.FeatureType = input.FeatureType; // we add all the old features to output IFeatureSet tempoutput = input.Intersection(input2, FieldJoinType.LocalOnly, cancelProgressHandler); // We add all the fields foreach (DataColumn inputColumn in tempoutput.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } foreach (var fe in tempoutput.Features) { output.Features.Add(fe); } output.SaveAs(output.Filename, true); return true; }
/// <summary> /// Executes the overwrite feature Opaeration tool programaticaly. /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="index">The Index to overwrite</param> /// <param name="input2">The input2 featureSet which has the new feature to overwrite.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute(IFeatureSet input1,int index,IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input1 == null|| input2 == null || output == null) { return false; } if (cancelProgressHandler.Cancel) return false; IFeature newFeature = input2.Features[0]; output.FeatureType = input1.FeatureType; foreach (IFeature f in input1.Features) output.Features.Add(f); if (index > -1) { if (index < output.Features.Count) { output.Features.RemoveAt(index); output.Features.Insert(index, newFeature); } } output.SaveAs(output.Filename, true); cancelProgressHandler.Progress("", 100, 100 + TextStrings.progresscompleted); return true; }
/// <summary> /// Executes the ClipPolygonWithLine Operation tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input Polygon FeatureSet.</param> /// <param name="input2">The input Polyline FeatureSet.</param> /// <param name="output">The output Polygon FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } if (cancelProgressHandler.Cancel) { return false; } IFeature polygon = input1.Features[0]; IFeature line = input2.Features[0]; IFeatureSet resultFs = new FeatureSet(FeatureType.Polygon); int previous = 0; if (DoClipPolygonWithLine(ref polygon, ref line, ref output) == false) { throw new SystemException(TextStrings.Exceptioninclipin); } int intFeature = output.Features.Count; for (int i = 0; i < intFeature; i++) { Polygon poly = new Polygon(output.Features[i].Coordinates); resultFs.AddFeature(poly); int current = Convert.ToInt32(Math.Round(i * 100D / intFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } cancelProgressHandler.Progress(string.Empty, 100, 100 + TextStrings.progresscompleted); resultFs.SaveAs(output.Filename, true); return true; }
/// <summary> /// Executes the Erase Opaeration tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="input2">The input Expression string to select features to Delete.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, string input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } if (cancelProgressHandler.Cancel) { return false; } int previous = 0; List<IFeature> fetList = input1.SelectByAttribute(input2); int noOfFeaturesToDelete = fetList.Count; int noOfFeatures = input1.Features.Count; output.FeatureType = input1.FeatureType; foreach (IFeature f in input1.Features) { output.Features.Add(f); } // Go through every item in the list for (int i = 0; i < noOfFeaturesToDelete; i++) { int current = Convert.ToInt32(Math.Round(i * 100D / noOfFeaturesToDelete)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; // loop through every item in the list for (int j = 0; j < noOfFeatures; j++) { // Select the Feature from Feature set to detlete if (fetList[i] == input1.Features[j]) { output.Features.Remove(input1.Features[j]); } } } output.SaveAs(output.Filename, true); return true; }
public bool RasterMath(IRaster input1, IRaster input2, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } Extent envelope = UnionEnvelope(input1, input2); // Figures out which raster has smaller cells IRaster smallestCellRaster = input1.CellWidth < input2.CellWidth ? input1 : input2; // Given the envelope of the two rasters we calculate the number of columns / rows int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / smallestCellRaster.CellWidth)); int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / smallestCellRaster.CellHeight)); // create output raster output = Raster.CreateRaster( output.Filename, string.Empty, noOfCol, noOfRow, 1, typeof(int), new[] { string.Empty }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex v1; RcIndex v2; int previous = 0; int max = output.Bounds.NumRows + 1; for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { Coordinate cellCenter = output.CellToProj(i, j); v1 = input1.ProjToCell(cellCenter); double val1; if (v1.Row <= input1.EndRow && v1.Column <= input1.EndColumn && v1.Row > -1 && v1.Column > -1) { val1 = input1.Value[v1.Row, v1.Column]; } else { val1 = input1.NoDataValue; } v2 = input2.ProjToCell(cellCenter); double val2; if (v2.Row <= input2.EndRow && v2.Column <= input2.EndColumn && v2.Row > -1 && v2.Column > -1) { val2 = input2.Value[v2.Row, v2.Column]; } else { val2 = input2.NoDataValue; } if (val1 == input1.NoDataValue && val2 == input2.NoDataValue) { output.Value[i, j] = output.NoDataValue; } else if (val1 != input1.NoDataValue && val2 == input2.NoDataValue) { output.Value[i, j] = output.NoDataValue; } else if (val1 == input1.NoDataValue && val2 != input2.NoDataValue) { output.Value[i, j] = output.NoDataValue; } else { output.Value[i, j] = Operation(val1, val2); } if (cancelProgressHandler.Cancel) { return false; } } int current = Convert.ToInt32(Math.Round(i * 100D / max)); // only update when increment in persentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } // output = Temp; output.Save(); return true; }
/// <summary> /// Executes the slope generation raster. /// </summary> /// <param name="ras">The input altitude raster.</param> /// <param name="inZFactor">A multiplicative scaling factor to be applied to the elevation values before calculating the slope.</param> /// <param name="slopeInPercent">If this is true, the resulting slopes are returned as percentages.</param> /// <param name="output">The output slope raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>True if the method worked.</returns> public bool Execute( IRaster ras, double inZFactor, bool slopeInPercent, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (ras == null || output == null) { return false; } try { int noOfCol = ras.NumColumns; int noOfRow = ras.NumRows; output = Raster.CreateRaster( output.Filename, string.Empty, noOfCol, noOfRow, 1, typeof(double), new[] { string.Empty }); output.NoDataValue = ras.NoDataValue; // output.Bounds = ras.Bounds.Copy(); output.Bounds = ras.Bounds; int previous = 0; for (int i = 0; i < output.NumRows; i++) { int current = Convert.ToInt32(Math.Round(i * 100D / output.NumRows)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; for (int j = 0; j < output.NumColumns; j++) { if (i > 0 && i < output.NumRows - 1 && j > 0 && j < output.NumColumns - 1) { double z1 = ras.Value[i - 1, j - 1]; double z2 = ras.Value[i - 1, j]; double z3 = ras.Value[i - 1, j + 1]; double z4 = ras.Value[i, j - 1]; double z5 = ras.Value[i, j + 1]; double z6 = ras.Value[i + 1, j - 1]; double z7 = ras.Value[i + 1, j]; double z8 = ras.Value[i + 1, j + 1]; // 3rd Order Finite Difference slope algorithm double dZdX = inZFactor * ((z3 - z1) + 2 * (z5 - z4) + (z8 - z6)) / (8 * ras.CellWidth); double dZdY = inZFactor * ((z1 - z6) + 2 * (z2 - z7) + (z3 - z8)) / (8 * ras.CellHeight); double slope = Math.Atan(Math.Sqrt((dZdX * dZdX) + (dZdY * dZdY))) * (180 / Math.PI); // change to radious and in persentage if (slopeInPercent) { slope = Math.Tan(slope * Math.PI / 180) * 100; } output.Value[i, j] = slope; if (cancelProgressHandler.Cancel) { return false; } } else { output.Value[i, j] = output.NoDataValue; } if (cancelProgressHandler.Cancel) { return false; } } } // output = Temp; if (output.IsFullyWindowed()) { output.Save(); return true; } return false; } catch (Exception ex) { // throw new SystemException("Error in Slope: ", ex); throw new SystemException(ex.ToString()); } }
/// <summary> /// Executes the Area tool with programatic input /// Ping delete static for external testing /// </summary> /// <param name="input">The input raster</param> /// <param name="output">The output polygon feature set</param> /// <param name="zField">The field name containing the values to interpolate</param> /// <param name="cellSize">The double geographic size of the raster cells to create</param> /// <param name="power">The double power representing the inverse</param> /// <param name="neighborType">Fixed distance of fixed number of neighbors</param> /// <param name="pointCount">The number of neighbors to include if the neighborhood type /// is Fixed</param> /// <param name="distance">Points further from the raster cell than this distance are not included /// in the calculation if the neighborhood type is Fixed Distance.</param> /// <param name="output">The output raster where values are stored. The filename is used, but the number /// of rows and columns will be computed from the cellSize and input featureset</param> /// <param name="cancelProgressHandler">A progress handler for receiving progress messages</param> /// <returns>A boolean, true if the IDW process worked correctly</returns> public bool Execute(IFeatureSet input, string zField, double cellSize, double power, NeighborhoodType neighborType, int pointCount, double distance, IRaster output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input == null || output == null) return false; //If the cellSize is 0 we calculate a cellsize based on the input extents if (cellSize == 0) cellSize = input.Envelope.Width / 255; //Defines the dimesions and position of the raster int numColumns = Convert.ToInt32(Math.Round(input.Envelope.Width / cellSize)); int numRows = Convert.ToInt32(Math.Round(input.Envelope.Height / cellSize)); output = Raster.Create(output.Filename, "",numColumns, numRows, 1, typeof(double), new[] {""} ); output.CellHeight = cellSize; output.CellWidth = cellSize; output.Xllcenter = input.Envelope.Minimum.X + (cellSize/2); output.Yllcenter = input.Envelope.Minimum.Y + (cellSize/2); //Used to calculate progress int lastUpdate=0; //Populates the KD tree MapWindow.Analysis.Topology.KDTree.KDTree kd = new MapWindow.Analysis.Topology.KDTree.KDTree(2); List<int> randomList = new List<int>(); for (int i = 0; i < input.Features.Count; i++) { randomList.Add(i); } Random rnd = new Random(); List<int> completed = new List<int>(); while (randomList.Count > 0) { int index = rnd.Next(0,randomList.Count -1); Coordinate coord = input.Features[randomList[index]].Coordinates[0]; while (kd.Search(coord.ToArray()) != null) coord.X = coord.X * 1.000000000000001D; kd.Insert(coord.ToArray(), input.Features[randomList[index]]); completed.Add(randomList[index]); randomList.RemoveAt(index); } System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //Makes sure we don't try to search for more points then exist if (kd.Count < pointCount) pointCount = kd.Count; if (neighborType == NeighborhoodType.FixedCount) { //we add all the old features to output for (int x = 0; x < numColumns; x++) { for (int y = 0; y < numRows; y++) { //Gets the pointCount number of cells closest to the current cell Coordinate cellCenter = output.CellToProj(y, x); Double[] pixelCoord = new double[2]; pixelCoord[0] = output.CellToProj(y, x).X; pixelCoord[1] = output.CellToProj(y, x).Y; sw.Start(); object[] result = kd.Nearest(pixelCoord, pointCount); sw.Stop(); //Sets up the IDW numerator and denominator double top = 0; double bottom = 0; foreach (object feat in result) { IFeature featurePt = feat as Feature; if (featurePt == null) continue; double distanceToCell = cellCenter.Distance(featurePt.Coordinates[0]); if (distanceToCell <= distance || distance == 0) { //If we can't convert the value to a double throw it out try { Convert.ToDouble(featurePt.DataRow[zField]); } catch { continue; } if (power == 2) { top += (1 / (distanceToCell * distanceToCell)) * Convert.ToDouble(featurePt.DataRow[zField]); bottom += (1 / (distanceToCell* distanceToCell)); } else { top += (1 / Math.Pow(distanceToCell, power)) * Convert.ToDouble(featurePt.DataRow[zField]); bottom += (1 / Math.Pow(distanceToCell, power)); } } } output.Value[y, x] = top / bottom; } //Checks if we need to update the status bar if (Convert.ToInt32(Convert.ToDouble(x*numRows ) / Convert.ToDouble(numColumns * numRows) * 100) > lastUpdate) { lastUpdate = Convert.ToInt32(Convert.ToDouble(x * numRows) / Convert.ToDouble(numColumns * numRows) * 100); cancelProgressHandler.Progress("", lastUpdate, "Cell: " + (x * numRows) + " of " + (numColumns * numRows)); if (cancelProgressHandler.Cancel) return false; } } System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds); } output.Save(); return true; }
/// <summary> /// Finds the average slope in the given polygons. /// </summary> /// <param name="gridIn">The Polygon Raster(Grid file).</param> /// <param name="polyOut">The Polygon shapefile path.</param> /// <param name="progress">The progress handler.</param> public bool Execute(IRaster gridIn, IFeatureSet polyOut, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (gridIn == null || polyOut == null) { return false; } int maxX, maxY; int current = 0; int previous = 0; double noData, currVal, currTrack; string strTrackPath; IRaster gridTrack = new Raster(); maxX = gridIn.NumRows - 1; maxY = gridIn.NumColumns - 1; noData = gridIn.NoDataValue; //strTrackPath = System.IO.Path.GetDirectoryName(strInRast) + "\\" + System.IO.Path.GetFileNameWithoutExtension(strInRast) + "_track.bgd"; gridTrack = Raster.Create("gridTrack.bgd", "", gridIn.NumColumns, gridIn.NumRows, 1, gridIn.DataType, new string[] { "" }); //gridTrack.CreateNew("gridTrack", "", gridIn.NumColumns, gridIn.NumRows, 1, gridIn.DataType, new string[] { "" }); gridTrack.Bounds = gridIn.Bounds; gridTrack.NoDataValue = gridIn.NoDataValue; polyOut.DataTable.Columns.Add("Value", typeof(int)); polyOut.DataTable.Columns.Add("Zone", typeof(string)); polyOut.DataTable.Columns.Add("Area", typeof(double)); polyOut.DataTable.Columns.Add("COMID", typeof(string)); polyOut.DataTable.Columns.Add("AveSlope", typeof(double)); for (int i = 0; i <= maxX; i++) { current = Convert.ToInt32(i * 100 / maxX); //only update when increment in percentage if (current > previous+5) { cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed"); previous = current; } for (int j = 0; j <= maxY; j++) { if (i > 0 && j > 0) { currVal = Convert.ToInt16(gridIn.Value[i, j]); currTrack = Convert.ToInt16(gridTrack.Value[i, j]); if (currVal == gridIn.NoDataValue) { gridTrack.Value[i, j] = 1; if (cancelProgressHandler.Cancel == true) return false; } else { if (currTrack == 1) { } else { formPolyFromCell(gridIn, gridTrack, i, j, polyOut, cancelProgressHandler); if (cancelProgressHandler.Cancel == true) return false; } } } else { gridTrack.Value[i, j] = gridIn.NoDataValue; } } } gridIn.Close(); gridTrack.Close(); polyOut.SaveAs(polyOut.Filename, true); polyOut.Close(); return true; }
/// <summary> /// Executes the add features Opaeration tool programaticaly. /// Ping deleted "static" for external Testing /// </summary> /// <param name="input1">The input FeatureSet.</param> /// <param name="input2">The input2 featureSet which has the new features to add.</param> /// <param name="output">The output FeatureSet.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute( IFeatureSet input1, IFeatureSet input2, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } int previous = 0; int i = 0; int maxFeature = input2.Features.Count; output.FeatureType = input1.FeatureType; foreach (IFeature f1 in input1.Features) { output.Features.Add(f1); } // go through new featureset that wanted to add. foreach (IFeature f in input2.Features) { if (cancelProgressHandler.Cancel) { return false; } if (input1.FeatureType == input2.FeatureType) { output.Features.Add(f); } int current = Convert.ToInt32(Math.Round(i * 100D / maxFeature)); // only update when increment in percentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; i++; } output.SaveAs(output.Filename, true); // cancelProgressHandler.Progress("", 100, 100.ToString() + TextStrings.progresscompleted); return true; }
/// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="cancelProgressHandler"></param> /// <returns></returns> public bool Execute(IFeatureSet input, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || output == null) { return false; } // We add all the fields foreach (DataColumn inputColumn in input.DataTable.Columns) { output.DataTable.Columns.Add(new DataColumn(inputColumn.ColumnName, inputColumn.DataType)); } // We add the area field bool addField = true; string fieldCount = string.Empty; int i = 0; while (addField) { if (output.DataTable.Columns.Contains(TextStrings.Area + fieldCount) == false) { output.DataTable.Columns.Add(new DataColumn(TextStrings.Area + fieldCount, typeof(double))); addField = false; } else { fieldCount = i.ToString(); i++; } } // we add all the old features to output for (int j = 0; j < input.Features.Count; j++) { Feature newFeature = new Feature(input.Features[j].BasicGeometry, output); foreach (DataColumn colSource in input.DataTable.Columns) { newFeature.DataRow[colSource.ColumnName] = input.Features[j].DataRow[colSource.ColumnName]; } newFeature.DataRow[TextStrings.Area + fieldCount] = MultiPolygon.FromBasicGeometry(output.Features[j].BasicGeometry).Area; // Status updates is done here cancelProgressHandler.Progress( string.Empty, Convert.ToInt32((Convert.ToDouble(j) / Convert.ToDouble(input.Features.Count)) * 100), input.Features[j].DataRow[0].ToString()); if (cancelProgressHandler.Cancel) { return false; } } output.Save(); return true; }
/// <summary> /// Executes the Erase Opaeration tool programaticaly /// Ping Yang deleted static for external testing 01/2010 /// </summary> /// <param name="input">The input raster</param> /// <param name="oldValue">The original double value representing no-data</param> /// <param name="newValue">The new double value representing no-data</param> /// <param name="output">The output raster</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns></returns> public bool Execute( IRaster input, double oldValue, double newValue, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || newValue == 0 || output == null) { return false; } Extent envelope = input.Bounds.Extent; int noOfCol = input.NumColumns; int noOfRow = input.NumRows; int previous = 0; Type dataType = input.DataType; // create output raster output = Raster.CreateRaster( output.Filename, string.Empty, noOfCol, noOfRow, 1, dataType, new[] { string.Empty }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = newValue; // Loop throug every cell int max = output.Bounds.NumRows + 1; for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { if (input.Value[i, j] == oldValue) { output.Value[i, j] = newValue; } else { output.Value[i, j] = input.Value[i, j]; } if (cancelProgressHandler.Cancel) { return false; } } int current = Convert.ToInt32(Math.Round(i * 100D / max)); // only update when increment in persentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } // output = Temp; output.Save(); return true; }
public static bool GetBuffer(IFeatureSet input, double bufferDistance, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { int previous = 0; int maxNo = input.Features.Count; for (int i = 0; i < maxNo; i++) { input.Features[i].Buffer(bufferDistance, output); //Here we update the progress int current = Convert.ToInt32(i * 100 / maxNo); if (current > previous) { cancelProgressHandler.Progress("", current, current + TextStrings.progresscompleted); previous = current; } if (cancelProgressHandler.Cancel) return false; } output.Save(); return true; }