__init__.py 24 KB

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