__init__.py 24 KB

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