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 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(); foreach (DataRow dr in DTread.Rows) { Console.WriteLine(dr[0].ToString()); p = (IXYPoint)PSR.ReadNext(); Console.WriteLine(p.X.ToString() + " " + p.Y.ToString()); } }
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 static C1.Win.Map.VectorLayer LoadShpFile(string shpFile, string dbfFile, ProcessVectorItem processVector) { using (var shpStream = OpenFile(shpFile)) using (var dbfStream = OpenFile(dbfFile)) { var records = ShapeReader.Read(shpStream, dbfStream); var items = records.Select(record => { var vector = CreateVector(record); if (vector != null && processVector != null) { processVector(vector, record.Data); } return(vector); }); var layer = new C1.Win.Map.VectorLayer(); foreach (var item in items) { layer.Items.Add(item); } return(layer); } }
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(); }
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 ReadProjectionFile() { string File = @"..\..\..\Testdata\kontinuitet.prj"; ShapeReader sr = new ShapeReader(File); var proj = sr.Projection; }
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 = @"..\..\..\..\MikeSheTools\TestData\CommandAreas.Shp"; ShapeReader target = new ShapeReader(File); var geo = target.ReadNext(0); double d =((XYPolygon)geo).GetArea(); Assert.IsTrue(0 < d); }
public ShapefileFeature(ShapeReader shapeReader, DbaseReader dbfReader, ShapeLocationInFileInfo shapeLocation, IGeometryFactory geoFactory) { m_ShapeReader = shapeReader; m_GeoFactory = geoFactory; m_ShapeLocationInfo = shapeLocation; m_LazyGeometry = new Lazy <IGeometry>(() => m_ShapeReader.ReadShapeAtOffset(m_ShapeLocationInfo.OffsetFromStartOfFile, m_GeoFactory), LazyThreadSafetyMode.ExecutionAndPublication); m_DbaseReader = dbfReader; m_LazyAttributeTable = new Lazy <IAttributesTable>(() => m_DbaseReader.ReadEntry(m_ShapeLocationInfo.ShapeIndex), LazyThreadSafetyMode.ExecutionAndPublication); }
public ShapefileFeature(ShapeReader shapeReader, DbaseReader dbfReader, ShapeLocationInFileInfo shapeLocation, IGeometryFactory geoFactory) { m_ShapeReader = shapeReader; m_GeoFactory = geoFactory; m_ShapeLocationInfo = shapeLocation; m_LazyGeometry = new Lazy<IGeometry>(() => m_ShapeReader.ReadShapeAtOffset(m_ShapeLocationInfo.OffsetFromStartOfFile, m_GeoFactory), LazyThreadSafetyMode.ExecutionAndPublication); m_DbaseReader = dbfReader; m_LazyAttributeTable = new Lazy<IAttributesTable>(() => m_DbaseReader.ReadEntry(m_ShapeLocationInfo.ShapeIndex), LazyThreadSafetyMode.ExecutionAndPublication); }
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 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 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 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)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 void ShapeReaderSkippingTest() { const string path = @"Data\Shapefiles\shp-no-m\SPATIAL_F_LUFTNINGSVENTIL.shp"; var source = new PointShapefileShapeSource(path); var target = new ShapeReader(source); target.PageSize = 10; int expectedStartIndex = 0; foreach (var page in target) { Assert.AreEqual(expectedStartIndex, page.Keys.Min(), "Shape reader skipped at least one entry."); expectedStartIndex = page.Keys.Max() + 1; } }
public static void LoadShape(this C1VectorLayer vl, Stream stream, Stream dbfStream, Location location, bool centerAndZoom, ProcessShapeItem processShape) { Dictionary <C1VectorItemBase, C1ShapeAttributes> vects = ShapeReader.Read(stream, dbfStream); vl.BeginUpdate(); foreach (C1VectorItemBase vect in vects.Keys) { if (processShape != null) { processShape(vect, vects[vect], location); } vl.Children.Add(vect); } vl.EndUpdate(); }
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 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 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 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; } } }
public void importShapeCallback(string path, string layer, Color color) { Bitmap bitmap = null; ShapeReader shape = new ShapeReader(path); GMapOverlay overlay = new GMapOverlay(layer); gMap.Overlays.Add(overlay); shape.errorHandler += errorHandlerCallback; shape.read(); ESRIShapeFile s = shape.getShape(); if (s.ShapeType == 3 || s.ShapeType == 13) { GMapRoute line_layer; PolyLineZ[] polyLines = s.PolyLineZ; foreach (PolyLineZ polyLine in polyLines) { PointLatLng[] points = polyLine.points; line_layer = new GMapRoute(points, "lines"); //TODO get carriage number line_layer.Stroke = new Pen(color, 1); overlay.Routes.Add(line_layer); } } else if (s.ShapeType == 1) { ShapeFile.Point[] points = s.Point; bitmap = ColorTable.getBitmap(ColorTable.ColorCrossDict, color.Name, 4); int id = 0; foreach (ShapeFile.Point point in points) { PointLatLng pointLatLng = new PointLatLng(point.y, point.x); MarkerTag tag = new MarkerTag(color.Name, id); tag.Dictionary = ColorTable.ColorCrossDict; GMapMarker marker = new GMarkerGoogle(pointLatLng, bitmap); marker.Tag = tag; overlay.Markers.Add(marker); id++; } GMapMarker[] markersArr = overlay.Markers.ToArray <GMapMarker>(); mOverlayDict.Add(layer, markersArr); } else if (s.ShapeType == 8) { MultiPoint[] points = s.MultiPoint; bitmap = ColorTable.getBitmap(ColorTable.ColorCrossDict, color.Name, 4); int id = 0; foreach (MultiPoint point in points) { PointLatLng[] pointsLatLng = point.points; foreach (PointLatLng p in pointsLatLng) { MarkerTag tag = new MarkerTag(color.Name, id); tag.Dictionary = ColorTable.ColorCrossDict; GMapMarker marker = new GMarkerGoogle(p, bitmap); marker.Tag = tag; overlay.Markers.Add(marker); id++; } } GMapMarker[] markersArr = overlay.Markers.ToArray <GMapMarker>(); mOverlayDict.Add(layer, markersArr); } addListItem(ColorTable.ColorCrossDict, overlay, color.Name); //if (bitmap != null) //{ // imageList.Images.Add(bitmap); //} //ListViewItem layerItem = new ListViewItem(overlay.Id, layerCount); //layerCount++; //layerItem.Text = overlay.Id; //layerItem.Checked = true; //mOverlay = overlay; //listLayers.SmallImageList = imageList; //listLayers.Items.Add(layerItem); ////addListItem(ColorTable.ColorCrossDict, overlay, color.Name); //overlay.IsVisibile = true; //mOverlay.IsVisibile = true; ////shape.readDBF(); }
public HttpResponseMessage Draw(double? minLon, double? maxLon, double? minLat, double? maxLat, int? maxImgWidth, int? maxImgHeight) { var shapefilePath = HostingEnvironment.MapPath("~/App_Data/builtupp_usa/builtupp_usa.shp"); ITransformation<GeographicCoordinate, Point2> transformation = null; var targetCrs = EpsgMicroDatabase.Default.GetCrs(3005); LongitudeDegreeRange dataLongitudeRange; Range dataLatitudeRange; using (var shapeFile = Shapefile.Open(shapefilePath)) { dataLongitudeRange = new LongitudeDegreeRange(shapeFile.Extent.MinX, shapeFile.Extent.MaxX); dataLatitudeRange = new Range(shapeFile.Extent.MinY, shapeFile.Extent.MaxY); var dataCrs = EpsgMicroDatabase.Default.GetCrs(4326); var pathGenerator = new EpsgCrsCoordinateOperationPathGenerator(); var paths = pathGenerator.Generate(dataCrs, targetCrs); var compiler = new StaticCoordinateOperationCompiler(); var firstTransfom = paths.Select(p => { return compiler.Compile(p); }).First(x => x != null); transformation = firstTransfom as ITransformation<GeographicCoordinate, Point2>; if (transformation == null && firstTransfom is IEnumerable<ITransformation>) transformation = new CompiledConcatenatedTransformation<GeographicCoordinate, Point2>((IEnumerable<ITransformation>)firstTransfom); } var geoMbrMin = new GeographicCoordinate(minLat ?? dataLatitudeRange.Low, minLon ?? dataLongitudeRange.Start); var geoMbrMax = new GeographicCoordinate(maxLat ?? dataLatitudeRange.High, maxLon ?? dataLongitudeRange.End); var geoMbrTL = new GeographicCoordinate(geoMbrMax.Latitude, geoMbrMin.Longitude); var geoMbrTR = new GeographicCoordinate(geoMbrMin.Latitude, geoMbrMax.Longitude); var projectedMbrPoints = new[] { geoMbrMin, geoMbrMax, geoMbrTL, geoMbrTR, new GeographicCoordinate(geoMbrMin.Latitude, Math.Abs(geoMbrMin.Longitude + geoMbrMax.Longitude) / 2.0) } .Select(transformation.TransformValue) .ToArray(); var projectedExtent = new Mbr( new Point2(projectedMbrPoints.Min(x => x.X), projectedMbrPoints.Min(x => x.Y)), new Point2(projectedMbrPoints.Max(x => x.X), projectedMbrPoints.Max(x => x.Y)) ); var geogMapOrigin = new GeographicCoordinate(dataLatitudeRange.Mid, dataLongitudeRange.Mid); var mapOrigin = transformation.TransformValue(geogMapOrigin); var mapOffset = new Vector2(0/*-(mapOrigin.X - projectedExtent.X.Mid)*/, projectedExtent.Height / 2.0); var imageSizeLimits = new Vector2(maxImgWidth ?? 300, maxImgHeight ?? 300); if (imageSizeLimits.X > 4096 || imageSizeLimits.Y > 4096) throw new ArgumentException("Image size too large"); var dataRatio = new Vector2(projectedExtent.Width / imageSizeLimits.X, projectedExtent.Height / imageSizeLimits.Y); var lowCorner = projectedExtent.Min; Vector2 desiredImageSize; double imageScaleFactor; if (dataRatio.Y < dataRatio.X) { imageScaleFactor = imageSizeLimits.X / projectedExtent.Width; desiredImageSize = new Vector2(imageSizeLimits.X, (int)(projectedExtent.Height * imageScaleFactor)); } else { imageScaleFactor = imageSizeLimits.Y / projectedExtent.Height; desiredImageSize = new Vector2((int)(projectedExtent.Width * imageScaleFactor), imageSizeLimits.Y); } using (var image = new System.Drawing.Bitmap((int)desiredImageSize.X, (int)desiredImageSize.Y)) using (var graphics = Graphics.FromImage(image)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var shapeSource = new PointShapefileShapeSource(shapefilePath); var shapeReader = new ShapeReader(shapeSource); using (var shapeEnumerator = shapeReader.GetEnumerator()) { var sourceCoordinates = ReadPagesToGeographicCoordinate(shapeEnumerator).SelectMany(x => x); var pointColor = Color.Black; var circleFillBrush = new SolidBrush(Color.FromArgb(64,16,64,128)); var featureRadius = 3.0; var featureDiameter = featureRadius * 2; var featureDiameterFloat = (float)featureDiameter; var topLeftOffset = new Vector2(-featureRadius,-featureRadius); foreach (var transformedPoint in transformation.TransformValues(sourceCoordinates)) { var offsetPoint = transformedPoint.Difference(lowCorner).Add(mapOffset); var scaledPoint = offsetPoint.GetScaled(imageScaleFactor); var screenPoint = new Point2(scaledPoint.X, image.Height - scaledPoint.Y); var drawTopLeft = screenPoint.Add(topLeftOffset); graphics.FillEllipse(circleFillBrush, (float)drawTopLeft.X, (float)drawTopLeft.Y, featureDiameterFloat, featureDiameterFloat); } } var result = new HttpResponseMessage(HttpStatusCode.OK); byte[] imageBytes; using (var memoryStream = new MemoryStream()) { image.Save(memoryStream, ImageFormat.Png); imageBytes = memoryStream.ToArray(); } result.Content = new ByteArrayContent(imageBytes); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); return result; } }
public void NovoTest() { TheisAnalysis target = new TheisAnalysis(); // TODO: Initialize to an appropriate value IXYPoint PumpingWell = new XYPoint(0, 0); double PumpingRate = 15 / 3600.0; // double Storativity = 5e-3; double Transmissivity = 1e-3; // List <IXYPoint> InjectionWells = new List <IXYPoint>(); // InjectionWells.Add(new XYPoint(704288.01, 6201186.04)); // InjectionWells.Add(new XYPoint(704455.3,6201201.6 )); // InjectionWells.Add(new XYPoint(704621.99, 6201219)); //// InjectionWells.Add(new XYPoint(704951.98, 6201249.18)); List <IXYPoint> ExtractionWells = new List <IXYPoint>(); //ExtractionWells.Add(new XYPoint(704934.54, 6200994.85)); //ExtractionWells.Add(new XYPoint(704896.26, 6200720.37)); //ExtractionWells.Add(new XYPoint(704940, 6200550)); //InjectionWells.Add(new XYPoint(704698, 6202442)); //ExtractionWells.Add(new XYPoint(704850, 6202365)); using (ShapeReader sr = new ShapeReader(@"C:\Users\Jacob\Dropbox\Enopsol\BiogenLocation.shp")) { foreach (var g in sr.GeoData) { if ((int)g.Data[0] == 1) { InjectionWells.Add((IXYPoint)g.Geometry); } else if ((int)g.Data[0] == 2) { ExtractionWells.Add((IXYPoint)g.Geometry); } } } var d = target.Drawdown(InjectionWells.First(), 56.0 / 3600.0, Storativity, Transmissivity, TimeSpan.FromHours(4), new XYPoint(InjectionWells.First().X + 2, InjectionWells.First().Y + 2)); List <List <double> > drawdowns = new List <List <double> >(); drawdowns.Add(new List <double>()); drawdowns.Add(new List <double>()); drawdowns.Add(new List <double>()); //Frederiksgade IXYPoint ObservationPoint = new XYPoint(705669, 6202256); int j = 0; for (int i = 0; i < 100; i++) { double s = 0; TimeSpan Time = TimeSpan.FromDays(i); foreach (var w in ExtractionWells) { s += target.Drawdown(w, +PumpingRate, Storativity, Transmissivity, Time, ObservationPoint); } drawdowns[j].Add(s); foreach (var w in InjectionWells) { s += target.Drawdown(w, -PumpingRate, Storativity, Transmissivity, Time, ObservationPoint); } drawdowns[j + 1].Add(s); double dw = target.Drawdown(ExtractionWells[0], PumpingRate, Storativity, Transmissivity, Time, new XYPoint(ExtractionWells[0].X + 0.5, ExtractionWells[0].Y + 0.5)); drawdowns[j + 2].Add(dw); } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"c:\temp\enopsol.txt")) { for (int i = 0; i < 100; i++) { sw.WriteLine(drawdowns[0][i].ToString() + "\t" + drawdowns[1][i].ToString() + "\t" + drawdowns[2][i].ToString()); } } }
/// <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(); } }
/// <summary> /// Update header extents from the geometries in a IShapeSource /// </summary> /// <param name="src"></param> protected void UpdateExtents(IShapeSource src) { var sr = new ShapeReader(src); Extent env = null; foreach (var page in sr) { foreach (var shape in page) { Extent shapeExtent = shape.Value.Range.Extent; if (env == null) { env = (Extent)shapeExtent.Clone(); } else { env.ExpandToInclude(shapeExtent); } } } // Extents for an empty file are unspecified according to the specification, so do nothing if (null == env) return; var sh = new ShapefileHeader(Filename); sh.SetExtent(env); sh.Save(); }
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"); }
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; } } } }
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 HttpResponseMessage Draw(double?minLon, double?maxLon, double?minLat, double?maxLat, int?maxImgWidth, int?maxImgHeight) { var shapefilePath = HostingEnvironment.MapPath("~/App_Data/builtupp_usa/builtupp_usa.shp"); ITransformation <GeographicCoordinate, Point2> transformation = null; var targetCrs = EpsgMicroDatabase.Default.GetCrs(3005); LongitudeDegreeRange dataLongitudeRange; Range dataLatitudeRange; using (var shapeFile = Shapefile.Open(shapefilePath)) { dataLongitudeRange = new LongitudeDegreeRange(shapeFile.Extent.MinX, shapeFile.Extent.MaxX); dataLatitudeRange = new Range(shapeFile.Extent.MinY, shapeFile.Extent.MaxY); var dataCrs = EpsgMicroDatabase.Default.GetCrs(4326); var pathGenerator = new EpsgCrsCoordinateOperationPathGenerator(); var paths = pathGenerator.Generate(dataCrs, targetCrs); var compiler = new StaticCoordinateOperationCompiler(); var firstTransfom = paths.Select(p => { return(compiler.Compile(p)); }).First(x => x != null); transformation = firstTransfom as ITransformation <GeographicCoordinate, Point2>; if (transformation == null && firstTransfom is IEnumerable <ITransformation> ) { transformation = new CompiledConcatenatedTransformation <GeographicCoordinate, Point2>((IEnumerable <ITransformation>)firstTransfom); } } var geoMbrMin = new GeographicCoordinate(minLat ?? dataLatitudeRange.Low, minLon ?? dataLongitudeRange.Start); var geoMbrMax = new GeographicCoordinate(maxLat ?? dataLatitudeRange.High, maxLon ?? dataLongitudeRange.End); var geoMbrTL = new GeographicCoordinate(geoMbrMax.Latitude, geoMbrMin.Longitude); var geoMbrTR = new GeographicCoordinate(geoMbrMin.Latitude, geoMbrMax.Longitude); var projectedMbrPoints = new[] { geoMbrMin, geoMbrMax, geoMbrTL, geoMbrTR, new GeographicCoordinate(geoMbrMin.Latitude, Math.Abs(geoMbrMin.Longitude + geoMbrMax.Longitude) / 2.0) } .Select(transformation.TransformValue) .ToArray(); var projectedExtent = new Mbr( new Point2(projectedMbrPoints.Min(x => x.X), projectedMbrPoints.Min(x => x.Y)), new Point2(projectedMbrPoints.Max(x => x.X), projectedMbrPoints.Max(x => x.Y)) ); var geogMapOrigin = new GeographicCoordinate(dataLatitudeRange.Mid, dataLongitudeRange.Mid); var mapOrigin = transformation.TransformValue(geogMapOrigin); var mapOffset = new Vector2(0 /*-(mapOrigin.X - projectedExtent.X.Mid)*/, projectedExtent.Height / 2.0); var imageSizeLimits = new Vector2(maxImgWidth ?? 300, maxImgHeight ?? 300); if (imageSizeLimits.X > 4096 || imageSizeLimits.Y > 4096) { throw new ArgumentException("Image size too large"); } var dataRatio = new Vector2(projectedExtent.Width / imageSizeLimits.X, projectedExtent.Height / imageSizeLimits.Y); var lowCorner = projectedExtent.Min; Vector2 desiredImageSize; double imageScaleFactor; if (dataRatio.Y < dataRatio.X) { imageScaleFactor = imageSizeLimits.X / projectedExtent.Width; desiredImageSize = new Vector2(imageSizeLimits.X, (int)(projectedExtent.Height * imageScaleFactor)); } else { imageScaleFactor = imageSizeLimits.Y / projectedExtent.Height; desiredImageSize = new Vector2((int)(projectedExtent.Width * imageScaleFactor), imageSizeLimits.Y); } using (var image = new System.Drawing.Bitmap((int)desiredImageSize.X, (int)desiredImageSize.Y)) using (var graphics = Graphics.FromImage(image)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var shapeSource = new PointShapefileShapeSource(shapefilePath); var shapeReader = new ShapeReader(shapeSource); using (var shapeEnumerator = shapeReader.GetEnumerator()) { var sourceCoordinates = ReadPagesToGeographicCoordinate(shapeEnumerator).SelectMany(x => x); var pointColor = Color.Black; var circleFillBrush = new SolidBrush(Color.FromArgb(64, 16, 64, 128)); var featureRadius = 3.0; var featureDiameter = featureRadius * 2; var featureDiameterFloat = (float)featureDiameter; var topLeftOffset = new Vector2(-featureRadius, -featureRadius); foreach (var transformedPoint in transformation.TransformValues(sourceCoordinates)) { var offsetPoint = transformedPoint.Difference(lowCorner).Add(mapOffset); var scaledPoint = offsetPoint.GetScaled(imageScaleFactor); var screenPoint = new Point2(scaledPoint.X, image.Height - scaledPoint.Y); var drawTopLeft = screenPoint.Add(topLeftOffset); graphics.FillEllipse(circleFillBrush, (float)drawTopLeft.X, (float)drawTopLeft.Y, featureDiameterFloat, featureDiameterFloat); } } var result = new HttpResponseMessage(HttpStatusCode.OK); byte[] imageBytes; using (var memoryStream = new MemoryStream()) { image.Save(memoryStream, ImageFormat.Png); imageBytes = memoryStream.ToArray(); } result.Content = new ByteArrayContent(imageBytes); result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png"); return(result); } }
public ShapefileFeature(ShapeReader shapeReader, DbaseReader dbfReader, ShapeLocationInFileInfo shapeLocation, GeometryFactory geoFactory) { FeatureId = shapeLocation.ShapeIndex; _lazyGeometry = new Lazy <Geometry>(() => shapeReader.ReadShapeAtOffset(shapeLocation.OffsetFromStartOfFile, geoFactory), LazyThreadSafetyMode.ExecutionAndPublication); _lazyAttributeTable = new Lazy <IAttributesTable>(() => dbfReader.ReadEntry(shapeLocation.ShapeIndex), LazyThreadSafetyMode.ExecutionAndPublication); }
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."); }