basic.py 16 KB

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