Example #1
0
        private void TestBugMultipolygonHShuntao()
        {
            IGeometryCollection gc1 = null;
            IGeometryCollection gc2 = null;
            string file = "BJmultipolygon.shp";
            if (!File.Exists(file))
                throw new FileNotFoundException();

            // Test with Default ShapefileReader
            try
            {                
                ShapefileReader sfr = new ShapefileReader(file);
                gc1 = sfr.ReadAll();                                                          
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // Test with MyShapefileReader (only for debug purpose!)
            try
            {
                MyShapeFileReader reader = new MyShapeFileReader();
                gc2 = reader.Read(file);                                
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // Check for equality
            if (!gc1.EqualsExact(gc2))
                throw new TopologyException("Both geometries must be equals!");
        }
Example #2
0
        private IGeometry LoadGraphResult()
        {
            var path = "graphresult.shp";            
            Assert.IsTrue(Path.GetExtension(path) == shp);

            var reader = new ShapefileReader(path);
            var coll = reader.ReadAll();
            Assert.AreEqual(1, coll.Count);

            var geom = coll.GetGeometryN(0);
            Assert.IsInstanceOfType(typeof(IMultiLineString), geom);
            var str = geom.GetGeometryN(0);
            Assert.IsInstanceOfType(typeof(ILineString), str);
            return str;
        }
Example #3
0
            /// <summary>
            /// Initializes a new instance of the <see cref="ShapefileEnumerator"/> class.
            /// </summary>
            /// <param name="shapefile"></param>
            public ShapefileEnumerator(ShapefileReader shapefile)
            {                
                _parent = shapefile;

                // create a file stream for each enumerator that is given out. This allows the same file
                // to have one or more enumerator. If we used the parents stream - than only one IEnumerator 
                // could be given out.
                FileStream stream = new FileStream(_parent._filename, FileMode.Open, FileAccess.Read, FileShare.Read);
                _shpBinaryReader = new BigEndianBinaryReader(stream);

                // skip header - since parent has already read this.
                _shpBinaryReader.ReadBytes(100);
                ShapeGeometryType type = _parent._mainHeader.ShapeType;
                _handler = Shapefile.GetShapeHandler(type);
                if (_handler == null) 
                    throw new NotSupportedException("Unsuported shape type:" + type);
            }
Example #4
0
            /// <summary>
            /// Initializes a new instance of the <see cref="ShapefileEnumerator"/> class.
            /// </summary>
            /// <param name="shapefile"></param>
            public ShapefileEnumerator(ShapefileReader shapefile)
            {
                _parent = shapefile;

                // create a file stream for each enumerator that is given out. This allows the same file
                // to have one or more enumerator. If we used the parents stream - than only one IEnumerator
                // could be given out.
                FileStream stream = new FileStream(_parent._filename, FileMode.Open, FileAccess.Read, FileShare.Read);

                _shpBinaryReader = new BigEndianBinaryReader(stream);

                // skip header - since parent has already read this.
                _shpBinaryReader.ReadBytes(100);
                ShapeGeometryType type = _parent._mainHeader.ShapeType;

                _handler = Shapefile.GetShapeHandler(type);
                if (_handler == null)
                {
                    throw new NotSupportedException("Unsuported shape type:" + type);
                }
            }
        /// <summary>
        /// Initializes a new instance of the ShapefileDataReader class.
        /// </summary>
        /// <param name="filename">The shapefile to read (minus the .shp extension)</param>
        ///<param name="geometryFactory">The GeometryFactory to use.</param>
        public ShapefileDataReader(string filename, IGeometryFactory geometryFactory)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("filename");
            }
            if (geometryFactory == null)
            {
                throw new ArgumentNullException("geometryFactory");
            }
            _geometryFactory = geometryFactory;
            _open            = true;

            if (filename.ToLower().EndsWith(".shp"))
            {
                filename = filename.ToLower().Replace(".shp", String.Empty);
            }

            _dbfReader = new DbaseFileReader(filename + ".dbf");
            _shpReader = new ShapefileReader(filename + ".shp", geometryFactory);

            _dbfHeader   = _dbfReader.GetHeader();
            _recordCount = _dbfHeader.NumRecords;

            // copy dbase fields to our own array. Insert into the first position, the shape column
            _dbaseFields    = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1];
            _dbaseFields[0] = DbaseFieldDescriptor.ShapeField();
            for (int i = 0; i < _dbfHeader.Fields.Length; i++)
            {
                _dbaseFields[i + 1] = _dbfHeader.Fields[i];
            }

            _shpHeader     = _shpReader.Header;
            _dbfEnumerator = _dbfReader.GetEnumerator();
            _shpEnumerator = _shpReader.GetEnumerator();
            _moreRecords   = true;
        }
