basic.py 17 KB

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