basic.py 17 KB

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