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