Example #6
0
        public void BuildGraphFromCompleteGraphShapefile()
        {
            var shapepath = "graph.shp";
            var count = 1179;

            Assert.IsTrue(File.Exists(shapepath));
            var reader = new ShapefileReader(shapepath);
            var edges = reader.ReadAll();
            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(GeometryCollection), edges);
            Assert.AreEqual(count, edges.NumGeometries);

            // Insert arbitrary userdata
            for (var i = 0; i < count; i++)
            {
                var g = edges.GetGeometryN(i) as IMultiLineString;
                Assert.IsNotNull(g);
                var ls = g.GetGeometryN(0) as ILineString;
                Assert.IsNotNull(ls);

                Assert.IsNull(ls.UserData);
                ls.UserData = i;
                Assert.IsNotNull(ls.UserData);
            }

            var startls = edges.GetGeometryN(515).GetGeometryN(0) as ILineString;
            Assert.IsNotNull(startls);
            var startPoint = startls.EndPoint;
            Assert.AreEqual(2317300d, startPoint.X);
            Assert.AreEqual(4843961d, startPoint.Y);

            var endls = edges.GetGeometryN(141).GetGeometryN(0) as ILineString; ;
            Assert.IsNotNull(endls);
            var endPoint = endls.StartPoint;
            Assert.AreEqual(2322739d, endPoint.X);
            Assert.AreEqual(4844539d, endPoint.Y);

            var finder = new PathFinder(true);
            foreach (IMultiLineString mlstr in edges.Geometries)
            {
                Assert.AreEqual(1, mlstr.NumGeometries);
                var str = mlstr.GetGeometryN(0) as ILineString;
                Assert.IsNotNull(str);
                Assert.IsNotNull(str.UserData);
                Assert.IsTrue(finder.Add(str));
            }
            finder.Initialize();

            var expectedResultCount = 8;
            var path = finder.Find(startPoint, endPoint);
            Assert.IsNotNull(path);
            Assert.IsInstanceOfType(typeof (IMultiLineString), path);
            var strings = (IMultiLineString) path;            
            Assert.AreEqual(expectedResultCount, strings.NumGeometries);
            foreach (var g in strings.Geometries)
            {
                Assert.IsNotNull(g.UserData);
                Console.WriteLine("{0} : {1}", g.UserData, g);
            }

            var reversedPath = finder.Find(endPoint, startPoint);
            Assert.IsNotNull(reversedPath);
            Assert.IsInstanceOfType(typeof(IMultiLineString), reversedPath);

            var reversedStrings = (IMultiLineString) reversedPath;
            Assert.AreEqual(expectedResultCount, reversedStrings.NumGeometries);
            foreach (var g in reversedStrings.Geometries)
            {
                Assert.IsNotNull(g.UserData);
                Console.WriteLine("{0} : {1}", g.UserData, g);
            }

            for (var i = 0; i < expectedResultCount; i++)
            {
                var item = strings.GetGeometryN(i);
                var itemReversed = strings.GetGeometryN(expectedResultCount - 1 - i);
                Assert.AreNotEqual(item.UserData, itemReversed.UserData);
                Assert.AreNotEqual(item, itemReversed);
            }
        }
        public void BuildGraphFromStradeShapefile()
        {
            string shapepath = "strade_fixed.shp";
            int count = 703;

            Assert.IsTrue(File.Exists(shapepath));
            ShapefileReader reader = new ShapefileReader(shapepath);
            IGeometryCollection edges = reader.ReadAll();
            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(GeometryCollection), edges);
            Assert.AreEqual(count, edges.NumGeometries);

            ICoordinate startCoord = new Coordinate(2317300d, 4843961d);
            ICoordinate endCoord = new Coordinate(2322739d, 4844539d);

            bool startFound = false;
            bool endFound = false;            
            GraphBuilder2 builder = new GraphBuilder2(true);
            foreach (IMultiLineString mlstr in edges.Geometries)
            {
                Assert.AreEqual(1, mlstr.NumGeometries);
                ILineString str = mlstr.GetGeometryN(0) as ILineString;
                Assert.IsNotNull(str);
                Assert.IsTrue(builder.Add(str));

                if (!startFound)
                {
                    List<ICoordinate> coords = new List<ICoordinate>(str.Coordinates);
                    if (coords.Contains(startCoord))
                        startFound = true;
                }

                if (!endFound)
                {
                    List<ICoordinate> coords = new List<ICoordinate>(str.Coordinates);
                    if (coords.Contains(endCoord))
                        endFound = true;
                }
            }
            builder.Initialize();
            Assert.IsTrue(startFound);
            Assert.IsTrue(endFound);

            ILineString path = builder.Perform(startCoord, endCoord);
            Assert.IsNotNull(path);
            SaveGraphResult(path);

            ILineString reverse = builder.Perform(startCoord, endCoord);
            Assert.IsNotNull(reverse);
            Assert.AreEqual(path, reverse.Reverse());
        }
 /// <summary>
 /// Loads the shapefile as a graph allowing SP analysis to be carried out
 /// </summary>
 /// <param name="fileName">The name of the shape file we want to load</param>
 /// <param name="src"></param>
 /// <param name="dst"></param>
 public ILineString TestGraphBuilder2WithSampleGeometries(string fileName, ICoordinate src, ICoordinate dst)
 {
     ShapefileReader reader = new ShapefileReader(fileName);
     IGeometryCollection edges = reader.ReadAll();
     return TestGraphBuilder2WithSampleGeometries(edges, src, dst);
 }
        public void BuildGraphFromCompleteGraphShapefile()
        {
            string shapepath = "graph.shp";
            int count = 1179;

            Assert.IsTrue(File.Exists(shapepath));
            ShapefileReader reader = new ShapefileReader(shapepath);
            IGeometryCollection edges = reader.ReadAll();
            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(GeometryCollection), edges);
            Assert.AreEqual(count, edges.NumGeometries);

            ILineString startls = edges.GetGeometryN(515).GetGeometryN(0) as ILineString;
            Assert.IsNotNull(startls);
            IPoint startPoint = startls.EndPoint;
            Assert.AreEqual(2317300d, startPoint.X);
            Assert.AreEqual(4843961d, startPoint.Y);

            ILineString endls = edges.GetGeometryN(141).GetGeometryN(0) as ILineString; ;
            Assert.IsNotNull(endls);
            IPoint endPoint = endls.StartPoint;
            Assert.AreEqual(2322739d, endPoint.X);
            Assert.AreEqual(4844539d, endPoint.Y);

            GraphBuilder2 builder = new GraphBuilder2(true);
            foreach (IMultiLineString mlstr in edges.Geometries)
            {
                Assert.AreEqual(1, mlstr.NumGeometries);
                ILineString str = mlstr.GetGeometryN(0) as ILineString;
                Assert.IsNotNull(str);
                Assert.IsTrue(builder.Add(str));
            }
            builder.Initialize();

            ILineString path = builder.Perform(startPoint, endPoint);
            Assert.IsNotNull(path);
            SaveGraphResult(path);

            ILineString reverse = builder.Perform(endPoint, startPoint);
            Assert.IsNotNull(reverse);
            Assert.AreEqual(path, reverse.Reverse());
        }
        public void BuildGraphFromMinimalGraphShapefile()
        {
            string shapepath = "minimalgraph.shp";
            int count = 15;

            Assert.IsTrue(File.Exists(shapepath));
            ShapefileReader reader = new ShapefileReader(shapepath);
            IGeometryCollection edges = reader.ReadAll();
            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(GeometryCollection), edges);
            Assert.AreEqual(count, edges.NumGeometries);

            ILineString startls = edges.GetGeometryN(0).GetGeometryN(0) as ILineString;
            Assert.IsNotNull(startls);
            ILineString endls = edges.GetGeometryN(5).GetGeometryN(0) as ILineString; ;
            Assert.IsNotNull(endls);

            GraphBuilder2 builder = new GraphBuilder2(true);
            foreach (IMultiLineString mlstr in edges.Geometries)
            {
                Assert.AreEqual(1, mlstr.NumGeometries);
                ILineString str = mlstr.GetGeometryN(0) as ILineString;
                Assert.IsNotNull(str);
                Assert.IsTrue(builder.Add(str));
            }
            builder.Initialize();
            
            ILineString path = builder.Perform(startls.StartPoint, endls.EndPoint);
            Assert.IsNotNull(path);
        }
