__init__.py 23 KB

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