basic.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 31 13:06:20 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. import grass.lib.vector as libvect
  8. from collections import Iterable
  9. class Bbox(object):
  10. """Instantiate a Bounding Box class that contains
  11. a ctypes pointer to the C struct bound_box, that could be used
  12. by C GRASS functions. ::
  13. >>> bbox = Bbox()
  14. >>> bbox
  15. Bbox(0.0, 0.0, 0.0, 0.0)
  16. The default parameters are 0. It is possible to set or change
  17. the parameters later, with: ::
  18. >>> bbox.north = 10
  19. >>> bbox.south = -10
  20. >>> bbox.east = -20
  21. >>> bbox.west = 20
  22. >>> bbox
  23. Bbox(10.0, -10.0, -20.0, 20.0)
  24. Or directly istantiate the class with the values, with: ::
  25. >>> bbox = Bbox(north=100, south=0, east=0, west=100)
  26. >>> bbox
  27. Bbox(100.0, 0.0, 0.0, 100.0)
  28. ..
  29. """
  30. def __init__(self, north=0, south=0, east=0, west=0, top=0, bottom=0):
  31. self.c_bbox = ctypes.pointer(libvect.bound_box())
  32. self.north = north
  33. self.south = south
  34. self.east = east
  35. self.west = west
  36. self.top = top
  37. self.bottom = bottom
  38. def _get_n(self):
  39. """Private method to obtain the north value"""
  40. return self.c_bbox.contents.N
  41. def _set_n(self, value):
  42. """Private method to set the north value"""
  43. self.c_bbox.contents.N = value
  44. north = property(fget=_get_n, fset=_set_n)
  45. def _get_s(self):
  46. """Private method to obtain the south value"""
  47. return self.c_bbox.contents.S
  48. def _set_s(self, value):
  49. """Private method to set the south value"""
  50. self.c_bbox.contents.S = value
  51. south = property(fget=_get_s, fset=_set_s)
  52. def _get_e(self):
  53. """Private method to obtain the east value"""
  54. return self.c_bbox.contents.E
  55. def _set_e(self, value):
  56. """Private method to set the east value"""
  57. self.c_bbox.contents.E = value
  58. east = property(fget=_get_e, fset=_set_e)
  59. def _get_w(self):
  60. """Private method to obtain the west value"""
  61. return self.c_bbox.contents.W
  62. def _set_w(self, value):
  63. """Private method to set the west value"""
  64. self.c_bbox.contents.W = value
  65. west = property(fget=_get_w, fset=_set_w)
  66. def _get_t(self):
  67. """Private method to obtain the top value"""
  68. return self.c_bbox.contents.T
  69. def _set_t(self, value):
  70. """Private method to set the top value"""
  71. self.c_bbox.contents.T = value
  72. top = property(fget=_get_t, fset=_set_t)
  73. def _get_b(self):
  74. """Private method to obtain the bottom value"""
  75. return self.c_bbox.contents.B
  76. def _set_b(self, value):
  77. """Private method to set the bottom value"""
  78. self.c_bbox.contents.B = value
  79. bottom = property(fget=_get_b, fset=_set_b)
  80. def __repr__(self):
  81. return "Bbox({n}, {s}, {e}, {w})".format(n=self.north, s=self.south,
  82. e=self.east, w=self.west)
  83. def contains(self, point):
  84. """Return True if the object is contained by the BoundingBox. ::
  85. >>> from grass.pygrass.vector.geometry import Point
  86. >>> poi = Point(5,5)
  87. >>> bbox = Bbox(north=10, south=0, west=0, east=10)
  88. >>> bbox.contains(poi)
  89. True
  90. ..
  91. """
  92. return bool(libvect.Vect_point_in_box(point.x, point.y,
  93. point.z if point.z else 0,
  94. self.c_bbox))
  95. def items(self):
  96. return [('north', self.north), ('south', self.south),
  97. ('east', self.east), ('west', self.west),
  98. ('top', self.top), ('bottom', self.bottom)]
  99. class BoxList(object):
  100. """Instantiate a BoxList class to create a list of Bounding Box"""
  101. def __init__(self, boxlist=None):
  102. self.c_boxlist = ctypes.pointer(libvect.boxlist())
  103. # if set to 0, the list will hold only ids and no boxes
  104. self.c_boxlist.contents.have_boxes = 1
  105. if boxlist is not None:
  106. for box in boxlist:
  107. self.append(box)
  108. def __len__(self):
  109. return self.c_boxlist.contents.n_values
  110. def __repr__(self):
  111. return "Boxlist([%s])" % ", ".join([repr(box)
  112. for box in self.__iter__()])
  113. def __getitem__(self, indx):
  114. bbox = Bbox()
  115. bbox.c_bbox = ctypes.pointer(self.c_boxlist.contents.box[indx])
  116. return bbox
  117. def __setitem__(self, indx, bbox):
  118. self.c_boxlist.contents.box[indx] = bbox
  119. def __iter__(self):
  120. return (self.__getitem__(box_id) for box_id in xrange(self.__len__()))
  121. def __str__(self):
  122. return self.__repr__()
  123. def append(self, box):
  124. """Append a Bbox object to a Boxlist object, using the
  125. ``Vect_boxlist_append`` C fuction. ::
  126. >>> box0 = Bbox()
  127. >>> box1 = Bbox(1,2,3,4)
  128. >>> box2 = Bbox(5,6,7,8)
  129. >>> boxlist = BoxList([box0, box1])
  130. >>> boxlist
  131. Boxlist([Bbox(0.0, 0.0, 0.0, 0.0), Bbox(1.0, 2.0, 3.0, 4.0)])
  132. >>> len(boxlist)
  133. 2
  134. >>> boxlist.append(box2)
  135. >>> len(boxlist)
  136. 3
  137. ..
  138. """
  139. indx = self.__len__()
  140. libvect.Vect_boxlist_append(self.c_boxlist, indx, box.c_bbox)
  141. # def extend(self, boxlist):
  142. # """Extend a boxlist with another boxlist or using a list of Bbox, using
  143. # ``Vect_boxlist_append_boxlist`` c function. ::
  144. #
  145. # >>> box0 = Bbox()
  146. # >>> box1 = Bbox(1,2,3,4)
  147. # >>> box2 = Bbox(5,6,7,8)
  148. # >>> box3 = Bbox(9,8,7,6)
  149. # >>> boxlist0 = BoxList([box0, box1])
  150. # >>> boxlist0
  151. # Boxlist([Bbox(0.0, 0.0, 0.0, 0.0), Bbox(1.0, 2.0, 3.0, 4.0)])
  152. # >>> boxlist1 = BoxList([box2, box3])
  153. # >>> len(boxlist0)
  154. # 2
  155. # >>> boxlist0.extend(boxlist1)
  156. # >>> len(boxlist0)
  157. # 4
  158. # >>> boxlist1.extend([box0, box1])
  159. # >>> len(boxlist1)
  160. # 4
  161. #
  162. # ..
  163. # """
  164. # if hasattr(boxlist, 'c_boxlist'):
  165. # #import pdb; pdb.set_trace()
  166. # # FIXME: doesn't work
  167. # libvect.Vect_boxlist_append_boxlist(self.c_boxlist,
  168. # boxlist.c_boxlist)
  169. # else:
  170. # for box in boxlist:
  171. # self.append(box)
  172. def remove(self, indx):
  173. """Remove Bbox from the boxlist, given an integer or a list of integer
  174. or a boxlist, using ``Vect_boxlist_delete`` C function or the
  175. ``Vect_boxlist_delete_boxlist``. ::
  176. >>> boxlist = BoxList([Bbox(),
  177. ... Bbox(1, 0, 0, 1),
  178. ... Bbox(1, -1, -1, 1)])
  179. >>> boxlist.remove(0)
  180. >>> boxlist
  181. Boxlist([Bbox(1.0, 0.0, 0.0, 1.0), Bbox(1.0, -1.0, -1.0, 1.0)])
  182. ..
  183. """
  184. if hasattr(indx, 'c_boxlist'):
  185. libvect.Vect_boxlist_delete_boxlist(self.c_boxlist, indx.c_boxlist)
  186. elif isinstance(indx, int):
  187. libvect.Vect_boxlist_delete(self.c_boxlist, indx)
  188. else:
  189. for ind in indx:
  190. libvect.Vect_boxlist_delete(self.c_boxlist, ind)
  191. def reset(self):
  192. """Reset the c_boxlist C struct, using the ``Vect_reset_boxlist`` C
  193. function. ::
  194. >>> boxlist = BoxList([Bbox(),
  195. ... Bbox(1, 0, 0, 1),
  196. ... Bbox(1, -1, -1, 1)])
  197. >>> len(boxlist)
  198. 3
  199. >>> boxlist.reset()
  200. >>> len(boxlist)
  201. 0
  202. ..
  203. """
  204. libvect.Vect_reset_boxlist(self.c_boxlist)
  205. class Ilist(object):
  206. """Instantiate a list of integer using the C GRASS struct ``ilist``,
  207. the class contains this struct as ``c_ilist`` attribute. """
  208. def __init__(self, integer_list=None):
  209. self.c_ilist = ctypes.pointer(libvect.struct_ilist())
  210. if integer_list is not None:
  211. self.extend(integer_list)
  212. def __getitem__(self, key):
  213. if isinstance(key, slice):
  214. #import pdb; pdb.set_trace()
  215. #Get the start, stop, and step from the slice
  216. return [self.c_ilist.contents.value[indx]
  217. for indx in xrange(*key.indices(len(self)))]
  218. elif isinstance(key, int):
  219. if key < 0: # Handle negative indices
  220. key += self.c_ilist.contents.n_values
  221. if key >= self.c_ilist.contents.n_values:
  222. raise IndexError('Index out of range')
  223. return self.c_ilist.contents.value[key]
  224. else:
  225. raise ValueError("Invalid argument type: %r." % key)
  226. def __setitem__(self, key, value):
  227. if self.contains(value):
  228. raise ValueError('Integer already in the list')
  229. self.c_ilist.contents.value[key] = int(value)
  230. def __len__(self):
  231. return self.c_ilist.contents.n_values
  232. def __iter__(self):
  233. return (self.c_ilist.contents.value[i] for i in xrange(self.__len__()))
  234. def __repr__(self):
  235. return "Ilist(%r)" % repr(self.__iter__())
  236. def __contains__(self, item):
  237. return item in self.__iter__()
  238. def append(self, value):
  239. """Append an integer to the list"""
  240. if libvect.Vect_list_append(self.c_ilist, value):
  241. raise # TODO
  242. def reset(self):
  243. """Reset the list"""
  244. libvect.Vect_reset_list(self.c_ilist)
  245. def extend(self, ilist):
  246. """Extend the list with another Ilist object or
  247. with a list of integers"""
  248. if isinstance(ilist, Ilist):
  249. libvect.Vect_list_append_list(self.c_ilist, ilist.ilist)
  250. else:
  251. for i in ilist:
  252. self.append(i)
  253. def remove(self, value):
  254. """Remove a value from a list"""
  255. if isinstance(value, int):
  256. libvect.Vect_list_delete(self.c_ilist, value)
  257. elif isinstance(value, Ilist):
  258. libvect.Vect_list_delete_list(self.c_ilist, value.ilist)
  259. elif isinstance(value, Iterable):
  260. for i in value:
  261. libvect.Vect_list_delete(self.c_ilist, int(i))
  262. else:
  263. raise ValueError('Value: %r, is not supported' % value)
  264. def contains(self, value):
  265. """Check if value is in the list"""
  266. return bool(libvect.Vect_val_in_list(self.c_ilist, value))
  267. class Cats(object):
  268. """Instantiate a Category class that contains a ctypes pointer
  269. to the C line_cats struct. ::
  270. >>> cats = Cats()
  271. >>> for cat in xrange(100, 110): cats.set(cat, layer=cat-50)
  272. >>> cats.n_cats
  273. 10
  274. >>> cats.cat
  275. [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
  276. >>> cats.layer
  277. [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
  278. >>> cats.get() # default layer is 1
  279. (-1, 0)
  280. >>> cats.get(50)
  281. (100, 1)
  282. >>> cats.get(51)
  283. (101, 1)
  284. >>> cats.set(1001, 52)
  285. >>> cats.cat
  286. [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 1001]
  287. >>> cats.layer
  288. [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 52]
  289. >>> cats.get(52)
  290. (102, 2)
  291. >>> cats.reset()
  292. >>> cats.layer
  293. []
  294. >>> cats.cat
  295. []
  296. """
  297. @property
  298. def layer(self):
  299. field = self.c_cats.contents.field
  300. return [field[i] for i in xrange(self.n_cats)]
  301. @property
  302. def cat(self):
  303. cat = self.c_cats.contents.cat
  304. return [cat[i] for i in xrange(self.n_cats)]
  305. @property
  306. def n_cats(self):
  307. """Return the number of categories"""
  308. return self.c_cats.contents.n_cats
  309. def __init__(self, c_cats=None):
  310. self.c_cats = c_cats if c_cats else ctypes.pointer(libvect.line_cats())
  311. def reset(self):
  312. """Reset the C cats struct from previous values."""
  313. libvect.Vect_reset_cats(self.c_cats)
  314. def get(self, layer=1):
  315. """Return the first found category of given layer
  316. and the number of category found. """
  317. cat = ctypes.c_int()
  318. n_cats = libvect.Vect_cat_get(self.c_cats, layer, ctypes.byref(cat))
  319. return cat.value, n_cats
  320. def set(self, cat, layer=1):
  321. """Add new field/cat to category structure if doesn't exist yet."""
  322. libvect.Vect_cat_set(self.c_cats, layer, cat)
  323. def delete(self, cat=None, layer=1):
  324. """If cat is given delete cat from line_cats structure
  325. (using Vect_field_cat_del) else delete all categories of given layer
  326. (using Vect_cat_del).
  327. """
  328. if cat:
  329. self.n_del = libvect.Vect_field_cat_del(self.c_cats, layer, cat)
  330. err_msg = "Layer(%d)/category(%d) number does not exist"
  331. err_msg = err_msg % (layer, cat)
  332. else:
  333. self.n_del = libvect.Vect_cat_del(self.c_cats, layer)
  334. err_msg = 'Layer: %r does not exist' % layer
  335. if self.n_del == 0:
  336. raise ValueError(err_msg)
  337. def check_cats_constraints(self, cats_list, layer=1):
  338. """Check if categories match with category constraints"""
  339. return bool(libvect.Vect_cats_in_constraint(self.c_cats, layer,
  340. cats_list.c_cat_list))
  341. def get_list(self, layer=1):
  342. """Get list of categories of given field."""
  343. ilist = Ilist()
  344. if libvect.Vect_field_cat_get(self.c_cats, layer,
  345. ilist.c_ilist) < 0:
  346. raise ValueError('Layer: %r does not exist' % layer)
  347. return ilist
  348. class CatsList(object):
  349. """::
  350. >>> cats_list = CatsList()
  351. >>> cats_list.min
  352. []
  353. >>> cats_list.max
  354. []
  355. >>> cats_list.n_ranges
  356. 0
  357. >>> cats_list.layer
  358. 0
  359. >>> string = "2,3,5-9,20"
  360. >>> cats_list.from_string(string)
  361. >>> cats_list.min
  362. [2, 3, 5, 20]
  363. >>> cats_list.max
  364. [2, 3, 9, 20]
  365. >>> cats_list.n_ranges
  366. 4
  367. """
  368. @property
  369. def layer(self):
  370. """Return the layer number"""
  371. return self.c_cat_list.contents.field
  372. @property
  373. def n_ranges(self):
  374. """Return the ranges number"""
  375. return self.c_cat_list.contents.n_ranges
  376. @property
  377. def min(self):
  378. """Return the minimum value"""
  379. min_values = self.c_cat_list.contents.min
  380. return [min_values[i] for i in xrange(self.n_ranges)]
  381. @property
  382. def max(self):
  383. """Return the maximum value"""
  384. max_values = self.c_cat_list.contents.max
  385. return [max_values[i] for i in xrange(self.n_ranges)]
  386. def __init__(self, c_cat_list=None):
  387. self.c_cat_list = c_cat_list if c_cat_list \
  388. else ctypes.pointer(libvect.cat_list())
  389. def from_string(self, string):
  390. """Converts string of categories and cat ranges separated by commas
  391. to cat_list."""
  392. num_errors = libvect.Vect_str_to_cat_list(string, self.c_cat_list)
  393. if num_errors:
  394. from grass.pygrass.errors import GrassError
  395. raise GrassError("%d number of errors in ranges" % num_errors)
  396. def from_array(self, array):
  397. """Convert ordered array of integers to cat_list structure."""
  398. # Vect_array_to_cat_list(const int *vals, int nvals, ***)
  399. # TODO: it's not working
  400. libvect.Vect_array_to_cat_list(array, len(array), self.c_cat_list)
  401. def __contains__(self, cat):
  402. """Check if category number is in list.
  403. int Vect_cat_in_cat_list (int cat, const struct cat_list *list)"""
  404. return bool(libvect.Vect_cat_in_cat_list(cat, self.c_cat_list))