Example #11
0
		/// <summary>
		/// Initializes a new instance of the ShapefileDataReader class.
		/// </summary>
		/// <param name="filename">The shapefile to read (minus the .shp extension)</param>
		///<param name="geometryFactory">The GeometryFactory to use.</param>
		public ShapefileDataReader(string filename, IGeometryFactory geometryFactory) 
		{
			if (filename == null)
				throw new ArgumentNullException("filename");
			if (geometryFactory == null)
				throw new ArgumentNullException("geometryFactory");
			_geometryFactory = geometryFactory;
			_open = true;			

			if (filename.ToLower().EndsWith(".shp"))
				filename = filename.ToLower().Replace(".shp",String.Empty);
			
			 _dbfReader = new DbaseFileReader(filename + ".dbf");
			 _shpReader = new ShapefileReader(filename + ".shp", geometryFactory);

			_dbfHeader =  _dbfReader.GetHeader();
			_recordCount = _dbfHeader.NumRecords;			
			
			// copy dbase fields to our own array. Insert into the first position, the shape column
			_dbaseFields = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1];
			_dbaseFields[0] = DbaseFieldDescriptor.ShapeField();
			for(int i=0; i < _dbfHeader.Fields.Length; i++)
				_dbaseFields[i+1] = _dbfHeader.Fields[i];
			
			_shpHeader = _shpReader.Header;			
			_dbfEnumerator = _dbfReader.GetEnumerator();
			_shpEnumerator = _shpReader.GetEnumerator();
			_moreRecords = true;
		}
