__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. # -*- coding: utf-8 -*-
  2. from __future__ import (nested_scopes, generators, division, absolute_import,
  3. with_statement, print_function, unicode_literals)
  4. import os
  5. import ctypes
  6. import numpy as np
  7. #
  8. # import GRASS modules
  9. #
  10. from grass.script import fatal, warning
  11. from grass.script import core as grasscore
  12. import grass.lib.gis as libgis
  13. import grass.lib.raster as libraster
  14. import grass.lib.rowio as librowio
  15. libgis.G_gisinit('')
  16. #
  17. # import pygrass modules
  18. #
  19. from grass.pygrass.errors import OpenError, must_be_open
  20. from grass.pygrass.gis.region import Region
  21. from grass.pygrass import utils
  22. #
  23. # import raster classes
  24. #
  25. from grass.pygrass.raster.abstract import RasterAbstractBase
  26. from grass.pygrass.raster.raster_type import TYPE as RTYPE, RTYPE_STR
  27. from grass.pygrass.raster.buffer import Buffer
  28. from grass.pygrass.raster.segment import Segment
  29. from grass.pygrass.raster.rowio import RowIO
  30. class RasterRow(RasterAbstractBase):
  31. """Raster_row_access": Inherits: "Raster_abstract_base" and implements
  32. the default row access of the Rast library.
  33. * Implements row access using row id
  34. * The get_row() method must accept a Row object as argument that will
  35. be used for value storage, so no new buffer will be allocated
  36. * Implements sequential writing of rows
  37. * Implements indexed value read only access using the [row][col]
  38. operator
  39. * Implements the [row] read method that returns a new Row object
  40. * Writing is limited using the put_row() method which accepts a
  41. Row as argument
  42. * No mathematical operation like __add__ and stuff for the Raster
  43. object (only for rows), since r.mapcalc is more sophisticated and
  44. faster
  45. Examples:
  46. >>> elev = RasterRow('elevation')
  47. >>> elev.exist()
  48. True
  49. >>> elev.is_open()
  50. False
  51. >>> elev.open()
  52. >>> elev.is_open()
  53. True
  54. >>> elev.has_cats()
  55. False
  56. >>> elev.mode
  57. u'r'
  58. >>> elev.mtype
  59. 'FCELL'
  60. >>> elev.num_cats()
  61. 0
  62. >>> elev.info.range
  63. (55.578792572021484, 156.32986450195312)
  64. >>> elev.info
  65. elevation@
  66. rows: 1350
  67. cols: 1500
  68. north: 228500.0 south: 215000.0 nsres:10.0
  69. east: 645000.0 west: 630000.0 ewres:10.0
  70. range: 55.578792572, 156.329864502
  71. proj: 99
  72. <BLANKLINE>
  73. Each Raster map have an attribute call ``cats`` that allow user
  74. to interact with the raster categories.
  75. >>> land = RasterRow('geology')
  76. >>> land.open()
  77. >>> land.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  78. [('Zml', 1, None),
  79. ...
  80. ('Tpyw', 1832, None)]
  81. Open a raster map using the *with statement*:
  82. >>> with RasterRow('elevation') as elev:
  83. ... for row in elev[:3]:
  84. ... row[:4]
  85. ...
  86. Buffer([ 141.99613953, 141.27848816, 141.37904358, 142.29821777], dtype=float32)
  87. Buffer([ 142.90461731, 142.39450073, 142.68611145, 143.59086609], dtype=float32)
  88. Buffer([ 143.81854248, 143.54707336, 143.83972168, 144.59527588], dtype=float32)
  89. >>> elev.is_open()
  90. False
  91. """
  92. def __init__(self, name, mapset='', *args, **kargs):
  93. super(RasterRow, self).__init__(name, mapset, *args, **kargs)
  94. # mode = "r", method = "row",
  95. @must_be_open
  96. def get_row(self, row, row_buffer=None):
  97. """Private method that return the row using the read mode
  98. call the `Rast_get_row` C function.
  99. :param row: the number of row to obtain
  100. :type row: int
  101. :param row_buffer: Buffer object instance with the right dim and type
  102. :type row_buffer: Buffer
  103. >>> elev = RasterRow('elevation')
  104. >>> elev.open()
  105. >>> elev[0] # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  106. Buffer([ 141.99613953, 141.27848816, 141.37904358, ..., 58.40825272,
  107. 58.30711365, 58.18310547], dtype=float32)
  108. >>> elev.get_row(0) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  109. Buffer([ 141.99613953, 141.27848816, 141.37904358, ..., 58.40825272,
  110. 58.30711365, 58.18310547], dtype=float32)
  111. """
  112. if row_buffer is None:
  113. row_buffer = Buffer((self._cols,), self.mtype)
  114. libraster.Rast_get_row(self._fd, row_buffer.p, row, self._gtype)
  115. return row_buffer
  116. @must_be_open
  117. def put_row(self, row):
  118. """Private method to write the row sequentially.
  119. :param row: a Row object to insert into raster
  120. :type row: Buffer object
  121. """
  122. libraster.Rast_put_row(self._fd, row.p, self._gtype)
  123. def open(self, mode=None, mtype=None, overwrite=None):
  124. """Open the raster if exist or created a new one.
  125. :param str mode: Specify if the map will be open with read or write mode
  126. ('r', 'w')
  127. :param str type: If a new map is open, specify the type of the map(`CELL`,
  128. `FCELL`, `DCELL`)
  129. :param bool overwrite: Use this flag to set the overwrite mode of existing
  130. raster maps
  131. if the map already exist, automatically check the type and set:
  132. * self.mtype
  133. Set all the privite, attributes:
  134. * self._fd;
  135. * self._gtype
  136. * self._rows and self._cols
  137. """
  138. self.mode = mode if mode else self.mode
  139. self.mtype = mtype if mtype else self.mtype
  140. self.overwrite = overwrite if overwrite is not None else self.overwrite
  141. if self.mode == 'r':
  142. if self.exist():
  143. self.info.read()
  144. self.cats.mtype = self.mtype
  145. self.cats.read()
  146. self.hist.read()
  147. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  148. self._gtype = libraster.Rast_get_map_type(self._fd)
  149. self.mtype = RTYPE_STR[self._gtype]
  150. else:
  151. str_err = _("The map does not exist, I can't open in 'r' mode")
  152. raise OpenError(str_err)
  153. elif self.mode == 'w':
  154. if self.exist():
  155. if not self.overwrite:
  156. str_err = _("Raster map <{0}> already exists"
  157. " and will be not overwritten")
  158. raise OpenError(str_err.format(self))
  159. if self._gtype is None:
  160. raise OpenError(_("Raster type not defined"))
  161. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  162. else:
  163. raise OpenError("Open mode: %r not supported,"
  164. " valid mode are: r, w")
  165. # read rows and cols from the active region
  166. self._rows = libraster.Rast_window_rows()
  167. self._cols = libraster.Rast_window_cols()
  168. class RasterRowIO(RasterRow):
  169. """Raster_row_cache_access": The same as "Raster_row_access" but uses
  170. the ROWIO library for cached row access
  171. """
  172. def __init__(self, name, *args, **kargs):
  173. self.rowio = RowIO()
  174. super(RasterRowIO, self).__init__(name, *args, **kargs)
  175. def open(self, mode=None, mtype=None, overwrite=False):
  176. """Open the raster if exist or created a new one.
  177. :param mode: specify if the map will be open with read or write mode
  178. ('r', 'w')
  179. :type mode: str
  180. :param type: if a new map is open, specify the type of the map(`CELL`,
  181. `FCELL`, `DCELL`)
  182. :type type: str
  183. :param overwrite: use this flag to set the overwrite mode of existing
  184. raster maps
  185. :type overwrite: bool
  186. """
  187. super(RasterRowIO, self).open(mode, mtype, overwrite)
  188. self.rowio.open(self._fd, self._rows, self._cols, self.mtype)
  189. @must_be_open
  190. def close(self):
  191. """Function to close the raster"""
  192. self.rowio.release()
  193. libraster.Rast_close(self._fd)
  194. # update rows and cols attributes
  195. self._rows = None
  196. self._cols = None
  197. self._fd = None
  198. @must_be_open
  199. def get_row(self, row, row_buffer=None):
  200. """This method returns the row using:
  201. * the read mode and
  202. * `rowcache` method
  203. :param row: the number of row to obtain
  204. :type row: int
  205. :param row_buffer: Specify the Buffer object that will be instantiate
  206. :type row_buffer: Buffer object
  207. """
  208. if row_buffer is None:
  209. row_buffer = Buffer((self._cols,), self.mtype)
  210. rowio_buf = librowio.Rowio_get(ctypes.byref(self.rowio.c_rowio), row)
  211. ctypes.memmove(row_buffer.p, rowio_buf, self.rowio.row_size)
  212. return row_buffer
  213. class RasterSegment(RasterAbstractBase):
  214. """Raster_segment_access": Inherits "Raster_abstract_base" and uses the
  215. segment library for cached randomly reading and writing access.
  216. * Implements the [row][col] operator for read and write access using
  217. Segment_get() and Segment_put() functions internally
  218. * Implements row read and write access with the [row] operator using
  219. Segment_get_row() Segment_put_row() internally
  220. * Implements the get_row() and put_row() method using
  221. Segment_get_row() Segment_put_row() internally
  222. * Implements the flush_segment() method
  223. * Implements the copying of raster maps to segments and vice verse
  224. * Overwrites the open and close methods
  225. * No mathematical operation like __add__ and stuff for the Raster
  226. object (only for rows), since r.mapcalc is more sophisticated and
  227. faster
  228. """
  229. def __init__(self, name, srows=64, scols=64, maxmem=100,
  230. *args, **kargs):
  231. self.segment = Segment(srows, scols, maxmem)
  232. super(RasterSegment, self).__init__(name, *args, **kargs)
  233. def _get_mode(self):
  234. return self._mode
  235. def _set_mode(self, mode):
  236. if mode and mode.lower() not in ('r', 'w', 'rw'):
  237. str_err = _("Mode type: {0} not supported ('r', 'w','rw')")
  238. raise ValueError(str_err.format(mode))
  239. self._mode = mode
  240. mode = property(fget=_get_mode, fset=_set_mode,
  241. doc="Set or obtain the opening mode of raster")
  242. def __setitem__(self, key, row):
  243. """Return the row of Raster object, slice allowed."""
  244. if isinstance(key, slice):
  245. #Get the start, stop, and step from the slice
  246. return [self.put_row(ii, row)
  247. for ii in range(*key.indices(len(self)))]
  248. elif isinstance(key, tuple):
  249. x, y = key
  250. return self.put(x, y, row)
  251. elif isinstance(key, int):
  252. if key < 0: # Handle negative indices
  253. key += self._rows
  254. if key >= self._rows:
  255. raise IndexError(_("Index out of range: %r.") % key)
  256. return self.put_row(key, row)
  257. else:
  258. raise TypeError("Invalid argument type.")
  259. @must_be_open
  260. def map2segment(self):
  261. """Transform an existing map to segment file.
  262. """
  263. row_buffer = Buffer((self._cols), self.mtype)
  264. for row in range(self._rows):
  265. libraster.Rast_get_row(
  266. self._fd, row_buffer.p, row, self._gtype)
  267. self.segment.put_row(row, row_buffer)
  268. @must_be_open
  269. def segment2map(self):
  270. """Transform the segment file to a map.
  271. """
  272. row_buffer = Buffer((self._cols), self.mtype)
  273. for row in range(self._rows):
  274. row_buffer = self.segment.get_row(row, row_buffer)
  275. libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
  276. @must_be_open
  277. def get_row(self, row, row_buffer=None):
  278. """Return the row using the `segment.get_row` method
  279. :param row: specify the row number
  280. :type row: int
  281. :param row_buffer: specify the Buffer object that will be instantiate
  282. :type row_buffer: Buffer object
  283. """
  284. if row_buffer is None:
  285. row_buffer = Buffer((self._cols), self.mtype)
  286. return self.segment.get_row(row, row_buffer)
  287. @must_be_open
  288. def put_row(self, row, row_buffer):
  289. """Write the row using the `segment.put_row` method
  290. :param row: a Row object to insert into raster
  291. :type row: Buffer object
  292. """
  293. self.segment.put_row(row, row_buffer)
  294. @must_be_open
  295. def get(self, row, col):
  296. """Return the map value using the `segment.get` method
  297. :param row: Specify the row number
  298. :type row: int
  299. :param col: Specify the column number
  300. :type col: int
  301. """
  302. return self.segment.get(row, col)
  303. @must_be_open
  304. def put(self, row, col, val):
  305. """Write the value to the map using the `segment.put` method
  306. :param row: Specify the row number
  307. :type row: int
  308. :param col: Specify the column number
  309. :type col: int
  310. :param val: Specify the value that will be write to the map cell
  311. :type val: value
  312. """
  313. self.segment.val.value = val
  314. self.segment.put(row, col)
  315. def open(self, mode=None, mtype=None, overwrite=None):
  316. """Open the map, if the map already exist: determine the map type
  317. and copy the map to the segment files;
  318. else, open a new segment map.
  319. :param mode: specify if the map will be open with read, write or
  320. read/write mode ('r', 'w', 'rw')
  321. :type mode: str
  322. :param mtype: specify the map type, valid only for new maps: CELL,
  323. FCELL, DCELL
  324. :type mtype: str
  325. :param overwrite: use this flag to set the overwrite mode of existing
  326. raster maps
  327. :type overwrite: bool
  328. """
  329. # read rows and cols from the active region
  330. self._rows = libraster.Rast_window_rows()
  331. self._cols = libraster.Rast_window_cols()
  332. self.mode = mode if mode else self.mode
  333. self.mtype = mtype if mtype else self.mtype
  334. self.overwrite = overwrite if overwrite is not None else self.overwrite
  335. if self.exist():
  336. self.info.read()
  337. self.cats.mtype = self.mtype
  338. self.cats.read()
  339. self.hist.read()
  340. if ((self.mode == "w" or self.mode == "rw") and
  341. self.overwrite is False):
  342. str_err = _("Raster map <{0}> already exists. Use overwrite.")
  343. fatal(str_err.format(self))
  344. # We copy the raster map content into the segments
  345. if self.mode == "rw" or self.mode == "r":
  346. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  347. self._gtype = libraster.Rast_get_map_type(self._fd)
  348. self.mtype = RTYPE_STR[self._gtype]
  349. # initialize the segment, I need to determine the mtype of the
  350. # map
  351. # before to open the segment
  352. self.segment.open(self)
  353. self.map2segment()
  354. self.segment.flush()
  355. self.cats.read()
  356. self.hist.read()
  357. if self.mode == "rw":
  358. warning(_(WARN_OVERWRITE.format(self)))
  359. # Close the file descriptor and open it as new again
  360. libraster.Rast_close(self._fd)
  361. self._fd = libraster.Rast_open_new(
  362. self.name, self._gtype)
  363. # Here we simply overwrite the existing map without content copying
  364. elif self.mode == "w":
  365. #warning(_(WARN_OVERWRITE.format(self)))
  366. self._gtype = RTYPE[self.mtype]['grass type']
  367. self.segment.open(self)
  368. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  369. else:
  370. if self.mode == "r":
  371. str_err = _("Raster map <{0}> does not exists")
  372. raise OpenError(str_err.format(self.name))
  373. self._gtype = RTYPE[self.mtype]['grass type']
  374. self.segment.open(self)
  375. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  376. @must_be_open
  377. def close(self, rm_temp_files=True):
  378. """Close the map, copy the segment files to the map.
  379. :param rm_temp_files: if True all the segments file will be removed
  380. :type rm_temp_files: bool
  381. """
  382. if self.mode == "w" or self.mode == "rw":
  383. self.segment.flush()
  384. self.segment2map()
  385. if rm_temp_files:
  386. self.segment.close()
  387. else:
  388. self.segment.release()
  389. libraster.Rast_close(self._fd)
  390. # update rows and cols attributes
  391. self._rows = None
  392. self._cols = None
  393. self._fd = None
  394. def random_map_only_columns(mapname, mtype, overwrite=True, factor=100):
  395. region = Region()
  396. random_map = RasterRow(mapname)
  397. row_buf = Buffer((region.cols, ), mtype,
  398. buffer=(np.random.random(region.cols,) * factor).data)
  399. random_map.open('w', mtype, overwrite)
  400. for _ in range(region.rows):
  401. random_map.put_row(row_buf)
  402. random_map.close()
  403. return random_map
  404. def random_map(mapname, mtype, overwrite=True, factor=100):
  405. region = Region()
  406. random_map = RasterRow(mapname)
  407. random_map.open('w', mtype, overwrite)
  408. for _ in range(region.rows):
  409. row_buf = Buffer((region.cols, ), mtype,
  410. buffer=(np.random.random(region.cols,) * factor).data)
  411. random_map.put_row(row_buf)
  412. random_map.close()
  413. return random_map
  414. def raster2numpy(rastname, mapset=''):
  415. """Return a numpy array from a raster map
  416. :param str rastname: the name of raster map
  417. :parar str mapser: the name of mapset containig raster map
  418. """
  419. with RasterRow(rastname, mapset=mapset, mode='r') as rast:
  420. return np.array(rast)
  421. def numpy2raster(array, mtype, rastname, overwrite=False):
  422. """Save a numpy array to a raster map
  423. :param obj array: a numpy array
  424. :param obj mtype: the datatype of array
  425. :param str rastername: the name of output map
  426. :param bool overwrite: True to overwrite existing map
  427. """
  428. reg = Region()
  429. if (reg.rows, reg.cols) != array.shape:
  430. msg = "Region and array are different: %r != %r"
  431. raise TypeError(msg % ((reg.rows, reg.cols), array.shape))
  432. with RasterRow(rastname, mode='w', mtype=mtype, overwrite=overwrite) as new:
  433. newrow = Buffer((array.shape[1],), mtype=mtype)
  434. for row in array:
  435. newrow[:] = row[:]
  436. new.put_row(newrow)