test_vector3d.py 2.1 KB

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