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