abstract.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. """
  2. Created on Fri Aug 17 16:05:25 2012
  3. @author: pietro
  4. """
  5. from __future__ import (
  6. nested_scopes,
  7. generators,
  8. division,
  9. absolute_import,
  10. with_statement,
  11. print_function,
  12. unicode_literals,
  13. )
  14. import ctypes
  15. #
  16. # import GRASS modules
  17. #
  18. from grass.script import fatal, gisenv
  19. import grass.lib.gis as libgis
  20. import grass.lib.raster as libraster
  21. #
  22. # import pygrass modules
  23. #
  24. from grass.pygrass import utils
  25. from grass.pygrass.gis.region import Region
  26. from grass.pygrass.errors import must_be_open, must_be_in_current_mapset
  27. from grass.pygrass.shell.conversion import dict2html
  28. from grass.pygrass.shell.show import raw_figure
  29. #
  30. # import raster classes
  31. #
  32. from grass.pygrass.raster.raster_type import TYPE as RTYPE, RTYPE_STR
  33. from grass.pygrass.raster.category import Category
  34. from grass.pygrass.raster.history import History
  35. test_raster_name = "abstract_test_map"
  36. # Define global variables to not exceed the 80 columns
  37. INDXOUTRANGE = "The index (%d) is out of range, have you open the map?."
  38. INFO = """{name}@{mapset}
  39. rows: {rows}
  40. cols: {cols}
  41. north: {north} south: {south} nsres:{nsres}
  42. east: {east} west: {west} ewres:{ewres}
  43. range: {min}, {max}
  44. proj: {proj}
  45. """
  46. class Info(object):
  47. def __init__(self, name, mapset=""):
  48. """Read the information for a raster map. ::
  49. >>> info = Info(test_raster_name)
  50. >>> info.read()
  51. >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  52. abstract_test_map@
  53. rows: 4
  54. cols: 4
  55. north: 40.0 south: 0.0 nsres:10.0
  56. east: 40.0 west: 0.0 ewres:10.0
  57. range: 11, 44
  58. ...
  59. <BLANKLINE>
  60. """
  61. self.name = name
  62. self.mapset = mapset
  63. self.c_region = ctypes.pointer(libraster.struct_Cell_head())
  64. self.c_range = None
  65. def _get_range(self):
  66. if self.mtype == "CELL":
  67. self.c_range = ctypes.pointer(libraster.Range())
  68. libraster.Rast_read_range(self.name, self.mapset, self.c_range)
  69. else:
  70. self.c_range = ctypes.pointer(libraster.FPRange())
  71. libraster.Rast_read_fp_range(self.name, self.mapset, self.c_range)
  72. def _get_raster_region(self):
  73. libraster.Rast_get_cellhd(self.name, self.mapset, self.c_region)
  74. def read(self):
  75. self._get_range()
  76. self._get_raster_region()
  77. @property
  78. def north(self):
  79. return self.c_region.contents.north
  80. @property
  81. def south(self):
  82. return self.c_region.contents.south
  83. @property
  84. def east(self):
  85. return self.c_region.contents.east
  86. @property
  87. def west(self):
  88. return self.c_region.contents.west
  89. @property
  90. def top(self):
  91. return self.c_region.contents.top
  92. @property
  93. def bottom(self):
  94. return self.c_region.contents.bottom
  95. @property
  96. def rows(self):
  97. return self.c_region.contents.rows
  98. @property
  99. def cols(self):
  100. return self.c_region.contents.cols
  101. @property
  102. def nsres(self):
  103. return self.c_region.contents.ns_res
  104. @property
  105. def ewres(self):
  106. return self.c_region.contents.ew_res
  107. @property
  108. def tbres(self):
  109. return self.c_region.contents.tb_res
  110. @property
  111. def zone(self):
  112. return self.c_region.contents.zone
  113. @property
  114. def proj(self):
  115. return self.c_region.contents.proj
  116. @property
  117. def min(self):
  118. if self.c_range is None:
  119. return None
  120. return self.c_range.contents.min
  121. @property
  122. def max(self):
  123. if self.c_range is None:
  124. return None
  125. return self.c_range.contents.max
  126. @property
  127. def range(self):
  128. if self.c_range is None:
  129. return None, None
  130. return self.c_range.contents.min, self.c_range.contents.max
  131. @property
  132. def mtype(self):
  133. return RTYPE_STR[libraster.Rast_map_type(self.name, self.mapset)]
  134. def _get_semantic_label(self):
  135. """Get semantic label identifier.
  136. :return str: semantic label (eg. S2_1) or None
  137. """
  138. semantic_label = libraster.Rast_read_semantic_label(self.name, self.mapset)
  139. if semantic_label:
  140. return utils.decode(semantic_label)
  141. return None
  142. @must_be_in_current_mapset
  143. def _set_semantic_label(self, semantic_label):
  144. """Set/Unset semantic label identifier.
  145. :param str semantic_label: semantic label to assign or None to remove (unset)
  146. """
  147. if semantic_label:
  148. if libraster.Rast_legal_semantic_label(semantic_label) is False:
  149. raise ValueError(_("Invalid semantic label"))
  150. libraster.Rast_write_semantic_label(self.name, semantic_label)
  151. else:
  152. libgis.G_remove_misc("cell_misc", "semantic_label", self.name)
  153. semantic_label = property(_get_semantic_label, _set_semantic_label)
  154. def _get_units(self):
  155. units = libraster.Rast_read_units(self.name, self.mapset)
  156. if units:
  157. return utils.decode(units)
  158. return None
  159. @must_be_in_current_mapset
  160. def _set_units(self, units):
  161. libraster.Rast_write_units(self.name, units)
  162. units = property(_get_units, _set_units)
  163. def _get_vdatum(self):
  164. vdatum = libraster.Rast_read_vdatum(self.name, self.mapset)
  165. if vdatum:
  166. return utils.decode(vdatum)
  167. return None
  168. @must_be_in_current_mapset
  169. def _set_vdatum(self, vdatum):
  170. libraster.Rast_write_vdatum(self.name, vdatum)
  171. vdatum = property(_get_vdatum, _set_vdatum)
  172. def __repr__(self):
  173. return INFO.format(
  174. name=self.name,
  175. mapset=self.mapset,
  176. rows=self.rows,
  177. cols=self.cols,
  178. north=self.north,
  179. south=self.south,
  180. east=self.east,
  181. west=self.west,
  182. top=self.top,
  183. bottom=self.bottom,
  184. nsres=self.nsres,
  185. ewres=self.ewres,
  186. tbres=self.tbres,
  187. zone=self.zone,
  188. proj=self.proj,
  189. min=self.min,
  190. max=self.max,
  191. )
  192. def keys(self):
  193. return [
  194. "name",
  195. "mapset",
  196. "rows",
  197. "cols",
  198. "north",
  199. "south",
  200. "east",
  201. "west",
  202. "top",
  203. "bottom",
  204. "nsres",
  205. "ewres",
  206. "tbres",
  207. "zone",
  208. "proj",
  209. "min",
  210. "max",
  211. ]
  212. def items(self):
  213. return [(k, self.__getattribute__(k)) for k in self.keys()]
  214. def __iter__(self):
  215. return ((k, self.__getattribute__(k)) for k in self.keys())
  216. def _repr_html_(self):
  217. return dict2html(dict(self.items()), keys=self.keys(), border="1", kdec="b")
  218. class RasterAbstractBase(object):
  219. """Raster_abstract_base: The base class from which all sub-classes
  220. inherit. It does not implement any row or map access methods:
  221. * Implements raster metadata information access (Type, ...)
  222. * Implements an open method that will be overwritten by the sub-classes
  223. * Implements the close method that might be overwritten by sub-classes
  224. (should work for simple row access)
  225. * Implements get and set region methods
  226. * Implements color, history and category handling
  227. * Renaming, deletion, ...
  228. """
  229. def __init__(self, name, mapset="", *aopen, **kwopen):
  230. """The constructor need at least the name of the map
  231. *optional* field is the `mapset`.
  232. >>> ele = RasterAbstractBase(test_raster_name)
  233. >>> ele.name
  234. 'abstract_test_map'
  235. >>> ele.exist()
  236. True
  237. ..
  238. """
  239. self.mapset = mapset
  240. if not mapset:
  241. # note that @must_be_in_current_mapset requires mapset to be set
  242. mapset = libgis.G_find_raster(name, mapset)
  243. if mapset is not None:
  244. self.mapset = utils.decode(mapset)
  245. self._name = name
  246. # Private attribute `_fd` that return the file descriptor of the map
  247. self._fd = None
  248. # Private attribute `_rows` that return the number of rows
  249. # in active window, When the class is instanced is empty and it is set
  250. # when you open the file, using Rast_window_rows()
  251. self._rows = None
  252. # Private attribute `_cols` that return the number of rows
  253. # in active window, When the class is instanced is empty and it is set
  254. # when you open the file, using Rast_window_cols()
  255. self._cols = None
  256. # self.region = Region()
  257. self.hist = History(self.name, self.mapset)
  258. self.cats = Category(self.name, self.mapset)
  259. self.info = Info(self.name, self.mapset)
  260. self._aopen = aopen
  261. self._kwopen = kwopen
  262. self._mtype = "CELL"
  263. self._mode = "r"
  264. self._overwrite = False
  265. def __enter__(self):
  266. self.open(*self._aopen, **self._kwopen)
  267. return self
  268. def __exit__(self, exc_type, exc_value, traceback):
  269. self.close()
  270. def _get_mtype(self):
  271. """Private method to get the Raster type"""
  272. return self._mtype
  273. def _set_mtype(self, mtype):
  274. """Private method to change the Raster type"""
  275. if mtype.upper() not in ("CELL", "FCELL", "DCELL"):
  276. str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
  277. raise ValueError(_(str_err).format(mtype))
  278. self._mtype = mtype
  279. self._gtype = RTYPE[self.mtype]["grass type"]
  280. mtype = property(fget=_get_mtype, fset=_set_mtype)
  281. def _get_mode(self):
  282. return self._mode
  283. def _set_mode(self, mode):
  284. if mode.upper() not in ("R", "W"):
  285. str_err = _("Mode type: {0} not supported ('r', 'w')")
  286. raise ValueError(str_err.format(mode))
  287. self._mode = mode
  288. mode = property(fget=_get_mode, fset=_set_mode)
  289. def _get_overwrite(self):
  290. return self._overwrite
  291. def _set_overwrite(self, overwrite):
  292. if overwrite not in (True, False):
  293. str_err = _("Overwrite type: {0} not supported (True/False)")
  294. raise ValueError(str_err.format(overwrite))
  295. self._overwrite = overwrite
  296. overwrite = property(fget=_get_overwrite, fset=_set_overwrite)
  297. def _get_name(self):
  298. """Private method to return the Raster name"""
  299. return self._name
  300. def _set_name(self, newname):
  301. """Private method to change the Raster name"""
  302. if not utils.is_clean_name(newname):
  303. str_err = _("Map name {0} not valid")
  304. raise ValueError(str_err.format(newname))
  305. if self.exist():
  306. self.rename(newname)
  307. self._name = newname
  308. name = property(fget=_get_name, fset=_set_name)
  309. @must_be_open
  310. def _get_cats_title(self):
  311. return self.cats.title
  312. @must_be_open
  313. def _set_cats_title(self, newtitle):
  314. self.cats.title = newtitle
  315. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  316. def __unicode__(self):
  317. return self.name_mapset()
  318. def __str__(self):
  319. """Return the string of the object"""
  320. return self.__unicode__()
  321. def __len__(self):
  322. return self._rows
  323. def __getitem__(self, key):
  324. """Return the row of Raster object, slice allowed."""
  325. if isinstance(key, slice):
  326. # Get the start, stop, and step from the slice
  327. return (self.get_row(ii) for ii in range(*key.indices(len(self))))
  328. elif isinstance(key, tuple):
  329. x, y = key
  330. return self.get(x, y)
  331. elif isinstance(key, int):
  332. if not self.is_open():
  333. raise IndexError("Can not operate on a closed map. Call open() first.")
  334. if key < 0: # Handle negative indices
  335. key += self._rows
  336. if key >= self._rows:
  337. raise IndexError(
  338. "The row index {0} is out of range [0, {1}).".format(
  339. key, self._rows
  340. )
  341. )
  342. return self.get_row(key)
  343. else:
  344. fatal("Invalid argument type.")
  345. def __iter__(self):
  346. """Return a constructor of the class"""
  347. return (self.__getitem__(irow) for irow in range(self._rows))
  348. def _repr_png_(self):
  349. return raw_figure(utils.r_export(self))
  350. def exist(self):
  351. """Return True if the map already exist, and
  352. set the mapset if were not set.
  353. call the C function `G_find_raster`.
  354. >>> ele = RasterAbstractBase(test_raster_name)
  355. >>> ele.exist()
  356. True
  357. """
  358. if self.name:
  359. if self.mapset == "":
  360. mapset = utils.get_mapset_raster(self.name, self.mapset)
  361. self.mapset = mapset if mapset else ""
  362. return True if mapset else False
  363. return bool(utils.get_mapset_raster(self.name, self.mapset))
  364. else:
  365. return False
  366. def is_open(self):
  367. """Return True if the map is open False otherwise.
  368. >>> ele = RasterAbstractBase(test_raster_name)
  369. >>> ele.is_open()
  370. False
  371. """
  372. return True if self._fd is not None and self._fd >= 0 else False
  373. @must_be_open
  374. def close(self):
  375. """Close the map"""
  376. libraster.Rast_close(self._fd)
  377. # update rows and cols attributes
  378. self._rows = None
  379. self._cols = None
  380. self._fd = None
  381. def remove(self):
  382. """Remove the map"""
  383. if self.is_open():
  384. self.close()
  385. utils.remove(self.name, "rast")
  386. def fullname(self):
  387. """Return the full name of a raster map: name@mapset"""
  388. return "{name}@{mapset}".format(name=self.name, mapset=self.mapset)
  389. def name_mapset(self, name=None, mapset=None):
  390. """Return the full name of the Raster.
  391. >>> ele = RasterAbstractBase(test_raster_name)
  392. >>> name = ele.name_mapset().split("@")
  393. >>> name
  394. ['abstract_test_map']
  395. """
  396. if name is None:
  397. name = self.name
  398. if mapset is None:
  399. self.exist()
  400. mapset = self.mapset
  401. gis_env = gisenv()
  402. if mapset and mapset != gis_env["MAPSET"]:
  403. return "{name}@{mapset}".format(name=name, mapset=mapset)
  404. else:
  405. return name
  406. def rename(self, newname):
  407. """Rename the map"""
  408. if self.exist():
  409. utils.rename(self.name, newname, "rast")
  410. self._name = newname
  411. def set_region_from_rast(self, rastname="", mapset=""):
  412. """Set the computational region from a map,
  413. if rastername and mapset is not specify, use itself.
  414. This region will be used by all
  415. raster map layers that are opened in the same process.
  416. The GRASS region settings will not be modified.
  417. call C function `Rast_get_cellhd`, `Rast_set_window`
  418. """
  419. if self.is_open():
  420. fatal("You cannot change the region if map is open")
  421. raise
  422. region = Region()
  423. if rastname == "":
  424. rastname = self.name
  425. if mapset == "":
  426. mapset = self.mapset
  427. libraster.Rast_get_cellhd(rastname, mapset, region.byref())
  428. self._set_raster_window(region)
  429. def set_region(self, region):
  430. """Set the computational region that can be different from the
  431. current region settings. This region will be used by all
  432. raster map layers that are opened in the same process.
  433. The GRASS region settings will not be modified.
  434. """
  435. if self.is_open():
  436. fatal("You cannot change the region if map is open")
  437. raise
  438. self._set_raster_window(region)
  439. def _set_raster_window(self, region):
  440. libraster.Rast_set_window(region.byref())
  441. # update rows and cols attributes
  442. self._rows = libraster.Rast_window_rows()
  443. self._cols = libraster.Rast_window_cols()
  444. @must_be_open
  445. def get_value(self, point, region=None):
  446. """This method returns the pixel value of a given pair of coordinates:
  447. :param point: pair of coordinates in tuple object or class object with coords() method
  448. """
  449. # Check for tuple
  450. if not isinstance(point, list) and not isinstance(point, tuple):
  451. point = point.coords()
  452. if not region:
  453. region = Region()
  454. row, col = utils.coor2pixel(point, region)
  455. if col < 0 or col > region.cols or row < 0 or row > region.rows:
  456. return None
  457. line = self.get_row(int(row))
  458. return line[int(col)]
  459. @must_be_open
  460. def has_cats(self):
  461. """Return True if the raster map has categories"""
  462. if self.exist():
  463. self.cats.read()
  464. if len(self.cats) != 0:
  465. return True
  466. return False
  467. @must_be_open
  468. def num_cats(self):
  469. """Return the number of categories"""
  470. return len(self.cats)
  471. @must_be_open
  472. def copy_cats(self, raster):
  473. """Copy categories from another raster map object"""
  474. self.cats.copy(raster.cats)
  475. @must_be_open
  476. def sort_cats(self):
  477. """Sort categories order by range"""
  478. self.cats.sort()
  479. @must_be_open
  480. def read_cats(self):
  481. """Read category from the raster map file"""
  482. self.cats.read(self)
  483. @must_be_open
  484. def write_cats(self):
  485. """Write category to the raster map file"""
  486. self.cats.write(self)
  487. @must_be_open
  488. def read_cats_rules(self, filename, sep=":"):
  489. """Read category from the raster map file"""
  490. self.cats.read_rules(filename, sep)
  491. @must_be_open
  492. def write_cats_rules(self, filename, sep=":"):
  493. """Write category to the raster map file"""
  494. self.cats.write_rules(filename, sep)
  495. @must_be_open
  496. def get_cats(self):
  497. """Return a category object"""
  498. cat = Category(name=self.name, mapset=self.mapset)
  499. cat.read()
  500. return cat
  501. @must_be_open
  502. def set_cats(self, category):
  503. """The internal categories are copied from this object."""
  504. self.cats.copy(category)
  505. @must_be_open
  506. def get_cat(self, label):
  507. """Return a category given an index or a label"""
  508. return self.cats[label]
  509. @must_be_open
  510. def set_cat(self, label, min_cat, max_cat=None, index=None):
  511. """Set or update a category"""
  512. self.cats.set_cat(index, (label, min_cat, max_cat))
  513. if __name__ == "__main__":
  514. import doctest
  515. from grass.pygrass.modules import Module
  516. Module("g.region", n=40, s=0, e=40, w=0, res=10)
  517. Module(
  518. "r.mapcalc",
  519. expression="%s = row() + (10 * col())" % (test_raster_name),
  520. overwrite=True,
  521. )
  522. doctest.testmod()
  523. """Remove the generated vector map, if exist"""
  524. mset = utils.get_mapset_raster(test_raster_name, mapset="")
  525. if mset:
  526. Module("g.remove", flags="f", type="raster", name=test_raster_name)