Example #12
0
        public void BuildGraphFromMinimalGraphShapefile()
        {
            string path = "minimalgraph.shp";
            int count = 15;
            Assert.IsTrue(File.Exists(path));
            ShapefileReader reader = new ShapefileReader(path);
            IGeometryCollection edges = reader.ReadAll();
            Assert.IsNotNull(edges);
            Assert.IsInstanceOfType(typeof(GeometryCollection), edges);
            Assert.AreEqual(count, edges.NumGeometries);

            ILineString startls = null;
            // Build graph
            Dictionary<IEdge<IGeometry>, double> consts = new Dictionary<IEdge<IGeometry>, double>(edges.NumGeometries);
            AdjacencyGraph<IGeometry, IEdge<IGeometry>> graph = new AdjacencyGraph<IGeometry, IEdge<IGeometry>>(true);
            foreach (IMultiLineString mlstr in edges.Geometries)
            {
                Assert.AreEqual(1, mlstr.NumGeometries);
                ILineString str = (ILineString) mlstr.GetGeometryN(0);
                if (startls == null)
                    startls = str;

                // Add vertex 1
                IGeometry vertex1 = str.StartPoint;
                Assert.IsNotNull(vertex1);
                if (!graph.ContainsVertex(vertex1))
                {
                    Debug.WriteLine(String.Format("Adding vertex {0} to the list", vertex1));
                    graph.AddVertex(vertex1);
                }
                else Debug.WriteLine(String.Format("Vertex {0} already present", vertex1));

                // Add vertex 2
                IGeometry vertex2 = str.EndPoint;
                Assert.IsNotNull(vertex2);
                if (!graph.ContainsVertex(vertex2))
                {
                    Debug.WriteLine(String.Format("Adding vertex {0} to the list", vertex2));
                    graph.AddVertex(vertex2);
                }
                else Debug.WriteLine(String.Format("Vertex {0} already present", vertex2));

                // Compute weight
                double weight = weightComputer(str);
                Assert.Greater(weight, 0.0);

                // Add edge 1 => 2
                IEdge<IGeometry> edge1 = new Edge<IGeometry>(vertex1, vertex2);
                Assert.IsNotNull(edge1);                
                graph.AddEdge(edge1);
                consts.Add(edge1, weight);

                // Add edge 2 => 1
                IEdge<IGeometry> edge2 = new Edge<IGeometry>(vertex2, vertex1);
                Assert.IsNotNull(edge2);
                graph.AddEdge(edge2);
                consts.Add(edge2, weight);
            }

            // Perform DijkstraShortestPathAlgorithm
            DijkstraShortestPathAlgorithm<IGeometry, IEdge<IGeometry>> dijkstra =
                new DijkstraShortestPathAlgorithm<IGeometry, IEdge<IGeometry>>(graph, consts);

            // attach a distance observer to give us the shortest path distances
            VertexDistanceRecorderObserver<IGeometry, IEdge<IGeometry>> distObserver =
                new VertexDistanceRecorderObserver<IGeometry, IEdge<IGeometry>>();
            distObserver.Attach(dijkstra);

            // Attach a Vertex Predecessor Recorder Observer to give us the paths
            VertexPredecessorRecorderObserver<IGeometry, IEdge<IGeometry>> predecessorObserver =
                new VertexPredecessorRecorderObserver<IGeometry, IEdge<IGeometry>>();
            predecessorObserver.Attach(dijkstra);

            // Run the algorithm   
            Assert.IsNotNull(startls);
            IGeometry startPoint = startls.StartPoint;
            Debug.WriteLine(String.Format("Starting algorithm from root vertex {0}", startPoint));
            dijkstra.Compute(startPoint);

            foreach (KeyValuePair<IGeometry, int> kvp in distObserver.Distances)
                Debug.WriteLine(String.Format("Distance from root to node {0} is {1}",
                    kvp.Key, kvp.Value));
            foreach (KeyValuePair<IGeometry, IEdge<IGeometry>> kvp in predecessorObserver.VertexPredecessors)
                Debug.WriteLine(String.Format(
                    "If you want to get to {0} you have to enter through the IN edge {1}", kvp.Key, kvp.Value));
            Check(graph, consts, predecessorObserver);

            // Detach the observers
            distObserver.Detach(dijkstra);
            predecessorObserver.Detach(dijkstra);
        }
