__init__.py 24 KB

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