private void Configure(IFeatureSet inFeatureSet) { FeatureType ft = inFeatureSet.FeatureType; if (ft != FeatureType.Point && ft != FeatureType.MultiPoint && ft != FeatureType.Unspecified) { throw new PointFeatureTypeException(); } if (inFeatureSet.NumRows() == 0) { MyExtent = new Extent(); } else if (inFeatureSet.NumRows() == 1) { MyExtent = inFeatureSet.Extent.Copy(); MyExtent.ExpandBy(10, 10); } else { MyExtent = inFeatureSet.Extent.Copy(); } Symbology = new PointScheme(); }
GetFeaturesBoundingBoxes(IFeatureSet featuresSet) { var res = new System.Collections.Generic.List <System.Tuple <uint, SharpSbn.DataStructures.Envelope> >( featuresSet.NumRows()); for (var i = 0; i < featuresSet.NumRows(); i++) { var feature = featuresSet.GetFeature(i); var min = feature.Envelope.Minimum; var max = feature.Envelope.Maximum; res.Add(System.Tuple.Create((uint)feature.Fid, new SharpSbn.DataStructures.Envelope( min.X, max.X, min.Y, max.Y))); } return(res); }
/// <summary> /// Removes the feature with the specified index. /// </summary> /// <param name="index">Removes the feature from the specified index location.</param> public void RemoveAt(int index) { // Get shape range so we can update header smartly int startIndex = index; IFeatureSet ifs = Select(null, null, ref startIndex, 1); if (ifs.NumRows() > 0) { var shx = new ShapefileIndexFile(); shx.Open(Filename); shx.Shapes.RemoveAt(index); shx.Save(); AttributeTable dbf = GetAttributeTable(Filename); dbf.RemoveRowAt(index); if (_trackDeletedRows) { _deletedRows = dbf.DeletedRows; } // Update extent in header if feature being deleted is NOT completely contained var hdr = new ShapefileHeader(Filename); Envelope featureEnv = ifs.GetFeature(0).Geometry.EnvelopeInternal; if (featureEnv.MinX <= hdr.Xmin || featureEnv.MaxX >= hdr.Xmax || featureEnv.MaxY >= hdr.Ymax || featureEnv.MinY <= hdr.Ymin) { UpdateExtents(); } // Update the Quadtree Quadtree?.Remove(featureEnv, index); } }
public static void CorrectionCentroid() { //中心点数据 List <Coordinate> centroidPoints = new List <Coordinate>(80); StreamReader sr = new StreamReader(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\中心点80.txt"); sr.ReadLine();//读取标题行 while (!sr.EndOfStream) { string[] line = sr.ReadLine().Split(','); centroidPoints.Add(new Coordinate(double.Parse(line[1]), double.Parse(line[2]))); } sr.Close(); //Bus数据,并且构造KD树 KdTree myKdtree = new KdTree(2); IFeatureSet busFS = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\BusStopGauss.shp"); List <Coordinate> busStopPoints = new List <Coordinate>(busFS.NumRows()); HashSet <int> checkDuplicate = new HashSet <int>(); foreach (var item in busFS.Features) { var c = item.Coordinates[0]; busStopPoints.Add(c); myKdtree.Insert(new double[] { c.X, c.Y }, item); } Console.WriteLine("数据读取完毕,开始纠正数据"); IFeatureSet newCentroid = new FeatureSet(FeatureType.Point); newCentroid.Name = "优化过的中心点"; newCentroid.Projection = ProjectionInfo.FromEpsgCode(GAUSS_EPSG); int count = 0; foreach (var item in centroidPoints) { var nearsestBus = myKdtree.Nearest(new double[] { item.X, item.Y }, 3); bool addSuccess = false; IFeature addFeature = null; for (int i = 0; i < 3; i++) { IFeature f = nearsestBus[i] as IFeature; if (f.Coordinates[0].Distance(item) < 100) { if (checkDuplicate.Add(f.Fid)) { addFeature = newCentroid.AddFeature(f.BasicGeometry); addSuccess = true; } } } if (!addSuccess) { addFeature = newCentroid.AddFeature(new Point(item)); count++; } } Console.WriteLine("数据优化结束,共有{0}个数据没有优化", count); newCentroid.SaveAs("newCentroid2.shp", true); Console.ReadKey(); }
private void ProxyCreateRandom() { // Default sample size int pSample = 25; var mSelectedLayer = ExtFunctions.GetSelectedLayer(theMap); IFeatureLayer mLayer = null; if (mSelectedLayer == null || !(mSelectedLayer is IFeatureLayer)) { this.Log("No feature layer selected, please select a layer and try again."); return; } mLayer = (IFeatureLayer)mSelectedLayer; var mFrmInputBox = new frmInputBox("Specify size of sample", "Please specify number of items to be included in the output file", pSample); if (DialogResult.OK == mFrmInputBox.ShowDialog()) { if (mFrmInputBox.GetAsInteger() != null) { pSample = (int)mFrmInputBox.GetAsInteger(); Utilities.LogDebug("Using specified sample size: " + pSample); } else if (mFrmInputBox.GetAsPercent() != null) { int mPercentage = (int)mFrmInputBox.GetAsPercent(); IFeatureSet mFeatureSet = mLayer.DataSet; pSample = (int)Math.Floor(((double)mPercentage * (double)mFeatureSet.NumRows()) / 100); Utilities.LogDebug("Using " + mPercentage + "% : " + pSample); } else { Utilities.LogDebug("Using default sample size: " + pSample); } this.Log(pSample.ToString()); if (pSample > 0) { var mRndFeatureSet = ExtFunctions.CreateRandomSelection(mLayer, pSample); if (mRndFeatureSet == null) { Utilities.LogDebug("Creation of random selection layer failed"); return; } var mLayer2 = (IFeatureLayer)ExtFunctions.GetFeatureLayer(theMap.Layers, mRndFeatureSet, mLayer.LegendText + " : random", ExtFunctions.CopyLayerSymbolizer(mLayer), mLayer.Projection); ExtFunctions.AddLabelsForFeatureLayer(mLayer2, "Address unit numbers", "#[ADDRESSUNITNR], [ROADNAME_EN]", GoogleMapsColors.BoundaryMajor); } } }
public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler) { IFeatureSet fs = null; if (!TypeConverterEx.IsNull(PointFeatureFileName) && File.Exists(PointFeatureFileName)) { fs = FeatureSet.Open(PointFeatureFileName); } if (fs != null) { var npt = fs.NumRows(); Coordinate[] coors = new Coordinate[npt]; int progress = 0; for (int i = 0; i < npt; i++) { var geo_pt = fs.GetFeature(i).Geometry; coors[i] = geo_pt.Coordinate; } var time = _TimeVariable.GetData() as float[]; var xx = _XVariable.GetData() as float[]; var yy = _YVariable.GetData() as float[]; var nc_array = _SelectedVariable.GetData() as float[, , ]; int nstep = time.Count(); var mat_out = new DataCube <float>(1, time.Length, npt); mat_out.Name = OutputMatrix; mat_out.Variables = new string[] { _SelectedVariableName }; mat_out.DateTimes = new DateTime[nstep]; var pt_index = GetIndex(xx, yy, coors); for (int t = 0; t < nstep; t++) { for (int i = 0; i < npt; i++) { mat_out[0, t, i] = nc_array[t, pt_index[i][1], pt_index[i][0]]; } progress = t * 100 / nstep; cancelProgressHandler.Progress("Package_Tool", progress, "Processing time step:" + t); mat_out.DateTimes[t] = DateTime.FromOADate(time[t]); } Workspace.Add(mat_out); return(true); } else { cancelProgressHandler.Progress("Package_Tool", 50, "Failed to run. The input parameters are incorrect."); return(false); } }
private void CreatePointsK( IFeatureSet shapeLayer, int idField) { this.data = shapeLayer; this.npoints1 = shapeLayer.NumRows(); // this.kpoints = new Kpoint[this.npoints1];//x,y,z,z-inter,error,stderr this.quadTree1 = new QuadTree(); Stat NorthSouth = new Stat(false); Stat EastWest = new Stat(false); Stat TopBott = new Stat(false); Stat Zvalue = new Stat(false); List<int> l = SelectRandom(shapeLayer.NumRows()); this.npoints1 = l.Count(); for (int shp1 = 0; shp1 < l.Count; shp1++) { int shp = l[shp1]; Coordinate pt = shapeLayer.Features[shp].Coordinates[0]; Kpoint point = new Kpoint(pt.X, pt.Y, double.IsNaN(pt.Z) ? 0 : pt.Z, Convert.ToDouble(shapeLayer.Features[shp].DataRow[idField]), shp); this.kpoints.Add(point ); //this.cpoints1[shp, 0] = pt.X; //this.cpoints1[shp, 1] = pt.Y; //this.cpoints1[shp, 2] = Convert.ToDouble(shapeLayer.Features[shp].DataRow[idField]); this.quadTree1.Insert(pt.X, pt.Y, point); NorthSouth += new Stat(pt.Y); EastWest += new Stat(pt.X); TopBott += new Stat(pt.Z); Zvalue += new Stat(point.W); } this.extentZ1= new double[2] {Zvalue.Min,Zvalue.Max}; this.extent1= new double[6]{EastWest.Min,NorthSouth.Min,TopBott.Min,EastWest.Max,NorthSouth.Max, TopBott.Max}; this.idExtremPoints= new long[6]{EastWest.PosMin,NorthSouth.PosMin,TopBott.PosMin,EastWest.PosMax,NorthSouth.PosMax, TopBott.PosMax}; this.idExtremeZPoints= new long[2]{Zvalue.PosMin,Zvalue.PosMax}; }
public static void CorretionCentroid() { //中心点数据 Stopwatch sw = new Stopwatch(); sw.Start(); List <Coordinate> centroidPoints = new List <Coordinate>(80); StreamReader sr = new StreamReader(@"D:\MagicSong\OneDrive\2017研究生毕业设计\数据\项目用数据\中心点80.txt"); sr.ReadLine();//读取标题行 while (!sr.EndOfStream) { string[] line = sr.ReadLine().Split(','); centroidPoints.Add(new Coordinate(double.Parse(line[1]), double.Parse(line[2]))); } sr.Close(); //Bus数据,并且构造KD树 KdTree myKdtree = new KdTree(2); IFeatureSet busFS = FeatureSet.Open(@"D:\MagicSong\OneDrive\2017研究生毕业设计\数据\项目用数据\BusStopGauss.shp"); List <Coordinate> busStopPoints = new List <Coordinate>(busFS.NumRows()); foreach (var item in busFS.Features) { var c = item.Coordinates[0]; busStopPoints.Add(c); myKdtree.Insert(new double[] { c.X, c.Y }, item); } Console.WriteLine("数据读取完毕,开始构造遗传算法"); IFeatureSet newCentroid = new FeatureSet(FeatureType.Point); newCentroid.Name = "优化过的中心点"; newCentroid.Projection = ProjectionInfo.FromEpsgCode(GAUSS_EPSG); newCentroid.DataTable.Columns.Add("name", typeof(string)); //遗传算法,构造适应性函数 MyProblemChromosome.CandiateNumber = 5; List <int[]> candinatesForEachControid = new List <int[]>(centroidPoints.Count); foreach (var item in centroidPoints) { object[] nearest = myKdtree.Nearest(new double[] { item.X, item.Y }, MyProblemChromosome.CandiateNumber); candinatesForEachControid.Add(nearest.Select((o) => { var f = o as IFeature; return(f.Fid); }).ToArray()); } MyProblemFitness fitness = new MyProblemFitness(centroidPoints, busStopPoints, candinatesForEachControid); MyProblemChromosome mpc = new MyProblemChromosome(centroidPoints.Count); //这边可以并行 MyProblemChromosome globalBest = null; Console.WriteLine("遗传算法构造已经完成!"); sw.Stop(); Console.WriteLine("一共用时:{0}s", sw.Elapsed.TotalSeconds); int GACount = 8; Parallel.For(0, GACount, new Action <int>((index) => { var selection = new EliteSelection(); var crossover = new TwoPointCrossover(); var mutation = new ReverseSequenceMutation(); var population = new Population(1000, 1200, mpc); var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation); ga.Termination = new GenerationNumberTermination(1000); Stopwatch sw1 = new Stopwatch(); sw1.Start(); Console.WriteLine("遗传算法任务{0}正在运行.......", index); ga.Start(); var best = ga.BestChromosome as MyProblemChromosome; if (globalBest == null || globalBest.Fitness < best.Fitness) { globalBest = best; } sw1.Stop(); Console.WriteLine("第{0}次遗传算法已经完成,耗费时间为:{1}s,最终的fitness为:{2},有效个数为:{3}", index, sw1.Elapsed.TotalSeconds, best.Fitness, best.Significance); })); Console.WriteLine("Final Choose!"); Console.WriteLine("最终的fitness为:{0},有效个数为:{1}", globalBest.Fitness, globalBest.Significance); for (int i = 0; i < globalBest.Length; i++) { int index = candinatesForEachControid[i][(int)globalBest.GetGene(i).Value]; Coordinate c = busStopPoints[index]; var f = newCentroid.AddFeature(new Point(c)); f.DataRow.BeginEdit(); f.DataRow["name"] = busFS.GetFeature(index).DataRow["name"]; f.DataRow.EndEdit(); } newCentroid.SaveAs("newCentroid.shp", true); Console.ReadKey(); }
private void CreatePoints( IFeatureSet shapeLayer, int idField) { this.npoints1 = shapeLayer.NumRows(); this.cpoints1 = new double[this.npoints1, 7];//x,y,z,z-inter,error,stderr this.quadTree1 = new QuadTree(); for (int shp = 0; shp < shapeLayer.NumRows(); shp++) { Coordinate pt = shapeLayer.Features[shp].Coordinates[0]; this.cpoints1[shp, 0] = pt.X; this.cpoints1[shp, 1] = pt.Y; this.cpoints1[shp, 6] = pt.Z; this.cpoints1[shp, 2] = Convert.ToDouble(shapeLayer.Features[shp].DataRow[idField]); // this.quadTree1.Insert(pt.X, pt.Y, shp); if (this.cpoints1[shp, 6] > this.extentZ1[1]) { this.extentZ1[1] = this.cpoints1[shp, 2]; } if (this.cpoints1[shp, 2] > this.extentZ1[1]) { this.extentZ1[1] = this.cpoints1[shp, 2]; } if (this.cpoints1[shp, 2] < this.extentZ1[0]) { this.extentZ1[0] = this.cpoints1[shp, 2]; } //xmin ymin xmax ymax //xmin ymin zmin xmax ymax zmax if (pt.Z > this.extent1[5]) { this.extent1[5] = pt.Z; } if (pt.Y > this.extent1[4]) { this.extent1[4] = pt.Y; } if (pt.X > this.extent1[3]) { this.extent1[3] = pt.X; } if (pt.X < this.extent1[0]) { this.extent1[0] = pt.X; } if (pt.Y < this.extent1[1]) { this.extent1[1] = pt.Y; } } }
private void Configure(IFeatureSet inFeatureSet) { FeatureType ft = inFeatureSet.FeatureType; if (ft != FeatureType.Point && ft != FeatureType.MultiPoint && ft != FeatureType.Unspecified) { throw new PointFeatureTypeException(); } if (inFeatureSet.NumRows() == 0) { MyExtent = new Extent(-180, -90, 180, 90); } if (inFeatureSet.NumRows() == 1) { MyExtent = inFeatureSet.Extent.Copy(); MyExtent.ExpandBy(10, 10); } Symbology = new PointScheme(); }
private static void buildMergeDownstreamUpStream(IFeatureSet newshed, int IDFieldNum, int LinksFieldNum, int DSFieldNum, int USFieldNum1, int USFieldNum2) { for (int i = 0; i <= newshed.NumRows() - 1; i++) { string currDSField = newshed.get_CellValue(DSFieldNum, i).ToString(); if (currDSField != "-1") { for (int j = 0; j <= newshed.NumRows() - 1; j++) { string links = newshed.get_CellValue(LinksFieldNum, j).ToString(); string[] split = links.Split(','); for (int k = 0; k <= split.Length - 1; k++) { if (split[k].Trim() == currDSField) { newshed.EditCellValue(DSFieldNum, i, newshed.get_CellValue(IDFieldNum, j)); string upstream1 = newshed.get_CellValue(USFieldNum1, j).ToString(); if (upstream1 == "-1") { newshed.EditCellValue(USFieldNum1, j, newshed.get_CellValue(IDFieldNum, i)); } else { newshed.EditCellValue(USFieldNum2, j, newshed.get_CellValue(IDFieldNum, i)); } break; } } } } } }
private static int GetBasinIndexByID(IFeatureSet shed, int id) { for (var i = 0; i < shed.NumRows(); i++) { if (int.Parse(shed.DataTable.Rows[i].ItemArray[0].ToString()) == id) { return i; } } return -1; }
public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler) { int progress = 0; int count = 1; if (_target_layer != null) { var nrow = _target_layer.NumRows(); var dx = System.Math.Sqrt(_target_layer.GetFeature(0).Geometry.Area); int nsample = (int)System.Math.Floor(dx / _dem_layer.CellHeight); var mat = new DataCube <float>(1, 1, nrow); mat.Name = Matrix; mat.Variables = new string[] { Matrix }; mat.TimeBrowsable = false; mat.AllowTableEdit = true; List <Coordinate> list = new List <Coordinate>(); if (_target_layer.FeatureType == FeatureType.Polygon) { for (int i = 0; i < nrow; i++) { float sum_cellv = 0; int npt = 0; list.Clear(); var fea = _target_layer.GetFeature(i).Geometry; var x0 = (from p in fea.Coordinates select p.X).Min(); var y0 = (from p in fea.Coordinates select p.Y).Min(); for (int r = 0; r <= nsample; r++) { var y = y0 + r * _dem_layer.CellHeight; for (int c = 0; c <= nsample; c++) { var x = x0 + c * _dem_layer.CellWidth; Coordinate pt = new Coordinate(x, y); list.Add(pt); } } foreach (var pt in list) { var cell = _dem_layer.ProjToCell(pt); if (cell != null && cell.Row > 0) { var buf = (float)_dem_layer.Value[cell.Row, cell.Column]; if (buf != _dem_layer.NoDataValue) { sum_cellv += buf; npt++; } } } if (npt > 0) { sum_cellv = sum_cellv / npt; } mat[0, 0, i] = sum_cellv; progress = i * 100 / nrow; if (progress > count) { cancelProgressHandler.Progress("Package_Tool", progress, "Processing polygon: " + i); count++; } } } else { Coordinate[] coors = new Coordinate[nrow]; for (int i = 0; i < nrow; i++) { var geo_pt = _target_layer.GetFeature(i).Geometry; coors[i] = geo_pt.Coordinate; } for (int i = 0; i < nrow; i++) { var cell = _dem_layer.ProjToCell(coors[i]); if (cell != null && cell.Row > 0) { mat[0, 0, i] = (float)_dem_layer.Value[cell.Row, cell.Column]; } progress = i * 100 / nrow; if (progress > count) { cancelProgressHandler.Progress("Package_Tool", progress, "Processing point: " + i); count++; } } } Workspace.Add(mat); return(true); } else { cancelProgressHandler.Progress("Package_Tool", 100, "Error message: the input layers are incorrect."); return(false); } }
private void Configure(IFeatureSet inFeatureSet) { if (inFeatureSet.FeatureType != FeatureTypes.Point && inFeatureSet.FeatureType != FeatureTypes.MultiPoint) { throw new PointFeatureTypeException(); } if (inFeatureSet.NumRows() == 0) { Envelope = new Envelope(new Coordinate(-180, -90), new Coordinate(180, 90)); } if (inFeatureSet.NumRows() == 1) { Envelope = inFeatureSet.Envelope; Envelope.ExpandBy(10); } Symbology = new PointScheme(); }
static void GetDataOfEachCentoid() { Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("开始读取数据"); IFeatureSet centroid = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\newCentroidNoDup.shp"); IFeatureSet LargePoints = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\DesGauss.shp"); sw.Stop(); Console.WriteLine("数据读取完成,耗费时间为{0}s", sw.Elapsed.TotalSeconds); sw.Restart(); Console.WriteLine("开始处理数据"); KdTree myTree = new KdTree(2); foreach (var item in centroid.Features) { var c = item.Coordinates[0]; myTree.Insert(new double[] { c.X, c.Y }, item); } Console.WriteLine("KD树构建完成"); List <int>[] result = new List <int> [centroid.NumRows()]; for (int i = 0; i < result.Length; i++) { result[i] = new List <int>(); } int core = 8; double eachTaskPointsCount = LargePoints.NumRows() / 8.0; Parallel.For(0, core, new Action <int>((index) => { //并行任务开始 int start = (int)Math.Ceiling(index * eachTaskPointsCount); int end = index != 7 ? (int)Math.Floor((index + 1) * eachTaskPointsCount) : LargePoints.NumRows() - 1; Console.WriteLine("开始为:{0},终点为:{1}", start, end); for (int i = start; i <= end; i++) { var currentFeature = LargePoints.GetFeature(i); Coordinate c = currentFeature.Coordinates[0]; IFeature f = myTree.Nearest(new double[] { c.X, c.Y }) as IFeature; if (f.Distance(currentFeature) < 300) { result[f.Fid].Add(currentFeature.Fid); } } })); sw.Stop(); Console.WriteLine("计算结束!还需保存!耗时:{0}", sw.Elapsed.TotalSeconds); StreamWriter streamw = new StreamWriter("summaryDes.txt"); foreach (var item in result) { for (int i = 0; i < item.Count; i++) { streamw.Write(item[i]); if (i != item.Count - 1) { streamw.Write(','); } } streamw.Write(Environment.NewLine); } streamw.Close(); Console.WriteLine("保存完毕!"); Console.ReadKey(); }
public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler) { //string basedir = @"E:\Heihe\HRB\DataSets\Driving Forces\PXD\"; //AverageTemperatureFileName = basedir + "daily_tavk_11243.dcx"; //MaxTemperatureFileName = basedir + "daily_tmaxk_11243.dcx"; //MinTemperatureFileName = basedir + "daily_tmink_11243.dcx"; //RelativeHumidityFileName = @"E:\Heihe\HRB\DataSets\Driving Forces\TY\rh.dcx"; //AirPressureFileName = basedir + "daily_ap_11243.dcx"; //WindSpeedFileName = basedir + "daily_windspeed_11243.dcx"; IFeatureSet fs = FeatureSet.Open(PointFeatureFileName); string[] files = new string[] { AverageTemperatureFileName, MaxTemperatureFileName, MinTemperatureFileName, RelativeHumidityFileName, AirPressureFileName, WindSpeedFileName }; var npt = fs.NumRows(); Coordinate[] coors = new Coordinate[npt]; for (int i = 0; i < npt; i++) { var geo_pt = fs.GetFeature(i).Geometry; coors[i] = geo_pt.Coordinate; } int nfile = files.Length; DataCubeStreamReader[] ass = new DataCubeStreamReader[nfile]; DataCube <float>[] mats = new DataCube <float> [nfile]; for (int i = 0; i < nfile; i++) { ass[i] = new DataCubeStreamReader(files[i]); ass[i].Open(); } int progress = 0; int nstep = ass[0].NumTimeStep; int ncell = ass[0].FeatureCount; PenmanMonteithET pet = new PenmanMonteithET(); DataCubeStreamWriter sw = new DataCubeStreamWriter(OutputFileName); sw.WriteHeader(new string[] { "pet" }, ncell); DataCube <float> mat_out = new DataCube <float>(1, 1, ncell); mat_out.DateTimes = new DateTime[nstep]; int count = 1; for (int t = 0; t < nstep; t++) { for (int i = 0; i < nfile; i++) { mats[i] = ass[i].LoadStep(); } for (int n = 0; n < ncell; n++) { var tav = mats[0][0, 0, n]; var tmax = mats[1][0, 0, n]; var tmin = mats[2][0, 0, n]; if (InputTemperatureUnit == TemperatureUnit.Fahrenheit) { tmax = (float)UnitConversion.Fahrenheit2Kelvin(tmax); tmin = (float)UnitConversion.Fahrenheit2Kelvin(tmin); tav = (float)UnitConversion.Fahrenheit2Kelvin(tav); } else if (InputTemperatureUnit == TemperatureUnit.Celsius) { tmax = (float)UnitConversion.Celsius2Kelvin(tmax); tmin = (float)UnitConversion.Celsius2Kelvin(tmin); tav = (float)UnitConversion.Celsius2Kelvin(tav); } double ap = mats[4][0, 0, n] / 1000; var et0 = pet.ET0(coors[n].Y, coors[n].X, tav, tmax, tmin, mats[3][0, 0, n], ap, mats[5][0, 0, n], Start.AddDays(t), CloudCover); if (OutputLengthUnit == LengthUnit.inch) { mat_out[0, 0, n] = (float)System.Math.Round(et0 * UnitConversion.mm2Inch, 3); } else { mat_out[0, 0, n] = (float)System.Math.Round(et0, 3); } } mat_out.DateTimes[t] = Start.AddDays(1); sw.WriteStep(1, ncell, mat_out); progress = t * 100 / nstep; if (progress > count) { cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + (t + 1)); count++; } } sw.Close(); for (int i = 0; i < nfile; i++) { ass[i].Close(); } return(true); }
public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler) { IFeatureSet fs = FeatureSet.Open(FeatureFile); int var_index = 0; int con_var_index = 0; var mat = Get3DMat(Matrix, ref var_index); DataCube <float> con_mat = null; if (Filter != FilterMode.None) { con_mat = Get3DMat(ConMat, ref con_var_index); } if (fs != null && mat != null) { IRaster raster = Raster.Open(TemplateFile); raster.SaveAs(TemplateFile + ".tif"); int fea_count = fs.NumRows(); Coordinate[] coors = new Coordinate[fea_count]; for (int i = 0; i < fea_count; i++) { coors[i] = fs.GetFeature(i).Geometry.Coordinates[0]; } var nsteps = mat.Size[1]; int progress = 0; string[] fns = new string[nsteps]; if (mat.DateTimes != null) { for (int t = 0; t < nsteps; t++) { fns[t] = string.Format("{0}_{1}.tif", VariableName, mat.DateTimes[t].ToString(DateFormat)); } } else { for (int t = 0; t < nsteps; t++) { fns[t] = string.Format("{0}_{1}.tif", VariableName, t.ToString("0000")); } } if (Filter != FilterMode.None) { for (int t = 0; t < nsteps; t++) { string outras = Path.Combine(Direcotry, fns[t]); int i = 0; foreach (var cor in coors) { var cell = raster.ProjToCell(cor); var temp = mat[var_index, t, i] * Scale; if (Filter == FilterMode.Maximum) { if (temp > con_mat[0, 0, i]) { temp = con_mat[0, 0, i]; } } else if (Filter == FilterMode.Minimum) { if (temp < con_mat[0, 0, i]) { temp = con_mat[0, 0, i]; } } raster.Value[cell.Row, cell.Column] = temp; i++; } raster.SaveAs(outras); progress = t * 100 / nsteps; cancelProgressHandler.Progress("Package_Tool", progress, "Saving raster to:" + outras); } } else { for (int t = 0; t < nsteps; t++) { string outras = Path.Combine(Direcotry, fns[t]); int i = 0; foreach (var cor in coors) { var cell = raster.ProjToCell(cor.X - 500, cor.Y + 500); var temp = mat[var_index, t, i] * Scale; raster.Value[cell.Row, cell.Column] = temp; i++; } raster.SaveAs(outras); progress = t * 100 / nsteps; cancelProgressHandler.Progress("Package_Tool", progress, "Saving raster to:" + outras); } } return(true); } else { cancelProgressHandler.Progress("Package_Tool", 100, "Failed to run. The input parameters are incorrect."); return(false); } }
static void GetDataOfEachCentoid2() { Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("开始读取数据"); IFeatureSet centroid = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\newCentroidNoDup.shp"); IFeatureSet LargePoints = FeatureSet.Open(@"D:\OneDrive\2017研究生毕业设计\数据\项目用数据\OriginalGauss.shp"); string newColumnName = "Subject"; LargePoints.DataTable.Columns.Add(newColumnName, typeof(int)); sw.Stop(); Console.WriteLine("数据读取完成,耗费时间为{0}s", sw.Elapsed.TotalSeconds); sw.Restart(); Console.WriteLine("开始处理数据"); KdTree myTree = new KdTree(2); foreach (var item in centroid.Features) { var c = item.Coordinates[0]; myTree.Insert(new double[] { c.X, c.Y }, item); } Console.WriteLine("KD树构建完成"); int core = 8; IFeature[] newFeatures = LargePoints.Features.ToArray(); double eachTaskPointsCount = LargePoints.NumRows() / 8.0; Parallel.For(0, core, new Action <int>((index) => { //并行任务开始 int start = (int)Math.Ceiling(index * eachTaskPointsCount); int end = index != 7 ? (int)Math.Floor((index + 1) * eachTaskPointsCount) : LargePoints.NumRows() - 1; Console.WriteLine("开始为:{0},终点为:{1}", start, end); for (int i = start; i <= end; i++) { var currentFeature = newFeatures[i]; Coordinate c = currentFeature.Coordinates[0]; IFeature f = myTree.Nearest(new double[] { c.X, c.Y }) as IFeature; lock (currentFeature.DataRow.Table) { currentFeature.DataRow.BeginEdit(); if (f.Distance(currentFeature) <= 350) { currentFeature.DataRow[newColumnName] = f.Fid; } else { currentFeature.DataRow[newColumnName] = -1; } currentFeature.DataRow.EndEdit(); } } })); sw.Stop(); Console.WriteLine("计算结束!还需保存!耗时:{0}", sw.Elapsed.TotalSeconds); FeatureSet newFeatureSet = new FeatureSet(newFeatures); newFeatureSet.Name = "OriginalGaussWithSubject"; newFeatureSet.Projection = LargePoints.Projection; newFeatureSet.SaveAs(newFeatureSet.Name + ".shp", true); Console.WriteLine("保存完毕!"); Console.ReadKey(); }
private static int GetWshedFromStreamLink(int streamLink, IFeatureSet streamShape, IFeatureSet shedShape) { int streamindx; const int LinkIDField = 0; const int WaterShedIDField = 13; for (streamindx = 0; streamindx <= streamShape.NumRows() - 1; streamindx++) { if (int.Parse(streamShape.get_CellValue(LinkIDField, streamindx).ToString()) == streamLink) { return int.Parse(streamShape.get_CellValue(WaterShedIDField, streamindx).ToString()); } } return -1; }
/// <summary> /// This tests each feature of the input /// </summary> /// <param name="self">This featureSet</param> /// <param name="other">The featureSet to perform intersection with</param> /// <param name="joinType">The attribute join type</param> /// <param name="progHandler">A progress handler for status messages</param> /// <returns>An IFeatureSet with the intersecting features, broken down based on the join Type</returns> public static IFeatureSet Intersection(this IFeatureSet self, IFeatureSet other, FieldJoinType joinType, IProgressHandler progHandler) { IFeatureSet result = null; ProgressMeter pm = new ProgressMeter(progHandler, "Calculating Intersection", self.Features.Count); if (joinType == FieldJoinType.All) { result = CombinedFields(self, other); // Intersection is symmetric, so only consider I X J where J <= I if (!self.AttributesPopulated) { self.FillAttributes(); } if (!other.AttributesPopulated) { other.FillAttributes(); } for (int i = 0; i < self.Features.Count; i++) { IFeature selfFeature = self.Features[i]; List <IFeature> potentialOthers = other.Select(selfFeature.Geometry.EnvelopeInternal.ToExtent()); foreach (IFeature otherFeature in potentialOthers) { selfFeature.Intersection(otherFeature, result, joinType); } pm.CurrentValue = i; } pm.Reset(); } else if (joinType == FieldJoinType.LocalOnly) { if (!self.AttributesPopulated) { self.FillAttributes(); } result = new FeatureSet(); result.CopyTableSchema(self); result.FeatureType = self.FeatureType; if (other.Features != null && other.Features.Count > 0) { pm = new ProgressMeter(progHandler, "Calculating Union", other.Features.Count); IFeature union = other.Features[0]; for (int i = 1; i < other.Features.Count; i++) { union = union.Union(other.Features[i].Geometry); pm.CurrentValue = i; } pm.Reset(); pm = new ProgressMeter(progHandler, "Calculating Intersections", self.NumRows()); Extent otherEnvelope = union.Geometry.EnvelopeInternal.ToExtent(); for (int shp = 0; shp < self.ShapeIndices.Count; shp++) { if (!self.ShapeIndices[shp].Extent.Intersects(otherEnvelope)) { continue; } IFeature selfFeature = self.GetFeature(shp); selfFeature.Intersection(union, result, joinType); pm.CurrentValue = shp; } pm.Reset(); } } else if (joinType == FieldJoinType.ForeignOnly) { if (!other.AttributesPopulated) { other.FillAttributes(); } result = new FeatureSet(); result.CopyTableSchema(other); result.FeatureType = other.FeatureType; if (self.Features != null && self.Features.Count > 0) { pm = new ProgressMeter(progHandler, "Calculating Union", self.Features.Count); IFeature union = self.Features[0]; for (int i = 1; i < self.Features.Count; i++) { union = union.Union(self.Features[i].Geometry); pm.CurrentValue = i; } pm.Reset(); if (other.Features != null) { pm = new ProgressMeter(progHandler, "Calculating Intersection", other.Features.Count); for (int i = 0; i < other.Features.Count; i++) { other.Features[i].Intersection(union, result, FieldJoinType.LocalOnly); pm.CurrentValue = i; } } pm.Reset(); } } return(result); }
public static void GettingNumberOfRowsInFeatureSet() { IFeatureSet fs = FeatureSet.Open(@"C:\[Your File Path]\Municipalities.shp"); int numRows = fs.NumRows(); }