abstract.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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_band_reference(self):
  135. """Get band reference identifier.
  136. :return str: band identifier (eg. S2_1) or None
  137. """
  138. band_ref = None
  139. p_filename = ctypes.c_char_p()
  140. p_band_ref = ctypes.c_char_p()
  141. ret = libraster.Rast_read_band_reference(
  142. self.name, self.mapset, ctypes.byref(p_filename), ctypes.byref(p_band_ref)
  143. )
  144. if ret:
  145. band_ref = utils.decode(p_band_ref.value)
  146. libgis.G_free(p_filename)
  147. libgis.G_free(p_band_ref)
  148. return band_ref
  149. @must_be_in_current_mapset
  150. def _set_band_reference(self, band_reference):
  151. """Set/Unset band reference identifier.
  152. :param str band_reference: band reference to assign or None to remove (unset)
  153. """
  154. if band_reference:
  155. # assign
  156. from grass.bandref import BandReferenceReader, BandReferenceReaderError
  157. reader = BandReferenceReader()
  158. # determine filename (assuming that band_reference is unique!)
  159. try:
  160. filename = reader.find_file(band_reference)
  161. except BandReferenceReaderError as e:
  162. fatal("{}".format(e))
  163. raise
  164. if not filename:
  165. fatal("Band reference <{}> not found".format(band_reference))
  166. raise
  167. # write band reference
  168. libraster.Rast_write_band_reference(self.name, filename, band_reference)
  169. else:
  170. libraster.Rast_remove_band_reference(self.name)
  171. band_reference = property(fget=_get_band_reference, fset=_set_band_reference)
  172. def _get_units(self):
  173. return libraster.Rast_read_units(self.name, self.mapset)
  174. def _set_units(self, units):
  175. libraster.Rast_write_units(self.name, units)
  176. units = property(_get_units, _set_units)
  177. def _get_vdatum(self):
  178. return libraster.Rast_read_vdatum(self.name, self.mapset)
  179. def _set_vdatum(self, vdatum):
  180. libraster.Rast_write_vdatum(self.name, vdatum)
  181. vdatum = property(_get_vdatum, _set_vdatum)
  182. def __repr__(self):
  183. return INFO.format(
  184. name=self.name,
  185. mapset=self.mapset,
  186. rows=self.rows,
  187. cols=self.cols,
  188. north=self.north,
  189. south=self.south,
  190. east=self.east,
  191. west=self.west,
  192. top=self.top,
  193. bottom=self.bottom,
  194. nsres=self.nsres,
  195. ewres=self.ewres,
  196. tbres=self.tbres,
  197. zone=self.zone,
  198. proj=self.proj,
  199. min=self.min,
  200. max=self.max,
  201. )
  202. def keys(self):
  203. return [
  204. "name",
  205. "mapset",
  206. "rows",
  207. "cols",
  208. "north",
  209. "south",
  210. "east",
  211. "west",
  212. "top",
  213. "bottom",
  214. "nsres",
  215. "ewres",
  216. "tbres",
  217. "zone",
  218. "proj",
  219. "min",
  220. "max",
  221. ]
  222. def items(self):
  223. return [(k, self.__getattribute__(k)) for k in self.keys()]
  224. def __iter__(self):
  225. return ((k, self.__getattribute__(k)) for k in self.keys())
  226. def _repr_html_(self):
  227. return dict2html(dict(self.items()), keys=self.keys(), border="1", kdec="b")
  228. class RasterAbstractBase(object):
  229. """Raster_abstract_base: The base class from which all sub-classes
  230. inherit. It does not implement any row or map access methods:
  231. * Implements raster metadata information access (Type, ...)
  232. * Implements an open method that will be overwritten by the sub-classes
  233. * Implements the close method that might be overwritten by sub-classes
  234. (should work for simple row access)
  235. * Implements get and set region methods
  236. * Implements color, history and category handling
  237. * Renaming, deletion, ...
  238. """
  239. def __init__(self, name, mapset="", *aopen, **kwopen):
  240. """The constructor need at least the name of the map
  241. *optional* field is the `mapset`.
  242. >>> ele = RasterAbstractBase(test_raster_name)
  243. >>> ele.name
  244. 'abstract_test_map'
  245. >>> ele.exist()
  246. True
  247. ..
  248. """
  249. self.mapset = mapset
  250. if not mapset:
  251. # note that @must_be_in_current_mapset requires mapset to be set
  252. mapset = libgis.G_find_raster(name, mapset)
  253. if mapset is not None:
  254. self.mapset = utils.decode(mapset)
  255. self._name = name
  256. # Private attribute `_fd` that return the file descriptor of the map
  257. self._fd = None
  258. # Private attribute `_rows` that return the number of rows
  259. # in active window, When the class is instanced is empty and it is set
  260. # when you open the file, using Rast_window_rows()
  261. self._rows = None
  262. # Private attribute `_cols` that return the number of rows
  263. # in active window, When the class is instanced is empty and it is set
  264. # when you open the file, using Rast_window_cols()
  265. self._cols = None
  266. # self.region = Region()
  267. self.hist = History(self.name, self.mapset)
  268. self.cats = Category(self.name, self.mapset)
  269. self.info = Info(self.name, self.mapset)
  270. self._aopen = aopen
  271. self._kwopen = kwopen
  272. self._mtype = "CELL"
  273. self._mode = "r"
  274. self._overwrite = False
  275. def __enter__(self):
  276. self.open(*self._aopen, **self._kwopen)
  277. return self
  278. def __exit__(self, exc_type, exc_value, traceback):
  279. self.close()
  280. def _get_mtype(self):
  281. """Private method to get the Raster type"""
  282. return self._mtype
  283. def _set_mtype(self, mtype):
  284. """Private method to change the Raster type"""
  285. if mtype.upper() not in ("CELL", "FCELL", "DCELL"):
  286. str_err = "Raster type: {0} not supported ('CELL','FCELL','DCELL')"
  287. raise ValueError(_(str_err).format(mtype))
  288. self._mtype = mtype
  289. self._gtype = RTYPE[self.mtype]["grass type"]
  290. mtype = property(fget=_get_mtype, fset=_set_mtype)
  291. def _get_mode(self):
  292. return self._mode
  293. def _set_mode(self, mode):
  294. if mode.upper() not in ("R", "W"):
  295. str_err = _("Mode type: {0} not supported ('r', 'w')")
  296. raise ValueError(str_err.format(mode))
  297. self._mode = mode
  298. mode = property(fget=_get_mode, fset=_set_mode)
  299. def _get_overwrite(self):
  300. return self._overwrite
  301. def _set_overwrite(self, overwrite):
  302. if overwrite not in (True, False):
  303. str_err = _("Overwrite type: {0} not supported (True/False)")
  304. raise ValueError(str_err.format(overwrite))
  305. self._overwrite = overwrite
  306. overwrite = property(fget=_get_overwrite, fset=_set_overwrite)
  307. def _get_name(self):
  308. """Private method to return the Raster name"""
  309. return self._name
  310. def _set_name(self, newname):
  311. """Private method to change the Raster name"""
  312. if not utils.is_clean_name(newname):
  313. str_err = _("Map name {0} not valid")
  314. raise ValueError(str_err.format(newname))
  315. if self.exist():
  316. self.rename(newname)
  317. self._name = newname
  318. name = property(fget=_get_name, fset=_set_name)
  319. @must_be_open
  320. def _get_cats_title(self):
  321. return self.cats.title
  322. @must_be_open
  323. def _set_cats_title(self, newtitle):
  324. self.cats.title = newtitle
  325. cats_title = property(fget=_get_cats_title, fset=_set_cats_title)
  326. def __unicode__(self):
  327. return self.name_mapset()
  328. def __str__(self):
  329. """Return the string of the object"""
  330. return self.__unicode__()
  331. def __len__(self):
  332. return self._rows
  333. def __getitem__(self, key):
  334. """Return the row of Raster object, slice allowed."""
  335. if isinstance(key, slice):
  336. # Get the start, stop, and step from the slice
  337. return (self.get_row(ii) for ii in range(*key.indices(len(self))))
  338. elif isinstance(key, tuple):
  339. x, y = key
  340. return self.get(x, y)
  341. elif isinstance(key, int):
  342. if not self.is_open():
  343. raise IndexError("Can not operate on a closed map. Call open() first.")
  344. if key < 0: # Handle negative indices
  345. key += self._rows
  346. if key >= self._rows:
  347. raise IndexError(
  348. "The row index {0} is out of range [0, {1}).".format(
  349. key, self._rows
  350. )
  351. )
  352. return self.get_row(key)
  353. else:
  354. fatal("Invalid argument type.")
  355. def __iter__(self):
  356. """Return a constructor of the class"""
  357. return (self.__getitem__(irow) for irow in range(self._rows))
  358. def _repr_png_(self):
  359. return raw_figure(utils.r_export(self))
  360. def exist(self):
  361. """Return True if the map already exist, and
  362. set the mapset if were not set.
  363. call the C function `G_find_raster`.
  364. >>> ele = RasterAbstractBase(test_raster_name)
  365. >>> ele.exist()
  366. True
  367. """
  368. if self.name:
  369. if self.mapset == "":
  370. mapset = utils.get_mapset_raster(self.name, self.mapset)
  371. self.mapset = mapset if mapset else ""
  372. return True if mapset else False
  373. return bool(utils.get_mapset_raster(self.name, self.mapset))
  374. else:
  375. return False
  376. def is_open(self):
  377. """Return True if the map is open False otherwise.
  378. >>> ele = RasterAbstractBase(test_raster_name)
  379. >>> ele.is_open()
  380. False
  381. """
  382. return True if self._fd is not None and self._fd >= 0 else False
  383. @must_be_open
  384. def close(self):
  385. """Close the map"""
  386. libraster.Rast_close(self._fd)
  387. # update rows and cols attributes
  388. self._rows = None
  389. self._cols = None
  390. self._fd = None
  391. def remove(self):
  392. """Remove the map"""
  393. if self.is_open():
  394. self.close()
  395. utils.remove(self.name, "rast")
  396. def fullname(self):
  397. """Return the full name of a raster map: name@mapset"""
  398. return "{name}@{mapset}".format(name=self.name, mapset=self.mapset)
  399. def name_mapset(self, name=None, mapset=None):
  400. """Return the full name of the Raster.
  401. >>> ele = RasterAbstractBase(test_raster_name)
  402. >>> name = ele.name_mapset().split("@")
  403. >>> name
  404. ['abstract_test_map']
  405. """
  406. if name is None:
  407. name = self.name
  408. if mapset is None:
  409. self.exist()
  410. mapset = self.mapset
  411. gis_env = gisenv()
  412. if mapset and mapset != gis_env["MAPSET"]:
  413. return "{name}@{mapset}".format(name=name, mapset=mapset)
  414. else:
  415. return name
  416. def rename(self, newname):
  417. """Rename the map"""
  418. if self.exist():
  419. utils.rename(self.name, newname, "rast")
  420. self._name = newname
  421. def set_region_from_rast(self, rastname="", mapset=""):
  422. """Set the computational region from a map,
  423. if rastername and mapset is not specify, use itself.
  424. This region will be used by all
  425. raster map layers that are opened in the same process.
  426. The GRASS region settings will not be modified.
  427. call C function `Rast_get_cellhd`, `Rast_set_window`
  428. """
  429. if self.is_open():
  430. fatal("You cannot change the region if map is open")
  431. raise
  432. region = Region()
  433. if rastname == "":
  434. rastname = self.name
  435. if mapset == "":
  436. mapset = self.mapset
  437. libraster.Rast_get_cellhd(rastname, mapset, region.byref())
  438. self._set_raster_window(region)
  439. def set_region(self, region):
  440. """Set the computational region that can be different from the
  441. current region settings. This region will be used by all
  442. raster map layers that are opened in the same process.
  443. The GRASS region settings will not be modified.
  444. """
  445. if self.is_open():
  446. fatal("You cannot change the region if map is open")
  447. raise
  448. self._set_raster_window(region)
  449. def _set_raster_window(self, region):
  450. libraster.Rast_set_window(region.byref())
  451. # update rows and cols attributes
  452. self._rows = libraster.Rast_window_rows()
  453. self._cols = libraster.Rast_window_cols()
  454. @must_be_open
  455. def get_value(self, point, region=None):
  456. """This method returns the pixel value of a given pair of coordinates:
  457. :param point: pair of coordinates in tuple object or class object with coords() method
  458. """
  459. # Check for tuple
  460. if not isinstance(point, list) and not isinstance(point, tuple):
  461. point = point.coords()
  462. if not region:
  463. region = Region()
  464. row, col = utils.coor2pixel(point, region)
  465. if col < 0 or col > region.cols or row < 0 or row > region.rows:
  466. return None
  467. line = self.get_row(int(row))
  468. return line[int(col)]
  469. @must_be_open
  470. def has_cats(self):
  471. """Return True if the raster map has categories"""
  472. if self.exist():
  473. self.cats.read()
  474. if len(self.cats) != 0:
  475. return True
  476. return False
  477. @must_be_open
  478. def num_cats(self):
  479. """Return the number of categories"""
  480. return len(self.cats)
  481. @must_be_open
  482. def copy_cats(self, raster):
  483. """Copy categories from another raster map object"""
  484. self.cats.copy(raster.cats)
  485. @must_be_open
  486. def sort_cats(self):
  487. """Sort categories order by range"""
  488. self.cats.sort()
  489. @must_be_open
  490. def read_cats(self):
  491. """Read category from the raster map file"""
  492. self.cats.read(self)
  493. @must_be_open
  494. def write_cats(self):
  495. """Write category to the raster map file"""
  496. self.cats.write(self)
  497. @must_be_open
  498. def read_cats_rules(self, filename, sep=":"):
  499. """Read category from the raster map file"""
  500. self.cats.read_rules(filename, sep)
  501. @must_be_open
  502. def write_cats_rules(self, filename, sep=":"):
  503. """Write category to the raster map file"""
  504. self.cats.write_rules(filename, sep)
  505. @must_be_open
  506. def get_cats(self):
  507. """Return a category object"""
  508. cat = Category(name=self.name, mapset=self.mapset)
  509. cat.read()
  510. return cat
  511. @must_be_open
  512. def set_cats(self, category):
  513. """The internal categories are copied from this object."""
  514. self.cats.copy(category)
  515. @must_be_open
  516. def get_cat(self, label):
  517. """Return a category given an index or a label"""
  518. return self.cats[label]
  519. @must_be_open
  520. def set_cat(self, label, min_cat, max_cat=None, index=None):
  521. """Set or update a category"""
  522. self.cats.set_cat(index, (label, min_cat, max_cat))
  523. if __name__ == "__main__":
  524. import doctest
  525. from grass.pygrass.modules import Module
  526. Module("g.region", n=40, s=0, e=40, w=0, res=10)
  527. Module(
  528. "r.mapcalc",
  529. expression="%s = row() + (10 * col())" % (test_raster_name),
  530. overwrite=True,
  531. )
  532. doctest.testmod()
  533. """Remove the generated vector map, if exist"""
  534. mset = utils.get_mapset_raster(test_raster_name, mapset="")
  535. if mset:
  536. Module("g.remove", flags="f", type="raster", name=test_raster_name)