/// <summary> /// Loads the catchments and connects them /// First data column must be ID /// Second column must be ID of downstream catchment /// </summary> /// <param name="ShapeFileName"></param> public void LoadCatchments(string ShapeFileName) { using (ShapeReader sr = new ShapeReader(ShapeFileName)) { if (AllCatchments == null) AllCatchments = new Dictionary<int, Catchment>(); var data = sr.GeoData.ToList(); foreach (var c in data) { Catchment ca = new Catchment((int)c.Data[0]); if (!AllCatchments.ContainsKey(ca.ID)) AllCatchments.Add(ca.ID, ca); ca.Geometry = (IXYPolygon)c.Geometry; } //now loop again to do the connections foreach (var c in data) { int catcid = ((int)c.Data[0]); int downid = ((int)c.Data[1]); Catchment DownStreamCatchment; if (AllCatchments.TryGetValue(downid, out DownStreamCatchment)) { if (DownStreamCatchment != AllCatchments[catcid]) //Do not allow reference to self { AllCatchments[catcid].DownstreamConnection = DownStreamCatchment; DownStreamCatchment.UpstreamConnections.Add(AllCatchments[catcid]); } } } } }
public void WritePointShapeTest() { string File = @"..\..\..\TestData\WriteTest.Shp"; ShapeWriter PSW = new ShapeWriter(File); PSW.WritePointShape(10, 20); PSW.WritePointShape(20, 30); PSW.WritePointShape(30, 40); DataTable DT = new DataTable(); DT.Columns.Add("Name", typeof(string)); DT.Rows.Add(new object[] { "point1" }); DT.Rows.Add(new object[] { "point2" }); DT.Rows.Add(new object[] { "point3" }); PSW.Data.WriteDate(DT); PSW.Dispose(); ShapeReader PSR = new ShapeReader(File); IXYPoint p; DataTable DTread = PSR.Data.Read(); int i = 0; foreach (DataRow dr in DTread.Rows) { Console.WriteLine(dr[0].ToString()); p = (IXYPoint)PSR.ReadNext(i); Console.WriteLine(p.X.ToString() + " " + p.Y.ToString()); i++; } }
public WFDLakesViewModel() { ShapeReader psp = new ShapeReader(@"soervp1.shp"); Lakes = new Dictionary<string, WFDLake>(); DT = psp.Data.Read(); psp.Data.SpoolBack(); foreach (var l in psp.GeoData) { WFDLake wf = new WFDLake(); wf.Polygon = (XYPolygon)l.Geometry; wf.Data = l.Data; string name =(string) l.Data[0]; if (!Lakes.ContainsKey(name)) Lakes.Add(name, wf); } psp.Dispose(); Precipitation = new TimespanSeries(); Precipitation.Name = "Precipitation"; double[] values = new double[] { 108, 83, 73, 52, 61, 86, 99, 101, 75, 108, 85, 101 }; AddMonthlyValues(Precipitation, 2007, values); Evaporation = new TimespanSeries(); Evaporation.Name = "Evaporation"; double[] values2 = new double[] { 4, 11, 34, 66, 110, 118, 122, 103, 61, 26, 7, 1 }; AddMonthlyValues(Evaporation, 2007, values2); }
public void ReadNextTest2() { string File = @"..\..\..\..\MikeSheTools\TestData\CommandAreas.Shp"; ShapeReader target = new ShapeReader(File); var geo = target.ReadNext(); double d =((XYPolygon)geo).GetArea(); Assert.IsTrue(0 < d); }
public void TestMethod1() { string File = TestDataPath + @"CommandAreas.Shp"; ShapeReader target = new ShapeReader(File); var geo = target.ReadNext(0); double d = ((XYPolygon)geo).GetArea(); Assert.IsTrue(0 < d); }
public static void BuildTotalLeachFile(string TemplateFile, string ShapeGrid, string OutputDirectory) { Dictionary<int, List<int>> SortedPoints = new Dictionary<int, List<int>>(); using (ShapeReader sr = new ShapeReader(ShapeGrid)) { foreach (var p in sr.GeoData) { int domain = int.Parse(p.Data["Model_Doma"].ToString()); int gridcode = int.Parse(p.Data["GRIDID"].ToString()); List<int> grids; if(!SortedPoints.TryGetValue(domain, out grids)) { grids = new List<int>(); SortedPoints.Add(domain, grids); } grids.Add(gridcode); } } List<string> lines = new List<string>(); using (StreamReader sr = new StreamReader(TemplateFile)) { sr.ReadLine();//headline var l = sr.ReadLine(); int gridid = int.Parse(l.Substring(0, l.IndexOf(';'))); lines.Add(l.Substring(l.IndexOf(';'))); while (!sr.EndOfStream) { l = sr.ReadLine(); int newgridid = int.Parse(l.Substring(0, l.IndexOf(';'))); lines.Add(l.Substring(l.IndexOf(';'))); if (newgridid != gridid) break; } } foreach (var domain in SortedPoints) { using (StreamWriter sr = new StreamWriter(Path.Combine(OutputDirectory, "Leaching_area_" + domain.Key + ".txt"))) { foreach (var grid in domain.Value) { foreach (var year in lines) { sr.WriteLine(grid.ToString() + year); } } } } }
public void ReadXYPoint() { string file = @"..\..\..\Testdata\kontinuitet.shp"; ShapeReader target = new ShapeReader(file); foreach (GeoRefData grd in target.GeoData) { Assert.IsTrue(grd.Geometry is XYPoint); } }
public void GeoData() { string File = TestDataPath + @"CommandAreas.Shp"; ShapeReader target = new ShapeReader(File); foreach (GeoRefData grd in target.GeoData) { Assert.IsTrue(grd.Geometry is XYPolygon); } }
public void GeoData() { string File = @"..\..\..\..\MikeSheTools\TestData\CommandAreas.Shp"; ShapeReader target = new ShapeReader(File); foreach (GeoRefData grd in target.GeoData) { Assert.IsTrue(grd.Geometry is XYPolygon); } }
public override void Initialize(DateTime Start, DateTime End, IEnumerable<Catchment> Catchments) { base.Initialize(Start, End, Catchments); using (ShapeReader sr = new ShapeReader(ShapeFile.FileName)) { for (int i = 0; i < sr.Data.NoOfEntries; i++) { Reduction.Add(sr.Data.ReadInt(i, ShapeFile.ColumnNames[0]), sr.Data.ReadDouble(i, ShapeFile.ColumnNames[1])); } } }
public void ReadProjectionFile() { string File = @"..\..\..\Testdata\kontinuitet.prj"; ShapeReader sr = new ShapeReader(File); var proj = sr.Projection; }
public override void Initialize(DateTime Start, DateTime End, IEnumerable<Catchment> Catchments) { base.Initialize(Start, End, Catchments); List<Wetland> wetlands = new List<Wetland>(); using (ShapeReader sr = new ShapeReader(ShapeFile.FileName)) { foreach (var ldata in sr.GeoData) { Wetland w = new Wetland { Geometry = (IXYPolygon) ldata.Geometry, Name = ldata.Data[ShapeFile.ColumnNames[1]].ToString(), }; int startyear = int.Parse(ldata.Data[ShapeFile.ColumnNames[0]].ToString()); if (startyear != 0) w.StartTime = new DateTime(startyear, 1, 1); else w.StartTime = Start; wetlands.Add(w); } } //Get the soil type Parallel.ForEach(wetlands, l => { foreach (var soil in MainModel.SoilTypes) { if (l.Geometry.OverLaps((IXYPolygon)soil.Geometry)) { if ((int)soil.Data[0] < 4) l.SoilString = "sand"; else l.SoilString = "ler"; break; } } }); Parallel.ForEach(wetlands, l => { foreach (var c in Catchments) if (c.Geometry.OverLaps(l.Geometry as IXYPolygon)) { lock (Lock) { c.Wetlands.Add(l); } } }); NewMessage(wetlands.Count + " wetlands read and distributed on " + Catchments.Count(c => c.Wetlands.Count > 0) + " catchments."); }
public static Lake GetLake(string Name) { ShapeReader psp = new ShapeReader(@"soervp1.shp"); foreach (var l in psp.GeoData) { Lake L = new Lake((string)l.Data[0], (XYPolygon)l.Geometry); if (L.Name.ToLower().Equals(Name.ToLower())) { psp.Dispose(); return L; } } psp.Dispose(); return null; }
public RegionViewModel() { IWellCollection Wells; using (Reader R = new Reader(@"C:\Jacob\Projects\OPI\sjælland.mdb")) { Wells = R.ReadWellsInSteps(); R.ReadLithology(Wells); } Sites = new List<SiteViewModel>(); using (ShapeReader sr = new ShapeReader(@"C:\Jacob\Projects\OPI\ds_kortlaegninger_dkjord_v2_download.shp")) { foreach(var s in sr.GeoData) Sites.Add(new SiteViewModel(s, Wells)); } RaisePropertyChanged("Sites"); }
public void DebugPrint(string outputpath, string FileName, string SoilGridCodesFileName) { List<GeoRefData> Allpoints; ProjNet.CoordinateSystems.ICoordinateSystem proj; using (ShapeReader shr = new ShapeReader(SoilGridCodesFileName)) { proj = shr.Projection; Allpoints = shr.GeoData.ToList(); } Dictionary<int, GeoRefData> data= new Dictionary<int,GeoRefData>(); foreach(var p in Allpoints) { data.Add((int)(double)p.Data["GRIDID"], p); } string name = Path.GetFileNameWithoutExtension(FileName); name = "Y_"+ name.Substring(name.Length - 4); var dt = Allpoints.First().Data.Table; dt.Columns.Add(name, typeof(double)); //if(GridCounts!=null) // dt.Columns.Add(name, typeof(double)); List<GeoRefData> NewPoints = new List<GeoRefData>(); using (ShapeWriter sw = new ShapeWriter(Path.Combine(outputpath, "Leach_"+name+"_debug.shp")) { Projection = proj }) { using (StreamReader sr = new StreamReader(FileName)) { // Headers = sr.ReadLine().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); while (!sr.EndOfStream) { var de = sr.ReadLine().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); double leach = double.Parse(de[de.Count() - 2]); int gridid = int.Parse(de[0]); var p = data[gridid]; p.Data[name] = leach; NewPoints.Add(p); } } foreach (var v in NewPoints) sw.Write(v); } }
public virtual void Initialize(DateTime Start, DateTime End, IEnumerable<Catchment> Catchments) { if (ExtraParsShape != null) { MultiplicationFactors = new Dictionary<int, double>(); AdditionFactors = new Dictionary<int, double>(); using (ShapeReader sr = new ShapeReader(ExtraParsShape.FileName)) { for (int i = 0; i < sr.Data.NoOfEntries; i++) { int id15 = sr.Data.ReadInt(i, ExtraParsShape.ColumnNames[0]); if (!string.IsNullOrEmpty(ExtraParsShape.ColumnNames[1])) MultiplicationFactors.Add(id15, sr.Data.ReadDouble(i, ExtraParsShape.ColumnNames[1])); if (!string.IsNullOrEmpty(ExtraParsShape.ColumnNames[2])) AdditionFactors.Add(id15, sr.Data.ReadDouble(i, ExtraParsShape.ColumnNames[2])); } } } }
public void TestMethod1() { Dictionary<int, int> dmuTOId15 = new Dictionary<int, int>(); using (StreamReader sr = new StreamReader(@"D:\DK_information\Overfladevand\stationer\maol.txt")) { sr.ReadLine(); while (!sr.EndOfStream) { var data = sr.ReadLine().Split(new string[] { "\t" }, StringSplitOptions.None); dmuTOId15.Add(int.Parse(data[1]), int.Parse(data[3])); } } using (ShapeWriter sw = new ShapeWriter(@"D:\DK_information\Overfladevand\stationer\stationer2.shp")) { using (ShapeReader sh = new ShapeReader(@"D:\DK_information\Overfladevand\stationer\stationer.shp")) { var dt = sh.Data.Read(); dt.Columns.Add("ID15", typeof(int)); for(int i =0;i< dt.Rows.Count;i++) { int dmunr = int.Parse(dt.Rows[i][0].ToString()); int id15; if(dmuTOId15.TryGetValue(dmunr, out id15)) { dt.Rows[i]["ID15"] = id15; } sw.Write(new Geometry.GeoRefData() { Geometry = sh.ReadNext(i), Data = dt.Rows[i] }); } } } }
public void BuildGrid(string ShapeSoilCodes) { using (ShapeReader sr = new ShapeReader(ShapeSoilCodes)) { var Allpoints = sr.GeoData.ToList(); var BornholmPoints = Allpoints.Where(g => int.Parse(g.Data["Model_Doma"].ToString()) == 7).ToList(); var OtherPoints = Allpoints.Where(g => int.Parse(g.Data["Model_Doma"].ToString()) != 7).ToList(); var bbox = XYGeometryTools.BoundingBox(OtherPoints.Select(f => (IXYPoint)f.Geometry)); GlobalGrid.GridSize = 500.0; GlobalGrid.XOrigin = bbox.Points.Min(p => p.X); GlobalGrid.YOrigin = bbox.Points.Min(p => p.Y); GlobalGrid.NumberOfColumns = (int) (Math.Round((bbox.Points.Max(p => p.X) - GlobalGrid.XOrigin)/ GlobalGrid.GridSize,0))+1; GlobalGrid.NumberOfRows = (int)(Math.Round((bbox.Points.Max(p => p.Y) - GlobalGrid.YOrigin) / GlobalGrid.GridSize,0)+1); foreach (var g in OtherPoints) { GlobalGrid.Data[GlobalGrid.GetColumnIndex(((IXYPoint)g.Geometry).X), GlobalGrid.GetRowIndex(((IXYPoint)g.Geometry).Y)] = int.Parse(g.Data["GRIDID"].ToString()); } bbox = XYGeometryTools.BoundingBox(BornholmPoints.Select(f => (IXYPoint)f.Geometry)); BornholmGrid.GridSize = 250.0; BornholmGrid.XOrigin = bbox.Points.Min(p => p.X); BornholmGrid.YOrigin = bbox.Points.Min(p => p.Y); BornholmGrid.NumberOfColumns = (int)(Math.Round((bbox.Points.Max(p => p.X) - BornholmGrid.XOrigin) / BornholmGrid.GridSize, 0)) + 1; BornholmGrid.NumberOfRows = (int)(Math.Round((bbox.Points.Max(p => p.Y) - BornholmGrid.YOrigin) / BornholmGrid.GridSize, 0) + 1); foreach (var g in BornholmPoints) { int id = int.Parse(g.Data["GRIDID"].ToString()); BornholmerID.Add(id,id); BornholmGrid.Data[BornholmGrid.GetColumnIndex(((IXYPoint)g.Geometry).X), BornholmGrid.GetRowIndex(((IXYPoint)g.Geometry).Y)] =id; } } }
static void Main(string[] args) { double area = 0; using (ShapeReader sr = new ShapeReader(@"D:/Dropbox/ProjektData/Øvre Suså Ålav/skov2.shp")) { foreach (var gd in sr.GeoData) { area += ((IXYPolygon)gd.Geometry).GetArea(); } } double ha = area / 10000; XYPoint point = new XYPoint(715281.56, 6189341.78); double dx = 5000; double dy = 5000; actual = Map.GetImagery(point, dx, dy); actual.DownloadCompleted += new EventHandler(actual_DownloadCompleted); System.Windows.Controls.Image im = new System.Windows.Controls.Image(); im.Source = actual; im.SourceUpdated += new EventHandler<System.Windows.Data.DataTransferEventArgs>(im_SourceUpdated); im.UpdateLayout(); Console.WriteLine(DateTime.Now.Second); Console.ReadLine(); }
public void ReadWellsFromShape() { ShapeReader SR = new ShapeReader(_config.WellShapeFile); DataTable _wellData = SR.Data.Read(); SR.Dispose(); foreach (DataRow dr in _wellData.Rows) { IrrigationWell IW = new IrrigationWell(dr[_config.IdHeader].ToString()); IW.X = Convert.ToDouble(dr[_config.XHeader]); IW.Y = Convert.ToDouble(dr[_config.YHeader]); IIntake I = IW.AddNewIntake(1); IW.MaxDepth = Convert.ToDouble(dr[_config.MaxDepthHeader]); IW.MaxRate = Convert.ToDouble(dr[_config.MaxRateHeader]); Screen CurrentScreen = new Screen(I); CurrentScreen.DepthToBottom = Convert.ToDouble(dr[_config.BottomHeader]); CurrentScreen.DepthToTop = Convert.ToDouble(dr[_config.TopHeader]); _wells.Add(IW); } _wellData.Dispose(); }
/// <summary> /// Opens a point shape /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { openFileDialog2.Filter = "Known file types (*.shp)|*.shp"; this.openFileDialog2.ShowReadOnly = true; this.openFileDialog2.Title = "Select a shape file with data for wells or intakes"; if (openFileDialog2.ShowDialog() == DialogResult.OK) { string FileName = openFileDialog2.FileName; ShapeReader SR = new ShapeReader(FileName); DataTable FullDataSet = SR.Data.Read(); //Launch a data selector DataSelector DS = new DataSelector(FullDataSet); if (DS.ShowDialog() == DialogResult.OK) { if (ShpConfig == null) { XmlSerializer x = new XmlSerializer(typeof(ShapeReaderConfiguration)); string InstallationPath = Path.GetDirectoryName(this.GetType().Assembly.Location); string config = Path.Combine(InstallationPath, "ShapeReaderConfig.xml"); using (FileStream fs = new FileStream(config, FileMode.Open)) { ShpConfig = (ShapeReaderConfiguration)x.Deserialize(fs); if (CheckColumn(FullDataSet, ShpConfig.WellIDHeader, config)) if (CheckColumn(FullDataSet, ShpConfig.IntakeNumber, config)) if (CheckColumn(FullDataSet, ShpConfig.XHeader, config)) if (CheckColumn(FullDataSet, ShpConfig.YHeader, config)) if (CheckColumn(FullDataSet, ShpConfig.TOPHeader, config)) if (CheckColumn(FullDataSet, ShpConfig.BOTTOMHeader, config)) { Wells = new IWellCollection(); if (FullDataSet.Columns.Contains(ShpConfig.PlantIDHeader)) { DPlants = new IPlantCollection(); HeadObservations.FillInFromNovanaShape(DS.SelectedRows, ShpConfig, Wells, DPlants); } else HeadObservations.FillInFromNovanaShape(DS.SelectedRows, ShpConfig, Wells); UpdateListsAndListboxes(); } } } } SR.Dispose(); } }
static void Main(string[] args) { if(args.Count()<2) { Console.WriteLine("Usage: CatchmentConnector <ID15-catchments shapefile> <Station shapefile>"); return; } string CatchmentFilename = Path.GetFullPath(args[0]); string FilePath = Path.GetDirectoryName(CatchmentFilename); ID15Reader m = new ID15Reader(); m.LoadCatchments(CatchmentFilename); Dictionary<int, Catchment> StationCatchment = new Dictionary<int, Catchment>(); string outpufilen = Path.Combine(FilePath, "output2.shp"); if (args.Count() == 3) outpufilen = args[2]; using (ShapeReader sr = new ShapeReader(args[1])) { foreach (var station in sr.GeoData) { int stationid = (int)station.Data["DMUstnr"]; int catchid = (int)station.Data["ID15_NEW"]; Catchment c; if (!m.AllCatchments.TryGetValue(catchid, out c)) { Console.WriteLine("Catchment with ID: " + catchid + " not found"); } else { StationCatchment.Add(stationid, c); c.Measurements = new DMUStation() { ID = stationid }; } } using (ShapeWriter sw = new ShapeWriter(outpufilen) { Projection = sr.Projection }) { DataTable dt = new DataTable(); dt.Columns.Add("DMUstnr", typeof(int)); dt.Columns.Add("ID15_NEW", typeof(int)); dt.Columns.Add("TotalArea", typeof(double)); dt.Columns.Add("Area", typeof(double)); dt.Columns.Add("To_DMUstnr", typeof(int)); foreach (var c in StationCatchment) { var row = dt.NewRow(); row[0] = c.Key; row[1] = c.Value.ID; var upstream = m.GetUpstreamCatchments(c.Value).ToList(); row[2] = upstream.Sum(cu => cu.Geometry.GetArea()); var toremove = upstream.Where(cu => cu.ID != c.Value.ID & cu.Measurements != null).SelectMany(cu => m.GetUpstreamCatchments(cu)).Distinct().ToList(); foreach (var cu in toremove) upstream.Remove(cu); row[3] = upstream.Sum(cu => cu.Geometry.GetArea()); IXYPolygon geom; if (upstream.Count > 1) geom = HydroNumerics.Geometry.ClipperTools.Union(upstream.Select(g => g.Geometry).Cast<IXYPolygon>().ToList()); else geom = upstream.First().Geometry; var ds = m.GetDownStreamCatchments(c.Value); ds.Remove(c.Value); var dsc = ds.FirstOrDefault(dc => dc.Measurements != null); if (dsc != null) row[4] = dsc.Measurements.ID; sw.Write(new HydroNumerics.Geometry.GeoRefData() { Geometry = geom, Data = row }); } } } Console.WriteLine("Done! Hit enter to exit."); Console.Read(); }
public void LoadStationData(SafeFile ShapeFileName, string StationData, DateTime Start, DateTime End) { StateVariables.ClearColumnValues("ObservedFlow"); StateVariables.ClearColumnValues("ObservedNitrate"); Dictionary<int, DMUStation> locatedStations = new Dictionary<int,DMUStation>(); List<DMUStation> stations = new List<DMUStation>(); LogThis("Reading stations from " + ShapeFileName.FileName); using (ShapeReader sr = new ShapeReader(ShapeFileName.FileName)) { for (int i = 0; i < sr.Data.NoOfEntries; i++) { DMUStation dm = new DMUStation(); dm.Location = sr.ReadNext(i) as XYPoint; dm.ID = sr.Data.ReadInt(i, ShapeFileName.ColumnNames[0]); dm.ODANummer = sr.Data.ReadInt(i, ShapeFileName.ColumnNames[1]); stations.Add(dm); if(dm.ODANummer!=0) locatedStations.Add(dm.ODANummer, dm); int id = sr.Data.ReadInt(i, ShapeFileName.ColumnNames[2]); if (id != 0 & AllCatchments.ContainsKey(id)) { if (AllCatchments[id].Measurements != null) { int m = 0; } AllCatchments[id].Measurements = dm; } } } LogThis(stations.Count + " stations read. " + locatedStations.Count + " within catchments distributed on " + AllCatchments.Values.Count(ca => ca.Measurements != null) +" catchments."); using (StreamReader sr = new StreamReader(StationData)) { sr.ReadLine();//HeadLine while (!sr.EndOfStream) { var data = sr.ReadLine().Split(';'); DMUStation station; if (locatedStations.TryGetValue(int.Parse(data[0]), out station)) { var time = new DateTime(int.Parse(data[2]), int.Parse(data[3]), 1); if (time >= Start & time <= End) { station.Nitrate.Items.Add(new TimeStampValue(time, double.Parse(data[4]))); station.Flow.Items.Add(new TimeStampValue(time, double.Parse(data[5]) * 1000)); } } } } }
public void LoadLakes() { List<Lake> lakes = new List<Lake>(); LogThis("Reading lakes from: " + LakeFile.FileName); using (ShapeReader sr = new ShapeReader(LakeFile.FileName)) { foreach (var ldata in sr.GeoData) { Lake l = new Lake() { Geometry = ldata.Geometry as XYPolygon, ID = int.Parse(ldata.Data["OBJECTID_1"].ToString()), }; if (l.Geometry == null) l.Geometry = ((MultiPartPolygon)ldata.Geometry).Polygons.OrderBy(p => p.GetArea()).Last(); //Just take the largest l.HasDischarge = ldata.Data["Aflob"].ToString().ToLower().Trim() == "aflob"; if (ldata.Data["Type"].ToString().ToLower().Trim() == "stor soe") { l.IsSmallLake = false; l.Name = ldata.Data["Navn"].ToString(); l.BigLakeID = (int) ldata.Data["Rec"]; } else //Only small lakes have cultivation class and soil types { string cultclass = ldata.Data["Dyrk_klass"].ToString().ToLower().Trim(); if (cultclass == "> = 60 %") l.DegreeOfCultivation = CultivationClass.High; else if (cultclass == "< 30 %") l.DegreeOfCultivation = CultivationClass.Low; else if (cultclass == ">= 30 < 6*") l.DegreeOfCultivation = CultivationClass.Intermediate; l.SoilType = ldata.Data["Jord_type"].ToString(); } lakes.Add(l); } } LogThis(lakes.Count + " lakes read"); int distlakecount = 0; Parallel.ForEach(lakes.Where(la=>la.HasDischarge & la.IsSmallLake) , l => { foreach (var c in AllCatchments.Values) if (c.Geometry.Contains(l.Geometry.GetX(0),l.Geometry.GetY(0))) { lock (Lock) { c.Lakes.Add(l); distlakecount++; } break; } }); Parallel.ForEach(lakes.Where(la => la.HasDischarge & !la.IsSmallLake), l => { foreach (var c in AllCatchments.Values) if (c.Geometry.Contains(l.Geometry.Points.Average(p=>p.X),l.Geometry.Points.Average(p=>p.Y))) //Centroid { lock (Lock) { if (c.BigLake==null || c.BigLake.Geometry.GetArea()<l.Geometry.GetArea()) //Add the lake if it is bigger c.BigLake = l; } break; } }); LogThis(distlakecount + " lakes distributed on " + AllCatchments.Values.Count(c => c.Lakes.Count > 0) + " catchments"); LogThis(AllCatchments.Values.Count(c => c.BigLake != null).ToString() + " catchments have large lakes"); }
public void LoadCoastalZone() { if (CoastalZone == null) return; LogThis("Reading shape coastal zone"); List<IXYPolygon> CutPolygons = new List<IXYPolygon>(); using (ShapeReader sr = new ShapeReader(CoastalZone.FileName)) { foreach (var pol in sr.GeoData) { if(CoastalZone.ColumnNames.Skip(1).Contains(pol.Data[CoastalZone.ColumnNames.First()].ToString().ToLower().Trim())) CutPolygons.Add((IXYPolygon)pol.Geometry); } } LogThis("Distributing coastal zone"); Parallel.ForEach(EndCatchments, l => { foreach (var c in CutPolygons) if (l.Geometry.OverLaps(c)) { lock (Lock) l.CoastalZones.Add(c); } }); }
private void BiasCorrectFlow() { LogThis("Bias correcting Mike11-flow"); List<double> Factors = new List<double>(); using (ShapeReader sr = new ShapeReader(M11Base.FileName)) { var geodata = sr.GeoData.ToList(); Parallel.ForEach(geodata, item => { bool found = false; foreach (var C in AllCatchments.Values) { if (((IXYPolygon)item.Geometry).Contains((C.Geometry))) { found = true; if (C.M11Flow != null) { double factor = (double)item.Data[M11Base.ColumnNames.First()]; Factors.Add(factor); C.M11Flow.Multiply(factor); } } } if (!found) { foreach (var C in AllCatchments.Values) { if (((IXYPolygon)item.Geometry).OverLaps((IXYPolygon)C.Geometry)) { if (XYGeometryTools.CalculateSharedArea((IXYPolygon)item.Geometry, (IXYPolygon)C.Geometry) / ((IXYPolygon)C.Geometry).GetArea() > 0.9) { if (C.M11Flow != null) { double factor = (double)item.Data[M11Base.ColumnNames.First()]; Factors.Add(factor); C.M11Flow.Multiply(factor); } break; } } } } }); } if(Factors.Count==0) LogThis("No bias corrections"); else LogThis("Corrected " + Factors.Count + " catchments. Average correction: " + Factors.Average() + ". Max. Correction: " + Factors.Max()+ ". Min. Correction: " + Factors.Min()); }
public override void Initialize(DateTime Start, DateTime End, IEnumerable<Catchment> Catchments) { base.Initialize(Start, End, Catchments); MO5 = new Dictionary<int, int>(); MO5.Add(1, 1); MO5.Add(2, 2); MO5.Add(3, 3); MO5.Add(4, 4); MO5.Add(5, 5); MO5.Add(6, 6); MO5.Add(7, 6); MO5.Add(8, 5); MO5.Add(9, 4); MO5.Add(10, 3); MO5.Add(11, 2); MO5.Add(12, 1); Dictionary<int, GeoRefData> LakeDepths = new Dictionary<int, GeoRefData>(); using (ShapeReader s = new ShapeReader(ShapeFile.FileName)) { foreach (var l in s.GeoData) LakeDepths.Add((int)l.Data[ShapeFile.ColumnNames[0]],l); } foreach (var c in Catchments.Where(ca => ca.BigLake != null)) { GeoRefData lake; if (!LakeDepths.TryGetValue(c.BigLake.BigLakeID, out lake)) { NewMessage(c.BigLake.Name + " removed! No entry found in " + ShapeFile.FileName); c.BigLake = null; } else if (c.M11Flow == null) { NewMessage(c.BigLake.Name + " removed! No Mike11 flow."); c.BigLake = null; } else if (!c.Geometry.Contains( (XYPoint)lake.Geometry)) { c.BigLake = null; } else { c.BigLake.Volume = c.BigLake.Geometry.GetArea() * ((double)lake.Data[ShapeFile.ColumnNames[1] ]); c.BigLake.RetentionTime = c.BigLake.Volume / (c.M11Flow.GetTs(TimeStepUnit.Month).Average * 365.0 * 86400.0); c.BigLake.CurrentNMass = c.BigLake.Volume * ((double)lake.Data[ShapeFile.ColumnNames[2]]) / 1000.0; if ((int)lake.Data[ShapeFile.ColumnNames[3]] != 0) c.BigLake.Start = new DateTime((int)lake.Data[ShapeFile.ColumnNames[3]], 1, 1); else c.BigLake.Start = Start; if ((int)lake.Data[ShapeFile.ColumnNames[4]] != 0) c.BigLake.End = new DateTime((int)lake.Data[ShapeFile.ColumnNames[4]], 1, 1); else c.BigLake.End = End; } } }
private void DeselectPlantsWithShape() { Microsoft.Win32.OpenFileDialog openFileDialog2 = new Microsoft.Win32.OpenFileDialog(); openFileDialog2.Filter = "Known file types (*.shp)|*.shp"; openFileDialog2.ShowReadOnly = true; openFileDialog2.Title = "Select a shape file with plants"; if (openFileDialog2.ShowDialog().Value) { using (ShapeReader sr = new ShapeReader(openFileDialog2.FileName)) { for (int i = 0; i < sr.Data.NoOfEntries; i++) { int plantid = sr.Data.ReadInt(i, "PLANTID"); var p = allPlants.SingleOrDefault(var => var.ID == plantid); if (p != null) { allPlants.Remove(p); Plants.Remove(plantid); } } } BuildPlantList(); } }
public override void Initialize(DateTime Start, DateTime End, IEnumerable<Catchment> Catchments) { base.Initialize(Start, End, Catchments); //Source, Catchment Dictionary<string, int> Sources = new Dictionary<string,int>(); Dictionary<string, XYPoint> PointSources = new Dictionary<string,XYPoint>(); List<XYPoint> points = new List<XYPoint>(); //Read in the points using (ShapeReader sr = new ShapeReader(ShapeFile.FileName)) { foreach (var gd in sr.GeoData) { XYPoint xp = gd.Geometry as XYPoint; if (!PointSources.ContainsKey(gd.Data[ShapeFile.ColumnNames[0]].ToString())) //Some sources are listed multiple times if(gd.Data[ShapeFile.ColumnNames[1]].ToString()=="land") PointSources.Add(gd.Data[ShapeFile.ColumnNames[0]].ToString(), gd.Geometry as XYPoint); } } NewMessage("Distributing sources in catchments"); //Distribute points on catchments Parallel.ForEach(PointSources, (p) => { foreach (var c in Catchments) { if (c.Geometry.Contains(p.Value.X, p.Value.Y)) { //if (c.CoastalZones.Any(co=>co.Contains(p.Value.X, p.Value.Y))) lock (Lock) Sources.Add(p.Key, c.ID); break; } } }); NewMessage(PointSources.Count +" point sources distributed on " + Sources.Values.Distinct().Count().ToString() + " catchments"); Dictionary<string, int> entries = new Dictionary<string, int>(); foreach (var source in Sources.Keys) entries.Add(source, 0); NewMessage("Reading outlet data"); //Read source data and distrubute on catchments using (DBFReader dbf = new DBFReader(DBFFile.FileName)) { int k = 0; for (int i = 0; i < dbf.NoOfEntries; i++) { string id = dbf.ReadString(i, DBFFile.ColumnNames[0]).Trim(); int year = dbf.ReadInt(i, DBFFile.ColumnNames[1]); double value = dbf.ReadDouble(i, DBFFile.ColumnNames[2]); int catchid; if (Sources.TryGetValue(id, out catchid)) { entries[id] += 1; Dictionary<int, double> timevalues; if (!YearlyData.TryGetValue(catchid, out timevalues)) { timevalues = new Dictionary<int, double>(); YearlyData.Add(catchid, timevalues); } if (timevalues.ContainsKey(year)) timevalues[year] += value; else { if (year >= Start.Year) //This also removes some -99 years timevalues.Add(year, value); } } else { //if we have outlet data but no source placed k++; } } NewMessage(k + " time series entries have no points"); } foreach (var c in YearlyData.Values) foreach (var val in c.ToList()) c[val.Key] = val.Value/ ((DateTime.DaysInMonth(val.Key,2) + 337.0) * 86400.0); NewMessage(entries.Values.Count(v => v == 0) + " points have no time series data"); NewMessage("Initialized"); }
public override void Initialize(DateTime Start, DateTime End, IEnumerable<Catchment> Catchments) { base.Initialize(Start, End, Catchments); Dictionary<XYPoint, List<double>> Data = new Dictionary<XYPoint,List<double>>(); XSSFWorkbook hssfwb; using (FileStream file = new FileStream(ExcelFile.FileName, FileMode.Open, FileAccess.Read)) { hssfwb = new XSSFWorkbook(file); } List<IRow> DataRows = new List<IRow>(); var sheet = hssfwb.GetSheet("Ndep_Tot"); for (int row = 1; row <= sheet.LastRowNum; row++) { if (sheet.GetRow(row) != null) //null is when the row only contains empty cells { DataRows.Add(sheet.GetRow(row)); } } using (ShapeReader sr = new ShapeReader(Shapefile.FileName)) { FirstYear = (int)DataRows.First().Cells[0].NumericCellValue; for (int i = 0; i < sr.Data.NoOfEntries; i++) { int icoor = sr.Data.ReadInt(i, "i"); int jcoor = sr.Data.ReadInt(i, "j"); XYPoint point = (XYPoint)sr.ReadNext(i); //Create the timestampseries and set unit to kg/m2/s; var data = DataRows.Where(v => (int)v.Cells[3].NumericCellValue == icoor & (int)v.Cells[4].NumericCellValue == jcoor).OrderBy(v => (int)v.Cells[0].NumericCellValue).Select(v => v.Cells[6].NumericCellValue / (365.0 * 86400.0 * 1.0e6)).ToList(); if(data.Count()>0) Data.Add(point, data); } } foreach (var c in Catchments) { XYPolygon poly = null; if (c.Geometry is XYPolygon) poly = c.Geometry as XYPolygon; else if (c.Geometry is MultiPartPolygon) poly = ((MultiPartPolygon)c.Geometry).Polygons.First(); //Just use the first polygon double LakeArea = c.Lakes.Sum(l => l.Geometry.GetArea()); //Get the area of the lakes if (c.BigLake != null) //Add the big lake LakeArea += c.BigLake.Geometry.GetArea(); if (poly != null) { var point = new XYPoint(poly.PlotPoints.First().Longitude, poly.PlotPoints.First().Latitude); //Take one point in the polygon var closestpoint = Data.Keys.Select(p => new Tuple<XYPoint, double>(p, p.GetDistance(point))).OrderBy(s => s.Item2).First().Item1; deposition.Add(c.ID, new List<double>(Data[closestpoint].Select(v=>v*LakeArea))); } } NewMessage("Initialized"); }