Example #13
0
        public void BuildGraphBinary()
        {            
            string path = "strade" + shp;
            Assert.IsTrue(File.Exists(path));

            ShapefileReader reader = new ShapefileReader(path, factory);
            IGeometryCollection coll = reader.ReadAll();
            Assert.IsNotNull(coll);
            Assert.IsNotEmpty(coll.Geometries);

            IGeometry result = coll.Geometries[0];
            for (int i = 1; i < coll.NumGeometries; i++ )
            {
                Debug.WriteLine(String.Format("Union of {0}'th geometry", i));
                result = result.Union(coll.Geometries[i]);
            }
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(typeof(MultiLineString), result);

            WKBWriter wkbwriter = new WKBWriter();
            byte[] rawdata = wkbwriter.Write(result);
            Assert.IsNotEmpty(rawdata);

            path = "graph";
            if (File.Exists(path))
                File.Delete(path);
            Assert.IsFalse(File.Exists(path));
            using (FileStream stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                stream.Write(rawdata, 0, rawdata.Length);
            Assert.IsTrue(File.Exists(path));
        }
Example #14
0
        private void TestBugCimino()
        {
            try
            {
                string file = "countryCopy.shp";
                if (!File.Exists(file))
                    throw new FileNotFoundException();

                ShapefileReader sfr = new ShapefileReader(file);

                IGeometryCollection gc = sfr.ReadAll();

                for (int i = 0; i < gc.NumGeometries; i++)
                    Console.WriteLine(i + " " + gc.Geometries[i].Envelope);
           
                // IsValidOp.CheckShellsNotNested molto lento nell'analisi di J == 7 (Poligono con 11600 punti)
                ShapefileWriter sfw = new ShapefileWriter();
                string write = Path.Combine(Path.GetTempPath(), "copy_countryCopy");
                sfw.Write(write, gc);
                Console.WriteLine("Write Complete!");
            }
            catch (Exception ex) 
            {                
                throw ex;
            }
        }
Example #15
0
        private IGeometryCollection ReadShape(string shapepath)
        {
            if (!File.Exists(shapepath))
                throw new ArgumentException("File " + shapepath + " not found!");

            ShapefileReader reader = new ShapefileReader(shapepath);             
            IGeometryCollection geometries = reader.ReadAll();                  
            return geometries;            
        }