[GRASS-SVN] r66056 - in grass/trunk/lib/python/pygrass: gis gis/testsuite raster
svn_grass at osgeo.org
svn_grass at osgeo.org
Fri Aug 28 09:22:16 PDT 2015
Author: huhabla
Date: 2015-08-28 09:22:15 -0700 (Fri, 28 Aug 2015)
New Revision: 66056
Modified:
grass/trunk/lib/python/pygrass/gis/__init__.py
grass/trunk/lib/python/pygrass/gis/region.py
grass/trunk/lib/python/pygrass/gis/testsuite/test_doctests.py
grass/trunk/lib/python/pygrass/raster/__init__.py
grass/trunk/lib/python/pygrass/raster/abstract.py
grass/trunk/lib/python/pygrass/raster/history.py
Log:
pygrass raster: Updated and corrected the Region class, changed and added doctests in several raster classes
Modified: grass/trunk/lib/python/pygrass/gis/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/gis/__init__.py 2015-08-28 16:13:57 UTC (rev 66055)
+++ grass/trunk/lib/python/pygrass/gis/__init__.py 2015-08-28 16:22:15 UTC (rev 66056)
@@ -15,6 +15,9 @@
from grass.pygrass.errors import GrassError
+test_vector_name="Gis_test_vector"
+test_raster_name="Gis_test_raster"
+
ETYPE = {'raster': libgis.G_ELEMENT_RASTER,
'raster_3d': libgis.G_ELEMENT_RASTER3D,
'vector': libgis.G_ELEMENT_VECTOR,
@@ -319,13 +322,14 @@
::
- >>> mapset = Mapset('PERMANENT')
+ >>> mapset = Mapset()
+ >>> mapset.current()
>>> rast = mapset.glist('raster')
- >>> rast.sort()
- >>> rast # doctest: +ELLIPSIS
- ['basins', 'elevation', ...]
- >>> sorted(mapset.glist('raster', pattern='el*'))
- ['elevation', 'elevation_shade']
+ >>> test_raster_name in rast
+ True
+ >>> vect = mapset.glist('vector')
+ >>> test_vector_name in vect
+ True
..
"""
@@ -366,13 +370,7 @@
class VisibleMapset(object):
- """VisibleMapset object::
-
- >>> mapset = VisibleMapset('user1')
- >>> mapset # doctest: +ELLIPSIS
- [...]
-
- ..
+ """VisibleMapset object
"""
def __init__(self, mapset, location='', gisdbase=''):
self.mapset = mapset
@@ -444,3 +442,24 @@
"""Reset to the original search path"""
final = [self.mapset, 'PERMANENT']
self._write(final)
+
+if __name__ == "__main__":
+ import doctest
+ from grass.pygrass import utils
+ from grass.script.core import run_command
+
+ utils.create_test_vector_map(test_vector_name)
+ run_command("g.region", n=50, s=0, e=60, w=0, res=1)
+ run_command("r.mapcalc", expression="%s = 1"%(test_raster_name),
+ overwrite=True)
+ run_command("g.region", n=40, s=0, e=40, w=0, res=2)
+
+ doctest.testmod()
+
+ """Remove the generated vector map, if exist"""
+ mset = utils.get_mapset_vector(test_vector_name, mapset='')
+ if mset:
+ run_command("g.remove", flags='f', type='vector', name=test_vector_name)
+ mset = utils.get_mapset_raster(test_raster_name, mapset='')
+ if mset:
+ run_command("g.remove", flags='f', type='raster', name=test_raster_name)
Modified: grass/trunk/lib/python/pygrass/gis/region.py
===================================================================
--- grass/trunk/lib/python/pygrass/gis/region.py 2015-08-28 16:13:57 UTC (rev 66055)
+++ grass/trunk/lib/python/pygrass/gis/region.py 2015-08-28 16:22:15 UTC (rev 66056)
@@ -8,116 +8,176 @@
with_statement, print_function, unicode_literals)
import ctypes
import grass.lib.gis as libgis
+import grass.lib.raster as libraster
import grass.script as grass
from grass.pygrass.errors import GrassError
from grass.pygrass.shell.conversion import dict2html
+from grass.pygrass.utils import get_mapset_vector, get_mapset_raster
+test_vector_name="Region_test_vector"
+test_raster_name="Region_test_raster"
class Region(object):
"""This class is design to easily access and modify GRASS computational
region. ::
- >>> default = Region(default=True)
- >>> current_original = Region()
- >>> current = Region()
- >>> current.align('elevation')
- >>> default == current
- True
- >>> current.cols
- 1500
- >>> current.ewres
- 10.0
- >>> current.cols = 3000
- >>> current.ewres
+ >>> r = Region()
+ >>> r.north
+ 40.0
+ >>> r.south
+ 0.0
+ >>> r.east
+ 40.0
+ >>> r.west
+ 0.0
+ >>> r.cols
+ 20
+ >>> r.rows
+ 20
+ >>> r.nsres
+ 2.0
+ >>> r.ewres
+ 2.0
+
+ >>> r.north = 100
+ >>> r.east = 100
+ >>> r.adjust(rows=True, cols=True)
+ >>> r.nsres
5.0
- >>> current.ewres = 20.0
- >>> current.cols
- 750
- >>> current.set_current()
- >>> default == current
- False
- >>> current.get_default()
- >>> default = Region(default=True)
- >>> default == current
- True
- >>> current_original.set_current()
+ >>> r.ewres
+ 5.0
+ >>> r.cols
+ 20
+ >>> r.rows
+ 20
+ >>> r.read()
+ >>> r.north = 100
+ >>> r.east = 100
+ >>> r.adjust(rows=False, cols=True)
+ >>> r.nsres
+ 2.0
+ >>> r.ewres
+ 5.0
+ >>> r.cols
+ 20
+ >>> r.rows
+ 50
+
+ >>> r.read()
+ >>> r.north = 100
+ >>> r.east = 100
+ >>> r.adjust(rows=True, cols=False)
+ >>> r.nsres
+ 5.0
+ >>> r.ewres
+ 2.0
+ >>> r.cols
+ 50
+ >>> r.rows
+ 20
+
+ >>> r.read()
+ >>> r.north = 100
+ >>> r.east = 100
+ >>> r.adjust(rows=False, cols=False)
+ >>> r.nsres
+ 2.0
+ >>> r.ewres
+ 2.0
+ >>> r.cols
+ 50
+ >>> r.rows
+ 50
+
+ >>> r.read()
+ >>> r.cols = 1000
+ >>> r.ewres
+ 0.04
+ >>> r.rows = 1000
+ >>> r.nsres
+ 0.04
+
..
"""
def __init__(self, default=False):
- self.c_region = ctypes.pointer(libgis.Cell_head())
+ self.c_region = libgis.Cell_head()
if default:
- self.get_default()
+ self.read_default()
else:
- self.get_current()
+ self.read()
+ def byref(self):
+ """Return the internal region representation as pointer"""
+ return ctypes.pointer(self.c_region)
+
def _set_param(self, key, value):
grass.run_command('g.region', **{key: value})
#----------LIMITS----------
def _get_n(self):
"""Private function to obtain north value"""
- return self.c_region.contents.north
+ return self.c_region.north
def _set_n(self, value):
"""Private function to set north value"""
- self.c_region.contents.north = value
+ self.c_region.north = value
north = property(fget=_get_n, fset=_set_n,
doc="Set and obtain north coordinate")
def _get_s(self):
"""Private function to obtain south value"""
- return self.c_region.contents.south
+ return self.c_region.south
def _set_s(self, value):
"""Private function to set south value"""
- self.c_region.contents.south = value
+ self.c_region.south = value
south = property(fget=_get_s, fset=_set_s,
doc="Set and obtain south coordinate")
def _get_e(self):
"""Private function to obtain east value"""
- return self.c_region.contents.east
+ return self.c_region.east
def _set_e(self, value):
"""Private function to set east value"""
- self.c_region.contents.east = value
+ self.c_region.east = value
east = property(fget=_get_e, fset=_set_e,
doc="Set and obtain east coordinate")
def _get_w(self):
"""Private function to obtain west value"""
- return self.c_region.contents.west
+ return self.c_region.west
def _set_w(self, value):
"""Private function to set west value"""
- self.c_region.contents.west = value
+ self.c_region.west = value
west = property(fget=_get_w, fset=_set_w,
doc="Set and obtain west coordinate")
def _get_t(self):
"""Private function to obtain top value"""
- return self.c_region.contents.top
+ return self.c_region.top
def _set_t(self, value):
"""Private function to set top value"""
- self.c_region.contents.top = value
+ self.c_region.top = value
top = property(fget=_get_t, fset=_set_t,
doc="Set and obtain top value")
def _get_b(self):
"""Private function to obtain bottom value"""
- return self.c_region.contents.bottom
+ return self.c_region.bottom
def _set_b(self, value):
"""Private function to set bottom value"""
- self.c_region.contents.bottom = value
+ self.c_region.bottom = value
bottom = property(fget=_get_b, fset=_set_b,
doc="Set and obtain bottom value")
@@ -125,11 +185,11 @@
#----------RESOLUTION----------
def _get_rows(self):
"""Private function to obtain rows value"""
- return self.c_region.contents.rows
+ return self.c_region.rows
def _set_rows(self, value):
"""Private function to set rows value"""
- self.c_region.contents.rows = value
+ self.c_region.rows = value
self.adjust(rows=True)
rows = property(fget=_get_rows, fset=_set_rows,
@@ -137,23 +197,34 @@
def _get_cols(self):
"""Private function to obtain columns value"""
- return self.c_region.contents.cols
+ return self.c_region.cols
def _set_cols(self, value):
"""Private function to set columns value"""
- self.c_region.contents.cols = value
+ self.c_region.cols = value
self.adjust(cols=True)
cols = property(fget=_get_cols, fset=_set_cols,
doc="Set and obtain number of columns")
+ def _get_depths(self):
+ """Private function to obtain depths value"""
+ return self.c_region.depths
+
+ def _set_depths(self, value):
+ """Private function to set depths value"""
+ self.c_region.depths = value
+
+ depths = property(fget=_get_depths, fset=_set_depths,
+ doc="Set and obtain number of depths")
+
def _get_nsres(self):
"""Private function to obtain north-south value"""
- return self.c_region.contents.ns_res
+ return self.c_region.ns_res
def _set_nsres(self, value):
"""Private function to obtain north-south value"""
- self.c_region.contents.ns_res = value
+ self.c_region.ns_res = value
self.adjust()
nsres = property(fget=_get_nsres, fset=_set_nsres,
@@ -161,11 +232,11 @@
def _get_ewres(self):
"""Private function to obtain east-west value"""
- return self.c_region.contents.ew_res
+ return self.c_region.ew_res
def _set_ewres(self, value):
"""Private function to set east-west value"""
- self.c_region.contents.ew_res = value
+ self.c_region.ew_res = value
self.adjust()
ewres = property(fget=_get_ewres, fset=_set_ewres,
@@ -173,11 +244,11 @@
def _get_tbres(self):
"""Private function to obtain top-botton 3D value"""
- return self.c_region.contents.tb_res
+ return self.c_region.tb_res
def _set_tbres(self, value):
"""Private function to set top-bottom 3D value"""
- self.c_region.contents.tb_res = value
+ self.c_region.tb_res = value
self.adjust()
tbres = property(fget=_get_tbres, fset=_set_tbres,
@@ -186,22 +257,14 @@
@property
def zone(self):
"""Return the zone of projection
-
- >>> reg = Region()
- >>> reg.zone
- 0
"""
- return self.c_region.contents.zone
+ return self.c_region.zone
@property
def proj(self):
"""Return a code for projection
-
- >>> reg = Region()
- >>> reg.proj
- 99
"""
- return self.c_region.contents.proj
+ return self.c_region.proj
@property
def cells(self):
@@ -210,22 +273,25 @@
#----------MAGIC METHODS----------
def __repr__(self):
- rg = 'Region(north=%g, south=%g, east=%g, west=%g, nsres=%g, ewres=%g)'
+ rg = "Region(north=%g, south=%g, east=%g, west=%g, "\
+ "nsres=%g, ewres=%g, rows=%i, cols=%i, "\
+ "cells=%i, zone=%i, proj=%i)"
return rg % (self.north, self.south, self.east, self.west,
- self.nsres, self.ewres)
+ self.nsres, self.ewres, self.rows, self.cols,
+ self.cells, self.zone, self.proj)
def _repr_html_(self):
return dict2html(dict(self.items()), keys=self.keys(),
border='1', kdec='b')
def __unicode__(self):
- return grass.pipe_command("g.region", flags="pu").communicate()[0]
+ return self.__repr__()
def __str__(self):
return self.__unicode__()
def __eq__(self, reg):
- """Compare two region.
+ """Compare two region. ::
>>> r0 = Region()
>>> r1 = Region()
@@ -235,6 +301,8 @@
True
>>> r1 == r2
False
+
+ ..
"""
attrs = ['north', 'south', 'west', 'east', 'top', 'bottom',
'nsres', 'ewres', 'tbres']
@@ -263,13 +331,7 @@
'cols', 'cells']
def items(self):
- """Return a list of tuple with key and value. ::
-
- >>> reg = Region()
- >>> reg.items() # doctest: +ELLIPSIS
- [(u'proj', 99), ..., (u'cells', 2025000)]
-
- ..
+ """Return a list of tuple with key and value.
"""
return [(k, self.__getattribute__(k)) for k in self.keys()]
@@ -277,79 +339,245 @@
def zoom(self, raster_name):
"""Shrink region until it meets non-NULL data from this raster map
+ Warning: This will change the user GRASS region settings
+
:param raster_name: the name of raster
:type raster_name: str
"""
self._set_param('zoom', str(raster_name))
- self.get_current()
+ self.read()
def align(self, raster_name):
"""Adjust region cells to cleanly align with this raster map
+ Warning: This will change the user GRASS region settings
+
:param raster_name: the name of raster
:type raster_name: str
"""
self._set_param('align', str(raster_name))
- self.get_current()
+ self.read()
def adjust(self, rows=False, cols=False):
"""Adjust rows and cols number according with the nsres and ewres
resolutions. If rows or cols parameters are True, the adjust method
update nsres and ewres according with the rows and cols numbers.
"""
- libgis.G_adjust_Cell_head(self.c_region, bool(rows), bool(cols))
+ libgis.G_adjust_Cell_head(self.byref(), bool(rows), bool(cols))
- def vect(self, vector_name):
+ def from_vect(self, vector_name):
"""Adjust bounding box of region using a vector
- :param vector_name: the name of vector
- :type vector_name: str
+ :param vector_name: the name of vector
+ :type vector_name: str
- ::
+ Example ::
>>> reg = Region()
- >>> reg.vect('census')
+ >>> reg.from_vect(test_vector_name)
>>> reg.get_bbox()
- Bbox(230963.640878, 212125.562878, 645837.437393, 628769.374393)
- >>> reg.get_default()
+ Bbox(6.0, 0.0, 14.0, 0.0)
+ >>> reg.read()
+ >>> reg.get_bbox()
+ Bbox(40.0, 0.0, 40.0, 0.0)
- ..
+ ..
"""
from grass.pygrass.vector import VectorTopo
with VectorTopo(vector_name, mode='r') as vect:
bbox = vect.bbox()
self.set_bbox(bbox)
+ def from_rast(self, raster_name):
+ """Set the region from the computational region
+ of a raster map layer.
+
+ :param raster_name: the name of raster
+ :type raster_name: str
+
+ :param mapset: the mapset of raster
+ :type mapset: str
+
+ call C function `Rast_get_cellhd`
+
+ Example ::
+
+ >>> reg = Region()
+ >>> reg.from_rast(test_raster_name)
+ >>> reg.get_bbox()
+ Bbox(50.0, 0.0, 60.0, 0.0)
+ >>> reg.read()
+ >>> reg.get_bbox()
+ Bbox(40.0, 0.0, 40.0, 0.0)
+
+ ..
+ """
+ if not raster_name:
+ raise ValueError("Raster name or mapset are invalid")
+
+
+ mapset = get_mapset_raster(raster_name)
+
+ if mapset:
+ libraster.Rast_get_cellhd(raster_name, mapset,
+ self.byref())
+
def get_current(self):
- """Set the current GRASS region to the Region object"""
- libgis.G_get_set_window(self.c_region)
+ """Get the current working region of this process
+ and store it into this Region object
+ Previous calls to set_current() affects values returned by this function.
+ Previous calls to read() affects values returned by this function
+ only if the current working region is not initialized.
+
+ Example:
+
+ >>> r = Region()
+ >>> r.north
+ 40.0
+
+ >>> r.north = 30
+ >>> r.north
+ 30.0
+ >>> r.get_current()
+ >>> r.north
+ 40.0
+
+ """
+ libgis.G_get_set_window(self.byref())
+
def set_current(self):
- """Set the Region object to the current GRASS region"""
- libgis.G_set_window(self.c_region)
+ """Set the current working region from this region object
- def get_default(self):
- """Set the default GRASS region to the Region object"""
- libgis.G_get_window(self.c_region)
+ This function adjusts the values before setting the region
+ so you don't have to call G_adjust_Cell_head().
- def set_default(self):
- """Set the Region object to the default GRASS region.
- It works only in PERMANENT mapset"""
- from grass.pygrass.gis import Mapset
- mapset = Mapset()
- if mapset.name != 'PERMANENT':
- raise GrassError("ERROR: Unable to change default region. The " \
- "current mapset is not <PERMANENT>.")
+ Attention: Only the current process is affected.
+ The GRASS computational region is not affected.
+
+ Example::
+
+ >>> r = Region()
+ >>> r.north
+ 40.0
+ >>> r.south
+ 0.0
+
+ >>> r.north = 30
+ >>> r.south = 20
+ >>> r.set_current()
+ >>> r.north
+ 30.0
+ >>> r.south
+ 20.0
+ >>> r.get_current()
+ >>> r.north
+ 30.0
+ >>> r.south
+ 20.0
+
+ >>> r.read(force_read=False)
+ >>> r.north
+ 40.0
+ >>> r.south
+ 0.0
+
+ >>> r.read(force_read=True)
+ >>> r.north
+ 40.0
+ >>> r.south
+ 0.0
+
+ """
+ libgis.G_set_window(self.byref())
+
+ def read(self, force_read=True):
+ """
+ Read the region into this region object
+
+ Reads the region as stored in the WIND file in the user's current
+ mapset into region.
+
+ 3D values are set to defaults if not available in WIND file. An
+ error message is printed and exit() is called if there is a problem
+ reading the region.
+
+ <b>Note:</b> GRASS applications that read or write raster maps
+ should not use this routine since its use implies that the active
+ module region will not be used. Programs that read or write raster
+ map data (or vector data) can query the active module region using
+ Rast_window_rows() and Rast_window_cols().
+
+ :param force_read: If True the WIND file of the current mapset
+ is re-readed, otherwise the initial region
+ set at process start will be loaded from the internal
+ static variables.
+ :type force_read: boolean
+
+ """
+ # Force the reading of the WIND file
+ if force_read:
+ libgis.G_unset_window()
+ libgis.G_get_window(self.byref())
+
+ def write(self):
+ """Writes the region from this region object
+
+ This function writes this region to the Region file (WIND)
+ in the users current mapset. This function should be
+ carefully used, since the user will ot notice if his region
+ was changed and would expect that only g.region will do this.
+
+ Example ::
+
+ >>> from copy import deepcopy
+ >>> r = Region()
+ >>> rn = deepcopy(r)
+ >>> r.north = 20
+ >>> r.south = 10
+
+ >>> r.write()
+ >>> r.read()
+ >>> r.north
+ 20.0
+ >>> r.south
+ 10.0
+
+ >>> rn.write()
+ >>> r.read()
+ >>> r.north
+ 40.0
+ >>> r.south
+ 0.0
+
+ >>> r.read_default()
+ >>> r.write()
+
+ ..
+ """
self.adjust()
- if libgis.G_put_window(self.c_region) < 0:
+ if libgis.G_put_window(self.byref()) < 0:
raise GrassError("Cannot change region (DEFAUL_WIND file).")
+
+ def read_default(self):
+ """
+ Get the default region
+
+ Reads the default region for the location in this Region object.
+ 3D values are set to defaults if not available in WIND file.
+
+ An error message is printed and exit() is called if there is a
+ problem reading the default region.
+ """
+ libgis.G_get_default_window(self.byref())
+
def get_bbox(self):
"""Return a Bbox object with the extension of the region. ::
>>> reg = Region()
>>> reg.get_bbox()
- Bbox(228500.0, 215000.0, 645000.0, 630000.0)
+ Bbox(40.0, 0.0, 40.0, 0.0)
..
"""
@@ -380,3 +608,26 @@
self.south = bbox.south
self.east = bbox.east
self.west = bbox.west
+
+if __name__ == "__main__":
+
+ import doctest
+ from grass.pygrass import utils
+ from grass.script.core import run_command
+
+ utils.create_test_vector_map(test_vector_name)
+ run_command("g.region", n=50, s=0, e=60, w=0, res=1)
+ run_command("r.mapcalc", expression="%s = 1"%(test_raster_name),
+ overwrite=True)
+ run_command("g.region", n=40, s=0, e=40, w=0, res=2)
+
+ doctest.testmod()
+
+ """Remove the generated vector map, if exist"""
+ mset = utils.get_mapset_vector(test_vector_name, mapset='')
+ if mset:
+ run_command("g.remove", flags='f', type='vector', name=test_vector_name)
+ mset = utils.get_mapset_raster(test_raster_name, mapset='')
+ if mset:
+ run_command("g.remove", flags='f', type='raster', name=test_raster_name)
+
Modified: grass/trunk/lib/python/pygrass/gis/testsuite/test_doctests.py
===================================================================
--- grass/trunk/lib/python/pygrass/gis/testsuite/test_doctests.py 2015-08-28 16:13:57 UTC (rev 66055)
+++ grass/trunk/lib/python/pygrass/gis/testsuite/test_doctests.py 2015-08-28 16:22:15 UTC (rev 66056)
@@ -31,11 +31,22 @@
# TODO: ultimate solution is not to use _ as a buildin in lib/python
# for now it is the only place where it works
grass.gunittest.utils.do_doctest_gettext_workaround()
+
+ from grass.pygrass import utils
+ from grass.script.core import run_command
+ utils.create_test_vector_map(gis.test_vector_name)
+ utils.create_test_vector_map(gis.region.test_vector_name)
+ run_command("g.region", n=50, s=0, e=60, w=0, res=1)
+ run_command("r.mapcalc", expression="%s = 1"%(gis.test_raster_name),
+ overwrite=True)
+ run_command("r.mapcalc", expression="%s = 1"%(gis.region.test_raster_name),
+ overwrite=True)
+ run_command("g.region", n=40, s=0, e=40, w=0, res=2)
+
# this should be called at some top level
tests.addTests(doctest.DocTestSuite(gis))
tests.addTests(doctest.DocTestSuite(region))
return tests
-
if __name__ == '__main__':
grass.gunittest.main.test()
Modified: grass/trunk/lib/python/pygrass/raster/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/__init__.py 2015-08-28 16:13:57 UTC (rev 66055)
+++ grass/trunk/lib/python/pygrass/raster/__init__.py 2015-08-28 16:22:15 UTC (rev 66056)
@@ -33,6 +33,7 @@
from grass.pygrass.raster.segment import Segment
from grass.pygrass.raster.rowio import RowIO
+test_raster_name="Raster_test_map"
class RasterRow(RasterAbstractBase):
"""Raster_row_access": Inherits: "Raster_abstract_base" and implements
@@ -51,58 +52,61 @@
object (only for rows), since r.mapcalc is more sophisticated and
faster
- Examples:
+ Examples:
- >>> elev = RasterRow('elevation')
- >>> elev.exist()
- True
- >>> elev.is_open()
- False
- >>> elev.open()
- >>> elev.is_open()
- True
- >>> elev.has_cats()
- False
- >>> elev.mode
- u'r'
- >>> elev.mtype
- 'FCELL'
- >>> elev.num_cats()
- 0
- >>> elev.info.range
- (55.578792572021484, 156.32986450195312)
- >>> elev.info
- elevation@
- rows: 1350
- cols: 1500
- north: 228500.0 south: 215000.0 nsres:10.0
- east: 645000.0 west: 630000.0 ewres:10.0
- range: 55.578792572, 156.329864502
- proj: 99
- <BLANKLINE>
+ >>> elev = RasterRow(test_raster_name)
+ >>> elev.exist()
+ True
+ >>> elev.is_open()
+ False
+ >>> elev.open()
+ >>> elev.is_open()
+ True
+ >>> elev.has_cats()
+ True
+ >>> elev.mode
+ u'r'
+ >>> elev.mtype
+ 'CELL'
+ >>> elev.num_cats()
+ 16
+ >>> elev.info.range
+ (11, 44)
+ >>> elev.info.cols
+ 4
+ >>> elev.info.rows
+ 4
- Each Raster map have an attribute call ``cats`` that allow user
- to interact with the raster categories.
+ >>> elev.hist.read()
+ >>> elev.hist.title = "A test map"
+ >>> elev.hist.write()
+ >>> elev.hist.title
+ 'A test map'
+ >>> elev.hist.keyword
+ 'This is a test map'
- >>> land = RasterRow('geology')
- >>> land.open()
- >>> land.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
- [('Zml', 1, None),
- ...
- ('Tpyw', 1832, None)]
+ Each Raster map have an attribute call ``cats`` that allow user
+ to interact with the raster categories.
- Open a raster map using the *with statement*:
+ >>> elev.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
+ [('A', 11, None),
+ ('B', 12, None),
+ ...
+ ('P', 44, None)]
- >>> with RasterRow('elevation') as elev:
- ... for row in elev[:3]:
- ... row[:4]
- ...
- Buffer([ 141.99613953, 141.27848816, 141.37904358, 142.29821777], dtype=float32)
- Buffer([ 142.90461731, 142.39450073, 142.68611145, 143.59086609], dtype=float32)
- Buffer([ 143.81854248, 143.54707336, 143.83972168, 144.59527588], dtype=float32)
- >>> elev.is_open()
- False
+ Open a raster map using the *with statement*:
+ >>> with RasterRow(test_raster_name) as elev:
+ ... for row in elev:
+ ... row
+ Buffer([11, 21, 31, 41], dtype=int32)
+ Buffer([12, 22, 32, 42], dtype=int32)
+ Buffer([13, 23, 33, 43], dtype=int32)
+ Buffer([14, 24, 34, 44], dtype=int32)
+
+ >>> elev.is_open()
+ False
+
"""
def __init__(self, name, mapset='', *args, **kargs):
super(RasterRow, self).__init__(name, mapset, *args, **kargs)
@@ -111,21 +115,19 @@
@must_be_open
def get_row(self, row, row_buffer=None):
"""Private method that return the row using the read mode
- call the `Rast_get_row` C function.
+ call the `Rast_get_row` C function.
- :param row: the number of row to obtain
- :type row: int
- :param row_buffer: Buffer object instance with the right dim and type
- :type row_buffer: Buffer
+ :param row: the number of row to obtain
+ :type row: int
+ :param row_buffer: Buffer object instance with the right dim and type
+ :type row_buffer: Buffer
- >>> elev = RasterRow('elevation')
- >>> elev.open()
- >>> elev[0] # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
- Buffer([ 141.99613953, 141.27848816, 141.37904358, ..., 58.40825272,
- 58.30711365, 58.18310547], dtype=float32)
- >>> elev.get_row(0) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
- Buffer([ 141.99613953, 141.27848816, 141.37904358, ..., 58.40825272,
- 58.30711365, 58.18310547], dtype=float32)
+ >>> elev = RasterRow(test_raster_name)
+ >>> elev.open()
+ >>> elev[0]
+ Buffer([11, 21, 31, 41], dtype=int32)
+ >>> elev.get_row(0)
+ Buffer([11, 21, 31, 41], dtype=int32)
"""
if row_buffer is None:
@@ -241,6 +243,16 @@
:type row: int
:param row_buffer: Specify the Buffer object that will be instantiate
:type row_buffer: Buffer object
+
+
+ >>> with RasterRowIO(test_raster_name) as elev:
+ ... for row in elev:
+ ... row
+ Buffer([11, 21, 31, 41], dtype=int32)
+ Buffer([12, 22, 32, 42], dtype=int32)
+ Buffer([13, 23, 33, 43], dtype=int32)
+ Buffer([14, 24, 34, 44], dtype=int32)
+
"""
if row_buffer is None:
row_buffer = Buffer((self._cols,), self.mtype)
@@ -329,6 +341,15 @@
:type row: int
:param row_buffer: specify the Buffer object that will be instantiate
:type row_buffer: Buffer object
+
+ >>> with RasterSegment(test_raster_name) as elev:
+ ... for row in elev:
+ ... row
+ Buffer([11, 21, 31, 41], dtype=int32)
+ Buffer([12, 22, 32, 42], dtype=int32)
+ Buffer([13, 23, 33, 43], dtype=int32)
+ Buffer([14, 24, 34, 44], dtype=int32)
+
"""
if row_buffer is None:
row_buffer = Buffer((self._cols), self.mtype)
@@ -351,6 +372,18 @@
:type row: int
:param col: Specify the column number
:type col: int
+
+
+ >>> with RasterSegment(test_raster_name) as elev:
+ ... elev.get(0,0)
+ ... elev.get(1,1)
+ ... elev.get(2,2)
+ ... elev.get(3,3)
+ 11
+ 22
+ 33
+ 44
+
"""
return self.segment.get(row, col)
@@ -485,7 +518,7 @@
"""Return a numpy array from a raster map
:param str rastname: the name of raster map
- :parar str mapser: the name of mapset containig raster map
+ :parar str mapset: the name of mapset containig raster map
"""
with RasterRow(rastname, mapset=mapset, mode='r') as rast:
return np.array(rast)
@@ -508,3 +541,41 @@
for row in array:
newrow[:] = row[:]
new.put_row(newrow)
+
+if __name__ == "__main__":
+
+ import doctest
+ from grass.pygrass import utils
+ from grass.pygrass.modules import Module
+ Module("g.region", n=40, s=0, e=40, w=0, res=10)
+ Module("r.mapcalc", expression="%s = row() + (10 * col())"%(test_raster_name),
+ overwrite=True)
+ Module("r.support", map=test_raster_name,
+ title="A test map",
+ history="Generated by r.mapcalc",
+ description="This is a test map")
+ cats="""11:A
+ 12:B
+ 13:C
+ 14:D
+ 21:E
+ 22:F
+ 23:G
+ 24:H
+ 31:I
+ 32:J
+ 33:K
+ 34:L
+ 41:M
+ 42:n
+ 43:O
+ 44:P"""
+ Module("r.category", rules="-", map=test_raster_name,
+ stdin_=cats, separator=":")
+
+ doctest.testmod()
+
+ """Remove the generated vector map, if exist"""
+ mset = utils.get_mapset_raster(test_raster_name, mapset='')
+ if mset:
+ Module("g.remove", flags='f', type='raster', name=test_raster_name)
Modified: grass/trunk/lib/python/pygrass/raster/abstract.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/abstract.py 2015-08-28 16:13:57 UTC (rev 66055)
+++ grass/trunk/lib/python/pygrass/raster/abstract.py 2015-08-28 16:22:15 UTC (rev 66056)
@@ -31,6 +31,7 @@
from grass.pygrass.raster.category import Category
from grass.pygrass.raster.history import History
+test_raster_name="abstract_test_map"
## Define global variables to not exceed the 80 columns
WARN_OVERWRITE = "Raster map <{0}> already exists and will be overwritten"
@@ -49,16 +50,16 @@
def __init__(self, name, mapset=''):
"""Read the information for a raster map. ::
- >>> info = Info('elevation')
+ >>> info = Info(test_raster_name)
>>> info.read()
- >>> info
- elevation@
- rows: 1350
- cols: 1500
- north: 228500.0 south: 215000.0 nsres:10.0
- east: 645000.0 west: 630000.0 ewres:10.0
- range: 55.578792572, 156.329864502
- proj: 99
+ >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
+ abstract_test_map@
+ rows: 4
+ cols: 4
+ north: 40.0 south: 0.0 nsres:10.0
+ east: 40.0 west: 0.0 ewres:10.0
+ range: 11, 44
+ ...
<BLANKLINE>
"""
@@ -212,13 +213,11 @@
"""The constructor need at least the name of the map
*optional* field is the `mapset`.
- >>> ele = RasterAbstractBase('elevation')
+ >>> ele = RasterAbstractBase(test_raster_name)
>>> ele.name
- u'elevation'
+ u'abstract_test_map'
>>> ele.exist()
True
- >>> ele.mapset
- 'PERMANENT'
..
"""
@@ -355,7 +354,7 @@
call the C function `G_find_raster`.
- >>> ele = RasterAbstractBase('elevation')
+ >>> ele = RasterAbstractBase(test_raster_name)
>>> ele.exist()
True
"""
@@ -371,7 +370,7 @@
def is_open(self):
"""Return True if the map is open False otherwise.
- >>> ele = RasterAbstractBase('elevation')
+ >>> ele = RasterAbstractBase(test_raster_name)
>>> ele.is_open()
False
@@ -400,9 +399,10 @@
def name_mapset(self, name=None, mapset=None):
"""Return the full name of the Raster.
- >>> ele = RasterAbstractBase('elevation')
- >>> ele.name_mapset()
- u'elevation at PERMANENT'
+ >>> ele = RasterAbstractBase(test_raster_name)
+ >>> name = ele.name_mapset().split("@")
+ >>> name
+ [u'abstract_test_map']
"""
if name is None:
@@ -424,11 +424,17 @@
utils.rename(self.name, newname, 'rast')
self._name = newname
- def set_from_rast(self, rastname='', mapset=''):
- """Set the region that will use from a map, if rastername and mapset
- is not specify, use itself.
+ def set_region_from_rast(self, rastname='', mapset=''):
+ """Set the computational region from a map,
+ if rastername and mapset is not specify, use itself.
+ This region will be used by all
+ raster map layers that are opened in the same process.
- call C function `Rast_get_cellhd`"""
+ The GRASS region settings will not be modified.
+
+ call C function `Rast_get_cellhd`, `Rast_set_window`
+
+ """
if self.is_open():
fatal("You cannot change the region if map is open")
raise
@@ -439,7 +445,23 @@
mapset = self.mapset
libraster.Rast_get_cellhd(rastname, mapset,
- ctypes.byref(region._region))
+ region.byref())
+ self._set_raster_window(region)
+
+ def set_region(self, region):
+ """Set the computational region that can be different from the
+ current region settings. This region will be used by all
+ raster map layers that are opened in the same process.
+
+ The GRASS region settings will not be modified.
+ """
+ if self.is_open():
+ fatal("You cannot change the region if map is open")
+ raise
+ self._set_raster_window(region)
+
+ def _set_raster_window(self, region):
+ libraster.Rast_set_window(region.byref())
# update rows and cols attributes
self._rows = libraster.Rast_window_rows()
self._cols = libraster.Rast_window_cols()
@@ -523,3 +545,19 @@
def set_cat(self, label, min_cat, max_cat=None, index=None):
"""Set or update a category"""
self.cats.set_cat(index, (label, min_cat, max_cat))
+
+if __name__ == "__main__":
+
+ import doctest
+ from grass.pygrass import utils
+ from grass.pygrass.modules import Module
+ Module("g.region", n=40, s=0, e=40, w=0, res=10)
+ Module("r.mapcalc", expression="%s = row() + (10 * col())"%(test_raster_name),
+ overwrite=True)
+
+ doctest.testmod()
+
+ """Remove the generated vector map, if exist"""
+ mset = utils.get_mapset_raster(test_raster_name, mapset='')
+ if mset:
+ Module("g.remove", flags='f', type='raster', name=test_raster_name)
Modified: grass/trunk/lib/python/pygrass/raster/history.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/history.py 2015-08-28 16:13:57 UTC (rev 66055)
+++ grass/trunk/lib/python/pygrass/raster/history.py 2015-08-28 16:22:15 UTC (rev 66056)
@@ -11,28 +11,6 @@
class History(object):
"""History class help to manage all the metadata of a raster map
-
- >>> import grass.lib.gis as libgis
- >>> libgis.G_gisinit('')
- >>> hist = History('elevation')
- >>> hist.read()
- >>> hist.creator
- 'helena'
- >>> hist.src1
- ''
- >>> hist.src2
- ''
- >>> hist.keyword
- 'generated by r.proj'
- >>> hist.date
- datetime.datetime(2006, 11, 7, 1, 9, 51)
- >>> hist.mapset
- 'PERMANENT'
- >>> hist.maptype
- 'raster'
- >>> hist.title
- 'elev_ned10m'
-
"""
def __init__(self, name, mapset='', mtype='',
creator='', src1='', src2='', keyword='',
@@ -234,17 +212,9 @@
obtain all the information of map. ::
>>> import grass.lib.gis as libgis
- >>> libgis.G_gisinit('')
>>> import ctypes
>>> import grass.lib.raster as libraster
>>> hist = libraster.History()
- >>> libraster.Rast_read_history(ctypes.c_char_p('elevation'),
- ... ctypes.c_char_p(''),
- ... ctypes.byref(hist))
- 0
- >>> libraster.Rast_get_history(ctypes.byref(hist),
- ... libraster.HIST_MAPID)
- 'Tue Nov 7 01:09:51 2006'
..
"""
More information about the grass-commit
mailing list