__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Fri May 25 12:56:33 2012
  4. @author: pietro
  5. """
  6. import ctypes
  7. import numpy as np
  8. #
  9. # import GRASS modules
  10. #
  11. from grass.script import fatal, warning
  12. from grass.script import core as grasscore
  13. #from grass.script import core
  14. #import grass.lib as grasslib
  15. import grass.lib.gis as libgis
  16. import grass.lib.raster as libraster
  17. import grass.lib.segment as libseg
  18. import grass.lib.rowio as librowio
  19. #
  20. # import pygrass modules
  21. #
  22. from grass.pygrass.errors import OpenError, must_be_open
  23. from grass.pygrass.gis.region import Region
  24. from grass.pygrass import functions
  25. #
  26. # import raster classes
  27. #
  28. from abstract import RasterAbstractBase, Info
  29. from raster_type import TYPE as RTYPE, RTYPE_STR
  30. from buffer import Buffer
  31. from segment import Segment
  32. from rowio import RowIO
  33. class RasterRow(RasterAbstractBase):
  34. """Raster_row_access": Inherits: "Raster_abstract_base" and implements
  35. the default row access of the Rast library.
  36. * Implements row access using row id
  37. * The get_row() method must accept a Row object as argument that will
  38. be used for value storage, so no new buffer will be allocated
  39. * Implements sequential writing of rows
  40. * Implements indexed value read only access using the [row][col]
  41. operator
  42. * Implements the [row] read method that returns a new Row object
  43. * Writing is limited using the put_row() method which accepts a
  44. Row as argument
  45. * No mathematical operation like __add__ and stuff for the Raster
  46. object (only for rows), since r.mapcalc is more sophisticated and
  47. faster
  48. Examples
  49. --------
  50. ::
  51. >>> elev = RasterRow('elevation')
  52. >>> elev.exist()
  53. True
  54. >>> elev.is_open()
  55. False
  56. >>> elev.cols
  57. >>> elev.open()
  58. >>> elev.is_open()
  59. True
  60. >>> type(elev.cols)
  61. <type 'int'>
  62. >>> elev.has_cats()
  63. False
  64. >>> elev.mode
  65. 'r'
  66. >>> elev.mtype
  67. 'FCELL'
  68. >>> elev.num_cats()
  69. 0
  70. >>> elev.range
  71. (55.578792572021484, 156.32986450195312)
  72. Each Raster map have an attribute call ``cats`` that allow user
  73. to interact with the raster categories. ::
  74. >>> land = RasterRow('landcover_1m')
  75. >>> land.open()
  76. >>> land.cats
  77. []
  78. >>> land.read_cats()
  79. >>> land.cats
  80. [('pond', 1, None),
  81. ('forest', 2, None),
  82. ('developed', 3, None),
  83. ('bare', 4, None),
  84. ('paved road', 5, None),
  85. ('dirt road', 6, None),
  86. ('vineyard', 7, None),
  87. ('agriculture', 8, None),
  88. ('wetland', 9, None),
  89. ('bare ground path', 10, None),
  90. ('grass', 11, None)]
  91. Open a raster map using the *with statement*: ::
  92. >>> with RasterRow('elevation') as elev:
  93. ... for row in elev[:3]:
  94. ... print row[:4]
  95. ...
  96. [ 141.99613953 141.27848816 141.37904358 142.29821777]
  97. [ 142.90461731 142.39450073 142.68611145 143.59086609]
  98. [ 143.81854248 143.54707336 143.83972168 144.59527588]
  99. >>> elev.is_open()
  100. False
  101. """
  102. def __init__(self, name, mapset='', *args, **kargs):
  103. super(RasterRow, self).__init__(name, mapset, *args, **kargs)
  104. # mode = "r", method = "row",
  105. @must_be_open
  106. def get_row(self, row, row_buffer=None):
  107. """Private method that return the row using the read mode
  108. call the `Rast_get_row` C function.
  109. >>> elev = RasterRow('elevation')
  110. >>> elev.open()
  111. >>> elev[0] # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  112. Buffer([ 141.99613953, 141.27848816, 141.37904358, ..., 58.40825272,
  113. 58.30711365, 58.18310547], dtype=float32)
  114. >>> elev.get_row(0) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  115. Buffer([ 141.99613953, 141.27848816, 141.37904358, ..., 58.40825272,
  116. 58.30711365, 58.18310547], dtype=float32)
  117. """
  118. if row_buffer is None:
  119. row_buffer = Buffer((self._cols,), self.mtype)
  120. libraster.Rast_get_row(self._fd, row_buffer.p, row, self._gtype)
  121. return row_buffer
  122. @must_be_open
  123. def put_row(self, row):
  124. """Private method to write the row sequentially.
  125. """
  126. libraster.Rast_put_row(self._fd, row.p, self._gtype)
  127. def open(self, mode='r', mtype='CELL', overwrite=False):
  128. """Open the raster if exist or created a new one.
  129. Parameters
  130. ------------
  131. mode: string
  132. Specify if the map will be open with read or write mode ('r', 'w')
  133. type: string
  134. If a new map is open, specify the type of the map(`CELL`, `FCELL`,
  135. `DCELL`)
  136. overwrite: Boolean
  137. Use this flag to set the overwrite mode of existing raster maps
  138. if the map already exist, automatically check the type and set:
  139. * self.mtype
  140. Set all the privite, attributes:
  141. * self._fd;
  142. * self._gtype
  143. * self._rows and self._cols
  144. """
  145. self.mode = mode
  146. self.mtype = mtype
  147. self.overwrite = overwrite
  148. # check if exist and instantiate all the private attributes
  149. if self.exist():
  150. self.info = Info(self.name, self.mapset)
  151. if self.mode == 'r':
  152. # the map exist, read mode
  153. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  154. self._gtype = libraster.Rast_get_map_type(self._fd)
  155. self.mtype = RTYPE_STR[self._gtype]
  156. self.cats.read(self)
  157. self.hist.read(self.name)
  158. elif self.overwrite:
  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. str_err = _("Raster map <{0}> already exists")
  164. raise OpenError(str_err.format(self))
  165. else:
  166. # Create a new map
  167. if self.mode == 'r':
  168. # check if we are in read mode
  169. str_err = _("The map does not exist, I can't open in 'r' mode")
  170. raise OpenError(str_err)
  171. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  172. # read rows and cols from the active region
  173. self._rows = libraster.Rast_window_rows()
  174. self._cols = libraster.Rast_window_cols()
  175. class RasterRowIO(RasterRow):
  176. """Raster_row_cache_access": The same as "Raster_row_access" but uses
  177. the ROWIO library for cached row access
  178. """
  179. def __init__(self, name, *args, **kargs):
  180. self.rowio = RowIO()
  181. super(RasterRowIO, self).__init__(name, *args, **kargs)
  182. def open(self, mode='r', mtype='CELL', overwrite=False):
  183. super(RasterRowIO, self).open(mode, mtype, overwrite)
  184. self.rowio.open(self._fd, self._rows, self._cols, self.mtype)
  185. @must_be_open
  186. def close(self):
  187. self.rowio.release()
  188. libraster.Rast_close(self._fd)
  189. # update rows and cols attributes
  190. self._rows = None
  191. self._cols = None
  192. self._fd = None
  193. @must_be_open
  194. def get_row(self, row, row_buffer=None):
  195. """This method returns the row using:
  196. * the read mode and
  197. * `rowcache` method
  198. """
  199. if row_buffer is None:
  200. row_buffer = Buffer((self._cols,), self.mtype)
  201. rowio_buf = librowio.Rowio_get(ctypes.byref(self.rowio.c_rowio), row)
  202. ctypes.memmove(row_buffer.p, rowio_buf, self.rowio.row_size)
  203. return row_buffer
  204. class RasterSegment(RasterAbstractBase):
  205. """Raster_segment_access": Inherits "Raster_abstract_base" and uses the
  206. segment library for cached randomly reading and writing access.
  207. * Implements the [row][col] operator for read and write access using
  208. segement_get() and segment_put() functions internally
  209. * Implements row read and write access with the [row] operator using
  210. segment_get_row() segment_put_row() internally
  211. * Implements the get_row() and put_row() method using
  212. segment_get_row() segment_put_row() internally
  213. * Implements the flush_segment() method
  214. * Implements the copying of raster maps to segments and vice verse
  215. * Overwrites the open and close methods
  216. * No mathematical operation like __add__ and stuff for the Raster
  217. object (only for rows), since r.mapcalc is more sophisticated and
  218. faster
  219. """
  220. def __init__(self, name, srows=64, scols=64, maxmem=100,
  221. *args, **kargs):
  222. self.segment = Segment(srows, scols, maxmem)
  223. super(RasterSegment, self).__init__(name, *args, **kargs)
  224. def _get_mode(self):
  225. return self._mode
  226. def _set_mode(self, mode):
  227. if mode.lower() not in ('r', 'w', 'rw'):
  228. str_err = _("Mode type: {0} not supported ('r', 'w','rw')")
  229. raise ValueError(str_err.format(mode))
  230. self._mode = mode
  231. mode = property(fget=_get_mode, fset=_set_mode)
  232. def __setitem__(self, key, row):
  233. """Return the row of Raster object, slice allowed."""
  234. if isinstance(key, slice):
  235. #Get the start, stop, and step from the slice
  236. return [self.put_row(ii, row)
  237. for ii in xrange(*key.indices(len(self)))]
  238. elif isinstance(key, tuple):
  239. x, y = key
  240. return self.put(x, y, row)
  241. elif isinstance(key, int):
  242. if key < 0: # Handle negative indices
  243. key += self._rows
  244. if key >= self._rows:
  245. raise IndexError(_("Index out of range: %r.") % key)
  246. return self.put_row(key, row)
  247. else:
  248. raise TypeError("Invalid argument type.")
  249. @must_be_open
  250. def map2segment(self):
  251. """Transform an existing map to segment file.
  252. """
  253. row_buffer = Buffer((self._cols), self.mtype)
  254. for row in xrange(self._rows):
  255. libraster.Rast_get_row(
  256. self._fd, row_buffer.p, row, self._gtype)
  257. libseg.segment_put_row(ctypes.byref(self.segment.cseg),
  258. row_buffer.p, row)
  259. @must_be_open
  260. def segment2map(self):
  261. """Transform the segment file to a map.
  262. """
  263. row_buffer = Buffer((self._cols), self.mtype)
  264. for row in xrange(self._rows):
  265. libseg.segment_get_row(ctypes.byref(self.segment.cseg),
  266. row_buffer.p, row)
  267. libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
  268. @must_be_open
  269. def get_row(self, row, row_buffer=None):
  270. """Return the row using the `segment.get_row` method
  271. Parameters
  272. ------------
  273. row: integer
  274. Specify the row number;
  275. row_buffer: Buffer object, optional
  276. Specify the Buffer object that will be instantiate.
  277. """
  278. if row_buffer is None:
  279. row_buffer = Buffer((self._cols), self.mtype)
  280. libseg.segment_get_row(
  281. ctypes.byref(self.segment.cseg), row_buffer.p, row)
  282. return row_buffer
  283. @must_be_open
  284. def put_row(self, row, row_buffer):
  285. """Write the row using the `segment.put_row` method
  286. Parameters
  287. ------------
  288. row: integer
  289. Specify the row number;
  290. row_buffer: Buffer object
  291. Specify the Buffer object that will be write to the map.
  292. """
  293. libseg.segment_put_row(ctypes.byref(self.segment.cseg),
  294. row_buffer.p, row)
  295. @must_be_open
  296. def get(self, row, col):
  297. """Return the map value using the `segment.get` method
  298. Parameters
  299. ------------
  300. row: integer
  301. Specify the row number;
  302. col: integer
  303. Specify the column number.
  304. """
  305. libseg.segment_get(ctypes.byref(self.segment.cseg),
  306. ctypes.byref(self.segment.val), row, col)
  307. return self.segment.val.value
  308. @must_be_open
  309. def put(self, row, col, val):
  310. """Write the value to the map using the `segment.put` method
  311. Parameters
  312. ------------
  313. row: integer
  314. Specify the row number;
  315. col: integer
  316. Specify the column number.
  317. val: value
  318. Specify the value that will be write to the map cell.
  319. """
  320. self.segment.val.value = val
  321. libseg.segment_put(ctypes.byref(self.segment.cseg),
  322. ctypes.byref(self.segment.val), row, col)
  323. def open(self, mode='r', mtype='DCELL', overwrite=False):
  324. """Open the map, if the map already exist: determine the map type
  325. and copy the map to the segment files;
  326. else, open a new segment map.
  327. Parameters
  328. ------------
  329. mode: string, optional
  330. Specify if the map will be open with read, write or read/write
  331. mode ('r', 'w', 'rw')
  332. mtype: string, optional
  333. Specify the map type, valid only for new maps: CELL, FCELL, DCELL;
  334. overwrite: Boolean, optional
  335. Use this flag to set the overwrite mode of existing raster maps
  336. """
  337. # read rows and cols from the active region
  338. self._rows = libraster.Rast_window_rows()
  339. self._cols = libraster.Rast_window_cols()
  340. self.overwrite = overwrite
  341. self.mode = mode
  342. self.mtype = mtype
  343. if self.exist():
  344. self.info = Info(self.name, self.mapset)
  345. if ((self.mode == "w" or self.mode == "rw") and
  346. self.overwrite is False):
  347. str_err = _("Raster map <{0}> already exists. Use overwrite.")
  348. fatal(str_err.format(self))
  349. # We copy the raster map content into the segments
  350. if self.mode == "rw" or self.mode == "r":
  351. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  352. self._gtype = libraster.Rast_get_map_type(self._fd)
  353. self.mtype = RTYPE_STR[self._gtype]
  354. # initialize the segment, I need to determine the mtype of the
  355. # map
  356. # before to open the segment
  357. self.segment.open(self)
  358. self.map2segment()
  359. self.segment.flush()
  360. self.cats.read(self)
  361. self.hist.read(self.name)
  362. if self.mode == "rw":
  363. warning(_(WARN_OVERWRITE.format(self)))
  364. # Close the file descriptor and open it as new again
  365. libraster.Rast_close(self._fd)
  366. self._fd = libraster.Rast_open_new(
  367. self.name, self._gtype)
  368. # Here we simply overwrite the existing map without content copying
  369. elif self.mode == "w":
  370. #warning(_(WARN_OVERWRITE.format(self)))
  371. self._gtype = RTYPE[self.mtype]['grass type']
  372. self.segment.open(self)
  373. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  374. else:
  375. if self.mode == "r":
  376. str_err = _("Raster map <{0}> does not exists")
  377. raise OpenError(str_err.format(self.name))
  378. self._gtype = RTYPE[self.mtype]['grass type']
  379. self.segment.open(self)
  380. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  381. @must_be_open
  382. def close(self, rm_temp_files=True):
  383. """Close the map, copy the segment files to the map.
  384. Parameters
  385. ------------
  386. rm_temp_files: bool
  387. If True all the segments file will be removed.
  388. """
  389. if self.mode == "w" or self.mode == "rw":
  390. self.segment.flush()
  391. self.segment2map()
  392. if rm_temp_files:
  393. self.segment.close()
  394. else:
  395. self.segment.release()
  396. libraster.Rast_close(self._fd)
  397. # update rows and cols attributes
  398. self._rows = None
  399. self._cols = None
  400. self._fd = None
  401. FLAGS = {1: {'b': 'i', 'i': 'i', 'u': 'i'},
  402. 2: {'b': 'i', 'i': 'i', 'u': 'i'},
  403. 4: {'f': 'f', 'i': 'i', 'b': 'i', 'u': 'i'},
  404. 8: {'f': 'd'}, }
  405. class RasterNumpy(np.memmap, RasterAbstractBase):
  406. """Raster_cached_narray": Inherits "Raster_abstract_base" and
  407. "numpy.memmap". Its purpose is to allow numpy narray like access to
  408. raster maps without loading the map into the main memory.
  409. * Behaves like a numpy array and supports all kind of mathematical
  410. operations: __add__, ...
  411. * Overrides the open and close methods
  412. * Be aware of the 2Gig file size limit
  413. >>> import grass.pygrass as pygrass
  414. >>> elev = pygrass.raster.RasterNumpy('elevation')
  415. >>> elev.open()
  416. >>> elev[:5, :3]
  417. RasterNumpy([[ 141.99613953, 141.27848816, 141.37904358],
  418. [ 142.90461731, 142.39450073, 142.68611145],
  419. [ 143.81854248, 143.54707336, 143.83972168],
  420. [ 144.56524658, 144.58493042, 144.86477661],
  421. [ 144.99488831, 145.22894287, 145.57142639]], dtype=float32)
  422. >>> el = elev < 144
  423. >>> el[:5, :3]
  424. RasterNumpy([[ True, True, True],
  425. [ True, True, True],
  426. [ True, True, True],
  427. [False, False, False],
  428. [False, False, False]], dtype=bool)
  429. >>> el._write()
  430. 0
  431. """
  432. def __new__(cls, name, mapset="", mtype='CELL', mode='r+',
  433. overwrite=False):
  434. reg = Region()
  435. shape = (reg.rows, reg.cols)
  436. mapset = libgis.G_find_raster(name, mapset)
  437. gtype = None
  438. if mapset:
  439. # map exist, set the map type
  440. gtype = libraster.Rast_map_type(name, mapset)
  441. mtype = RTYPE_STR[gtype]
  442. filename = grasscore.tempfile()
  443. obj = np.memmap.__new__(cls, filename=filename,
  444. dtype=RTYPE[mtype]['numpy'],
  445. mode=mode,
  446. shape=shape)
  447. obj.mtype = mtype.upper()
  448. obj.gtype = gtype if gtype else RTYPE[mtype]['grass type']
  449. obj._rows = reg.rows
  450. obj._cols = reg.cols
  451. obj.filename = filename
  452. obj._name = name
  453. obj.mapset = mapset
  454. obj.reg = reg
  455. obj.overwrite = overwrite
  456. return obj
  457. def __array_finalize__(self, obj):
  458. if hasattr(obj, '_mmap'):
  459. self._mmap = obj._mmap
  460. self.filename = grasscore.tempfile()
  461. self.offset = obj.offset
  462. self.mode = obj.mode
  463. self._rows = obj._rows
  464. self._cols = obj._cols
  465. self._name = None
  466. self.mapset = ''
  467. self.reg = obj.reg
  468. self.overwrite = obj.overwrite
  469. self.mtype = obj.mtype
  470. self._fd = obj._fd
  471. else:
  472. self._mmap = None
  473. def _get_mode(self):
  474. return self._mode
  475. def _set_mode(self, mode):
  476. if mode.lower() not in ('r', 'w+', 'r+', 'c'):
  477. raise ValueError(_("Mode type: {0} not supported.").format(mode))
  478. self._mode = mode
  479. mode = property(fget=_get_mode, fset=_set_mode)
  480. def __array_wrap__(self, out_arr, context=None):
  481. """See:
  482. http://docs.scipy.org/doc/numpy/user/
  483. basics.subclassing.html#array-wrap-for-ufuncs"""
  484. if out_arr.dtype.kind in 'bui':
  485. # there is not support for boolean maps, so convert into integer
  486. out_arr = out_arr.astype(np.int32)
  487. out_arr.mtype = 'CELL'
  488. #out_arr.p = out_arr.ctypes.data_as(out_arr.pointer_type)
  489. return np.ndarray.__array_wrap__(self, out_arr, context)
  490. def __init__(self, name, *args, **kargs):
  491. ## Private attribute `_fd` that return the file descriptor of the map
  492. self._fd = None
  493. rows, cols = self._rows, self._cols
  494. RasterAbstractBase.__init__(self, name)
  495. self._rows, self._cols = rows, cols
  496. def __unicode__(self):
  497. return RasterAbstractBase.__unicode__(self)
  498. def __str__(self):
  499. return self.__unicode__()
  500. def _get_flags(self, size, kind):
  501. if size in FLAGS:
  502. if kind in FLAGS[size]:
  503. return size, FLAGS[size][kind]
  504. else:
  505. raise ValueError(_('Invalid type {0}'.forma(kind)))
  506. else:
  507. raise ValueError(_('Invalid size {0}'.format(size)))
  508. def _read(self):
  509. """!Read raster map into array
  510. @return 0 on success
  511. @return non-zero code on failure
  512. """
  513. self.null = None
  514. size, kind = self._get_flags(self.dtype.itemsize, self.dtype.kind)
  515. kind = 'f' if kind == 'd' else kind
  516. ret = grasscore.run_command('r.out.bin', flags=kind,
  517. input=self._name, output=self.filename,
  518. bytes=size, null=self.null,
  519. quiet=True)
  520. return ret
  521. def _write(self):
  522. """
  523. r.in.bin input=/home/pietro/docdat/phd/thesis/gis/north_carolina/user1/.tmp/eraclito/14325.0 output=new title='' bytes=1,anull='' --verbose --overwrite north=228500.0 south=215000.0 east=645000.0 west=630000.0 rows=1350 cols=1500
  524. """
  525. self.tofile(self.filename)
  526. size, kind = self._get_flags(self.dtype.itemsize, self.dtype.kind)
  527. #print size, kind
  528. if kind == 'i':
  529. kind = None
  530. size = 4
  531. size = None if kind == 'f' else size
  532. # To be set in the future
  533. self.title = None
  534. self.null = None
  535. #import pdb; pdb.set_trace()
  536. if self.mode in ('w+', 'r+'):
  537. if not self._name:
  538. import os
  539. self._name = "doctest_%i" % os.getpid()
  540. ret = grasscore.run_command('r.in.bin', flags=kind,
  541. input=self.filename, output=self._name,
  542. title=self.title, bytes=size,
  543. anull=self.null,
  544. overwrite=self.overwrite,
  545. verbose=True,
  546. north=self.reg.north,
  547. south=self.reg.south,
  548. east=self.reg.east,
  549. west=self.reg.west,
  550. rows=self.reg.rows,
  551. cols=self.reg.cols)
  552. return ret
  553. def open(self, mtype='', null=None, overwrite=None):
  554. """Open the map, if the map already exist: determine the map type
  555. and copy the map to the segment files;
  556. else, open a new segment map.
  557. Parameters
  558. ------------
  559. mtype: string, optional
  560. Specify the map type, valid only for new maps: CELL, FCELL, DCELL;
  561. """
  562. if overwrite is not None:
  563. self.overwrite = overwrite
  564. self.null = null
  565. # rows and cols already set in __new__
  566. if self.exist():
  567. self._read()
  568. else:
  569. if mtype:
  570. self.mtype = mtype
  571. self._gtype = RTYPE[self.mtype]['grass type']
  572. # set _fd, because this attribute is used to check
  573. # if the map is open or not
  574. self._fd = 1
  575. def close(self):
  576. self._write()
  577. np.memmap._close(self)
  578. grasscore.try_remove(self.filename)
  579. self._fd = None
  580. def get_value(self, point, region=None):
  581. """This method returns the pixel value of a given pair of coordinates:
  582. Parameters
  583. ------------
  584. point = pair of coordinates in tuple object
  585. """
  586. if not region:
  587. region = Region()
  588. x, y = functions.coor2pixel(point.coords(), region)
  589. return self[x][y]
  590. def random_map_only_columns(mapname, mtype, overwrite=True, factor=100):
  591. region = Region()
  592. random_map = RasterRow(mapname)
  593. row_buf = Buffer((region.cols, ), mtype,
  594. buffer=(np.random.random(region.cols,) * factor).data)
  595. random_map.open('w', mtype, overwrite)
  596. for _ in xrange(region.rows):
  597. random_map.put_row(row_buf)
  598. random_map.close()
  599. return random_map
  600. def random_map(mapname, mtype, overwrite=True, factor=100):
  601. region = Region()
  602. random_map = RasterRow(mapname)
  603. random_map.open('w', mtype, overwrite)
  604. for _ in xrange(region.rows):
  605. row_buf = Buffer((region.cols, ), mtype,
  606. buffer=(np.random.random(region.cols,) * factor).data)
  607. random_map.put_row(row_buf)
  608. random_map.close()
  609. return random_map