test_vector3d.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. Created on Wed Jun 18 17:21:42 2014
  3. @author: pietro
  4. """
  5. import numpy as np
  6. from grass.gunittest.case import TestCase
  7. from grass.gunittest.main import test
  8. from grass.script.core import run_command
  9. from grass.pygrass.vector import VectorTopo
  10. from grass.pygrass.vector.geometry import Point
  11. from grass.pygrass.gis.region import Region
  12. from grass.pygrass.utils import get_mapset_vector
  13. def generate_coordinates(number, bbox=None, with_z=False):
  14. """Return 2 or 3 random arrays of coordinates"""
  15. bbox = Region() if bbox is None else bbox
  16. x = bbox.south + (bbox.north - bbox.south) * np.random.random(number)
  17. y = bbox.west + (bbox.east - bbox.west) * np.random.random(number)
  18. if with_z:
  19. z = np.random.random(number) * 1000
  20. return x, y, z
  21. return x, y
  22. class VectorTopo3DTestCase(TestCase):
  23. npoints = 10
  24. tmpname = "tmp_vect3d"
  25. @classmethod
  26. def setUpClass(cls):
  27. """Generate a number (NPOINTS) of random points"""
  28. cls.x, cls.y, cls.z = generate_coordinates(cls.npoints, with_z=True)
  29. def writing_points(self):
  30. """Write the generated random points to a vector map"""
  31. with VectorTopo(self.tmpname, mode="w", with_z=True) as vect:
  32. for x, y, z in zip(self.x, self.y, self.z):
  33. vect.write(Point(x, y, z))
  34. def reading_points(self):
  35. """Read the generated random points from a vector map"""
  36. with VectorTopo(self.tmpname, mode="r") as vect:
  37. # reading the generated vector points map
  38. arr = np.array([(p.x, p.y, p.z) for p in vect])
  39. # verify the correspondence
  40. for i, coords in enumerate((self.x, self.y, self.z)):
  41. np.testing.assert_almost_equal(arr.T[i], coords)
  42. def test_writing_reading_points(self):
  43. self.writing_points()
  44. self.reading_points()
  45. @classmethod
  46. def tearDownClass(cls):
  47. """Remove the generated vector map, if exist"""
  48. cls.runModule("g.remove", flags="f", type="vector", name=cls.tmpname)
  49. if __name__ == "__main__":
  50. test()