[GRASS-SVN] r62386 - in grass/branches/releasebranch_7_0/lib/python/pygrass: . gis modules/grid modules/interface raster vector vector/testsuite
svn_grass at osgeo.org
svn_grass at osgeo.org
Sun Oct 26 10:25:09 PDT 2014
Author: zarch
Date: 2014-10-26 10:25:09 -0700 (Sun, 26 Oct 2014)
New Revision: 62386
Added:
grass/branches/releasebranch_7_0/lib/python/pygrass/utils.py
Removed:
grass/branches/releasebranch_7_0/lib/python/pygrass/functions.py
Modified:
grass/branches/releasebranch_7_0/lib/python/pygrass/Makefile
grass/branches/releasebranch_7_0/lib/python/pygrass/gis/__init__.py
grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/grid.py
grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/patch.py
grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/flag.py
grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py
grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/parameter.py
grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/typedict.py
grass/branches/releasebranch_7_0/lib/python/pygrass/raster/__init__.py
grass/branches/releasebranch_7_0/lib/python/pygrass/raster/abstract.py
grass/branches/releasebranch_7_0/lib/python/pygrass/vector/__init__.py
grass/branches/releasebranch_7_0/lib/python/pygrass/vector/abstract.py
grass/branches/releasebranch_7_0/lib/python/pygrass/vector/geometry.py
grass/branches/releasebranch_7_0/lib/python/pygrass/vector/table.py
grass/branches/releasebranch_7_0/lib/python/pygrass/vector/testsuite/test_vector3d.py
Log:
pygrass: rename functions to utils
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/Makefile
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/Makefile 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/Makefile 2014-10-26 17:25:09 UTC (rev 62386)
@@ -7,7 +7,7 @@
GDIR = $(PYDIR)/grass
DSTDIR = $(GDIR)/pygrass
-MODULES = errors functions orderdict
+MODULES = errors utils orderdict
CLEAN_SUBDIRS = messages modules raster vector gis shell tests
Deleted: grass/branches/releasebranch_7_0/lib/python/pygrass/functions.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/functions.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/functions.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -1,384 +0,0 @@
-# -*- coding: utf-8 -*-
-import itertools
-import fnmatch
-import os
-from sqlite3 import OperationalError
-
-import grass.lib.gis as libgis
-libgis.G_gisinit('')
-import grass.lib.raster as libraster
-from grass.script import core as grasscore
-
-from grass.pygrass.errors import GrassError
-
-
-def looking(obj, filter_string):
- """
- >>> import grass.lib.vector as libvect
- >>> sorted(looking(libvect, '*by_box*')) # doctest: +NORMALIZE_WHITESPACE
- ['Vect_select_areas_by_box', 'Vect_select_isles_by_box',
- 'Vect_select_lines_by_box', 'Vect_select_nodes_by_box']
-
- """
- word_list = dir(obj)
- word_list.sort()
- return fnmatch.filter(word_list, filter_string)
-
-
-def findfiles(dirpath, match=None):
- """Return a list of the files"""
- res = []
- for f in sorted(os.listdir(dirpath)):
- abspath = os.path.join(dirpath, f)
- if os.path.isdir(abspath):
- res.extend(findfiles(abspath, match))
-
- if match:
- if fnmatch.fnmatch(abspath, match):
- res.append(abspath)
- else:
- res.append(abspath)
- return res
-
-
-def findmaps(type, pattern=None, mapset='', location='', gisdbase=''):
- """Return a list of tuple contining the names of the:
-
- * map
- * mapset,
- * location,
- * gisdbase
-
- """
- from grass.pygrass.gis import Gisdbase, Location, Mapset
-
- def find_in_location(type, pattern, location):
- res = []
- for msetname in location.mapsets():
- mset = Mapset(msetname, location.name, location.gisdbase)
- res.extend([(m, mset.name, mset.location, mset.gisdbase)
- for m in mset.glist(type, pattern)])
- return res
-
- def find_in_gisdbase(type, pattern, gisdbase):
- res = []
- for loc in gisdbase.locations():
- res.extend(find_in_location(type, pattern,
- Location(loc, gisdbase.name)))
- return res
-
- if gisdbase and location and mapset:
- mset = Mapset(mapset, location, gisdbase)
- return [(m, mset.name, mset.location, mset.gisdbase)
- for m in mset.glist(type, pattern)]
- elif gisdbase and location:
- loc = Location(location, gisdbase)
- return find_in_location(type, pattern, loc)
- elif gisdbase:
- gis = Gisdbase(gisdbase)
- return find_in_gisdbase(type, pattern, gis)
- elif location:
- loc = Location(location)
- return find_in_location(type, pattern, loc)
- elif mapset:
- mset = Mapset(mapset)
- return [(m, mset.name, mset.location, mset.gisdbase)
- for m in mset.glist(type, pattern)]
- else:
- gis = Gisdbase()
- return find_in_gisdbase(type, pattern, gis)
-
-
-def remove(oldname, maptype):
- """Remove a map"""
- grasscore.run_command('g.remove', quiet=True, flags='f',
- type=maptype, pattern=oldname)
-
-
-def rename(oldname, newname, maptype, **kwargs):
- """Rename a map"""
- kwargs.update({maptype: '{old},{new}'.format(old=oldname, new=newname), })
- grasscore.run_command('g.rename', quiet=True, **kwargs)
-
-
-def copy(existingmap, newmap, maptype, **kwargs):
- """Copy a map
-
- >>> copy('census', 'mycensus', 'vect')
- >>> rename('mycensus', 'mynewcensus', 'vect')
- >>> remove('mynewcensus', 'vect')
-
- """
- kwargs.update({maptype: '{old},{new}'.format(old=existingmap, new=newmap)})
- grasscore.run_command('g.copy', quiet=True, **kwargs)
-
-
-def getenv(env):
- """Return the current grass environment variables
-
- >>> getenv("MAPSET")
- 'user1'
-
- """
- return libgis.G__getenv(env)
-
-
-def get_mapset_raster(mapname, mapset=''):
- """Return the mapset of the raster map
-
- >>> get_mapset_raster('elevation')
- 'PERMANENT'
-
- """
- return libgis.G_find_raster2(mapname, mapset)
-
-
-def get_mapset_vector(mapname, mapset=''):
- """Return the mapset of the vector map
-
- >>> get_mapset_vector('census')
- 'PERMANENT'
-
- """
- return libgis.G_find_vector2(mapname, mapset)
-
-
-def is_clean_name(name):
- """Return if the name is valid
-
- >>> is_clean_name('census')
- True
- >>> is_clean_name('0census')
- True
- >>> is_clean_name('census?')
- False
- >>> is_clean_name('cénsus')
- False
-
- """
- if libgis.G_legal_filename(name) < 0:
- return False
- return True
-
-
-def coor2pixel(coord, region):
- """Convert coordinates into a pixel row and col
-
- >>> reg = Region()
- >>> coor2pixel((reg.west, reg.north), reg)
- (0.0, 0.0)
- >>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
- True
-
- """
- (east, north) = coord
- return (libraster.Rast_northing_to_row(north, region.c_region),
- libraster.Rast_easting_to_col(east, region.c_region))
-
-
-def pixel2coor(pixel, region):
- """Convert row and col of a pixel into a coordinates
-
- >>> reg = Region()
- >>> pixel2coor((0, 0), reg) == (reg.north, reg.west)
- True
- >>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
- True
-
- """
- (col, row) = pixel
- return (libraster.Rast_row_to_northing(row, region.c_region),
- libraster.Rast_col_to_easting(col, region.c_region))
-
-
-def get_raster_for_points(poi_vector, raster, column=None, region=None):
- """Query a raster map for each point feature of a vector
-
- Example
-
- >>> from grass.pygrass.vector import VectorTopo
- >>> from grass.pygrass.raster import RasterRow
- >>> ele = RasterRow('elevation')
- >>> copy('schools','myschools','vect')
- >>> sch = VectorTopo('myschools')
- >>> sch.open(mode='r')
- >>> get_raster_for_points(sch, ele) # doctest: +ELLIPSIS
- [(1, 633649.2856743174, 221412.94434781274, 145.06602)...
- >>> sch.table.columns.add('elevation','double precision')
- >>> 'elevation' in sch.table.columns
- True
- >>> get_raster_for_points(sch, ele, 'elevation')
- True
- >>> sch.table.filters.select('NAMESHORT','elevation')
- Filters(u'SELECT NAMESHORT, elevation FROM myschools;')
- >>> cur = sch.table.execute()
- >>> cur.fetchall() # doctest: +ELLIPSIS
- [(u'SWIFT CREEK', 145.06602), ... (u'9TH GRADE CTR', None)]
- >>> remove('myschools','vect')
-
-
- :param point: point vector object
- :param raster: raster object
- :param str column: column name to update
-
- """
- from math import isnan
- if not column:
- result = []
- if region is None:
- from grass.pygrass.gis.region import Region
- region = Region()
- if not poi_vector.is_open():
- poi_vector.open()
- if not raster.is_open():
- raster.open()
- if poi_vector.num_primitive_of('point') == 0:
- raise GrassError(_("Vector doesn't contain points"))
- for poi in poi_vector.viter('points'):
- val = raster.get_value(poi, region)
- if column:
- if val is not None and not isnan(val):
- poi.attrs[column] = val
- else:
- if val is not None and not isnan(val):
- result.append((poi.id, poi.x, poi.y, val))
- else:
- result.append((poi.id, poi.x, poi.y, None))
- if not column:
- return result
- else:
- poi.attrs.commit()
- return True
-
-
-def r_export(rast, output='', fmt='png', **kargs):
- from grass.pygrass.modules import Module
- if rast.exist():
- output = output if output else "%s_%s.%s" % (rast.name, rast.mapset,
- fmt)
- Module('r.out.%s' % fmt, input=rast.fullname(), output=output,
- overwrite=True, **kargs)
- return output
- else:
- raise ValueError('Raster map does not exist.')
-
-
-def get_lib_path(modname, libname):
- """Return the path of the libname contained in the module.
-
- >>> get_lib_path(modname='r.modis', libname='libmodis')
- """
- from os.path import isdir, join
- from os import getenv
-
- if isdir(join(getenv('GISBASE'), 'etc', modname)):
- path = join(os.getenv('GISBASE'), 'etc', modname)
- elif getenv('GRASS_ADDON_BASE') and \
- isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname)):
- path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
- elif getenv('GRASS_ADDON_BASE') and \
- isdir(join(getenv('GRASS_ADDON_BASE'), modname, modname)):
- path = join(os.getenv('GRASS_ADDON_BASE'), modname, modname)
- elif isdir(join('..', libname)):
- path = join('..', libname)
- else:
- path = None
- return path
-
-
-def split_in_chunk(iterable, lenght=10):
- """Split a list in chunk.
-
- >>> for chunk in split_in_chunk(range(25)): print chunk
- (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
- (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
- (20, 21, 22, 23, 24)
- >>> for chunk in split_in_chunk(range(25), 3): print chunk
- (0, 1, 2)
- (3, 4, 5)
- (6, 7, 8)
- (9, 10, 11)
- (12, 13, 14)
- (15, 16, 17)
- (18, 19, 20)
- (21, 22, 23)
- (24,)
- """
- it = iter(iterable)
- while True:
- chunk = tuple(itertools.islice(it, lenght))
- if not chunk:
- return
- yield chunk
-
-
-def table_exist(cursor, table_name):
- """Return True if the table exist False otherwise"""
- try:
- # sqlite
- cursor.execute("SELECT name FROM sqlite_master"
- " WHERE type='table' AND name='%s';" % table_name)
- except OperationalError:
- try:
- # pg
- cursor.execute("SELECT EXISTS(SELECT * FROM "
- "information_schema.tables "
- "WHERE table_name=%s)" % table_name)
- except OperationalError:
- return False
- one = cursor.fetchone() if cursor else None
- return True if one and one[0] else False
-
-
-def docstring_property(class_doc):
- """Property attribute for docstrings.
- Took from: https://gist.github.com/bfroehle/4041015
-
- >>> class A(object):
- ... '''Main docstring'''
- ... def __init__(self, x):
- ... self.x = x
- ... @docstring_property(__doc__)
- ... def __doc__(self):
- ... return "My value of x is %s." % self.x
-
- >>> A.__doc__
- 'Main docstring'
-
- >>> a = A(10)
- >>> a.__doc__
- 'My value of x is 10.'
- """
- def wrapper(fget):
- return DocstringProperty(class_doc, fget)
- return wrapper
-
-
-class DocstringProperty(object):
- """Property for the `__doc__` attribute.
-
- Different than `property` in the following two ways:
-
- * When the attribute is accessed from the main class, it returns the value
- of `class_doc`, *not* the property itself. This is necessary so Sphinx
- and other documentation tools can access the class docstring.
-
- * Only supports getting the attribute; setting and deleting raise an
- `AttributeError`.
- """
-
- def __init__(self, class_doc, fget):
- self.class_doc = class_doc
- self.fget = fget
-
- def __get__(self, obj, type=None):
- if obj is None:
- return self.class_doc
- else:
- return self.fget(obj)
-
- def __set__(self, obj, value):
- raise AttributeError("can't set attribute")
-
- def __delete__(self, obj):
- raise AttributeError("can't delete attribute")
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/gis/__init__.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/gis/__init__.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/gis/__init__.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -55,7 +55,7 @@
if value and CHECK_IS[type](join(path, value)):
return value
elif value is '':
- from grass.pygrass.functions import getenv
+ from grass.pygrass.utils import getenv
return getenv(type)
else:
raise GrassError("%s <%s> not found" % (type.title(),
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/grid.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/grid.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/grid.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -11,7 +11,7 @@
from grass.pygrass.gis import Mapset, Location
from grass.pygrass.gis.region import Region
from grass.pygrass.modules import Module
-from grass.pygrass.functions import get_mapset_raster, findmaps
+from grass.pygrass.utils import get_mapset_raster, findmaps
from grass.pygrass.modules.grid.split import split_region_tiles
from grass.pygrass.modules.grid.patch import rpatch_map
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/patch.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/patch.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/grid/patch.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -8,7 +8,7 @@
with_statement, print_function, unicode_literals)
from grass.pygrass.gis.region import Region
from grass.pygrass.raster import RasterRow
-from grass.pygrass.functions import coor2pixel
+from grass.pygrass.utils import coor2pixel
def get_start_end_index(bbox_list):
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/flag.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/flag.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/flag.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import (nested_scopes, generators, division, absolute_import,
with_statement, print_function, unicode_literals)
-from grass.pygrass.functions import docstring_property
+from grass.pygrass.utils import docstring_property
from grass.pygrass.modules.interface import read
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/module.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -15,7 +15,7 @@
from grass.exceptions import CalledModuleError
from grass.script.core import Popen, PIPE
from grass.pygrass.errors import GrassError, ParameterError
-from grass.pygrass.functions import docstring_property
+from grass.pygrass.utils import docstring_property
from grass.pygrass.modules.interface.parameter import Parameter
from grass.pygrass.modules.interface.flag import Flag
from grass.pygrass.modules.interface.typedict import TypeDict
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/parameter.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/parameter.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/parameter.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -8,7 +8,7 @@
with_statement, print_function, unicode_literals)
import re
-from grass.pygrass.functions import docstring_property
+from grass.pygrass.utils import docstring_property
from grass.pygrass.modules.interface.read import GETTYPE, element2dict, DOC
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/typedict.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/typedict.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/modules/interface/typedict.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -12,7 +12,7 @@
except ImportError:
from grass.pygrass.orderdict import OrderedDict
-from grass.pygrass.functions import docstring_property
+from grass.pygrass.utils import docstring_property
class TypeDict(OrderedDict):
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/raster/__init__.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/raster/__init__.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/raster/__init__.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -22,7 +22,7 @@
#
from grass.pygrass.errors import OpenError, must_be_open
from grass.pygrass.gis.region import Region
-from grass.pygrass import functions
+from grass.pygrass import utils
#
# import raster classes
@@ -664,7 +664,7 @@
"""
if not region:
region = Region()
- x, y = functions.coor2pixel(point.coords(), region)
+ x, y = utils.coor2pixel(point.coords(), region)
return self[x][y]
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/raster/abstract.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/raster/abstract.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/raster/abstract.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -18,7 +18,7 @@
#
# import pygrass modules
#
-from grass.pygrass import functions
+from grass.pygrass import utils
from grass.pygrass.gis.region import Region
from grass.pygrass.errors import must_be_open
from grass.pygrass.shell.conversion import dict2html
@@ -294,7 +294,7 @@
def _set_name(self, newname):
"""Private method to change the Raster name"""
- if not functions.is_clean_name(newname):
+ if not utils.is_clean_name(newname):
str_err = _("Map name {0} not valid")
raise ValueError(str_err.format(newname))
if self.exist():
@@ -347,7 +347,7 @@
return (self.__getitem__(irow) for irow in range(self._rows))
def _repr_png_(self):
- return raw_figure(functions.r_export(self))
+ return raw_figure(utils.r_export(self))
def exist(self):
"""Return True if the map already exist, and
@@ -361,10 +361,10 @@
"""
if self.name:
if self.mapset == '':
- mapset = functions.get_mapset_raster(self.name, self.mapset)
+ mapset = utils.get_mapset_raster(self.name, self.mapset)
self.mapset = mapset if mapset else ''
return True if mapset else False
- return bool(functions.get_mapset_raster(self.name, self.mapset))
+ return bool(utils.get_mapset_raster(self.name, self.mapset))
else:
return False
@@ -391,7 +391,7 @@
"""Remove the map"""
if self.is_open():
self.close()
- functions.remove(self.name, 'rast')
+ utils.remove(self.name, 'rast')
def fullname(self):
"""Return the full name of a raster map: name at mapset"""
@@ -421,7 +421,7 @@
def rename(self, newname):
"""Rename the map"""
if self.exist():
- functions.rename(self.name, newname, 'rast')
+ utils.rename(self.name, newname, 'rast')
self._name = newname
def set_from_rast(self, rastname='', mapset=''):
@@ -452,7 +452,7 @@
"""
if not region:
region = Region()
- row, col = functions.coor2pixel(point.coords(), region)
+ row, col = utils.coor2pixel(point.coords(), region)
if col < 0 or col > region.cols or row < 0 or row > region.rows:
return None
line = self.get_row(int(row))
Copied: grass/branches/releasebranch_7_0/lib/python/pygrass/utils.py (from rev 62383, grass/trunk/lib/python/pygrass/utils.py)
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/utils.py (rev 0)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/utils.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -0,0 +1,384 @@
+# -*- coding: utf-8 -*-
+import itertools
+import fnmatch
+import os
+from sqlite3 import OperationalError
+
+import grass.lib.gis as libgis
+libgis.G_gisinit('')
+import grass.lib.raster as libraster
+from grass.script import core as grasscore
+
+from grass.pygrass.errors import GrassError
+
+
+def looking(obj, filter_string):
+ """
+ >>> import grass.lib.vector as libvect
+ >>> sorted(looking(libvect, '*by_box*')) # doctest: +NORMALIZE_WHITESPACE
+ ['Vect_select_areas_by_box', 'Vect_select_isles_by_box',
+ 'Vect_select_lines_by_box', 'Vect_select_nodes_by_box']
+
+ """
+ word_list = dir(obj)
+ word_list.sort()
+ return fnmatch.filter(word_list, filter_string)
+
+
+def findfiles(dirpath, match=None):
+ """Return a list of the files"""
+ res = []
+ for f in sorted(os.listdir(dirpath)):
+ abspath = os.path.join(dirpath, f)
+ if os.path.isdir(abspath):
+ res.extend(findfiles(abspath, match))
+
+ if match:
+ if fnmatch.fnmatch(abspath, match):
+ res.append(abspath)
+ else:
+ res.append(abspath)
+ return res
+
+
+def findmaps(type, pattern=None, mapset='', location='', gisdbase=''):
+ """Return a list of tuple contining the names of the:
+
+ * map
+ * mapset,
+ * location,
+ * gisdbase
+
+ """
+ from grass.pygrass.gis import Gisdbase, Location, Mapset
+
+ def find_in_location(type, pattern, location):
+ res = []
+ for msetname in location.mapsets():
+ mset = Mapset(msetname, location.name, location.gisdbase)
+ res.extend([(m, mset.name, mset.location, mset.gisdbase)
+ for m in mset.glist(type, pattern)])
+ return res
+
+ def find_in_gisdbase(type, pattern, gisdbase):
+ res = []
+ for loc in gisdbase.locations():
+ res.extend(find_in_location(type, pattern,
+ Location(loc, gisdbase.name)))
+ return res
+
+ if gisdbase and location and mapset:
+ mset = Mapset(mapset, location, gisdbase)
+ return [(m, mset.name, mset.location, mset.gisdbase)
+ for m in mset.glist(type, pattern)]
+ elif gisdbase and location:
+ loc = Location(location, gisdbase)
+ return find_in_location(type, pattern, loc)
+ elif gisdbase:
+ gis = Gisdbase(gisdbase)
+ return find_in_gisdbase(type, pattern, gis)
+ elif location:
+ loc = Location(location)
+ return find_in_location(type, pattern, loc)
+ elif mapset:
+ mset = Mapset(mapset)
+ return [(m, mset.name, mset.location, mset.gisdbase)
+ for m in mset.glist(type, pattern)]
+ else:
+ gis = Gisdbase()
+ return find_in_gisdbase(type, pattern, gis)
+
+
+def remove(oldname, maptype):
+ """Remove a map"""
+ grasscore.run_command('g.remove', quiet=True, flags='f',
+ type=maptype, pattern=oldname)
+
+
+def rename(oldname, newname, maptype, **kwargs):
+ """Rename a map"""
+ kwargs.update({maptype: '{old},{new}'.format(old=oldname, new=newname), })
+ grasscore.run_command('g.rename', quiet=True, **kwargs)
+
+
+def copy(existingmap, newmap, maptype, **kwargs):
+ """Copy a map
+
+ >>> copy('census', 'mycensus', 'vect')
+ >>> rename('mycensus', 'mynewcensus', 'vect')
+ >>> remove('mynewcensus', 'vect')
+
+ """
+ kwargs.update({maptype: '{old},{new}'.format(old=existingmap, new=newmap)})
+ grasscore.run_command('g.copy', quiet=True, **kwargs)
+
+
+def getenv(env):
+ """Return the current grass environment variables
+
+ >>> getenv("MAPSET")
+ 'user1'
+
+ """
+ return libgis.G__getenv(env)
+
+
+def get_mapset_raster(mapname, mapset=''):
+ """Return the mapset of the raster map
+
+ >>> get_mapset_raster('elevation')
+ 'PERMANENT'
+
+ """
+ return libgis.G_find_raster2(mapname, mapset)
+
+
+def get_mapset_vector(mapname, mapset=''):
+ """Return the mapset of the vector map
+
+ >>> get_mapset_vector('census')
+ 'PERMANENT'
+
+ """
+ return libgis.G_find_vector2(mapname, mapset)
+
+
+def is_clean_name(name):
+ """Return if the name is valid
+
+ >>> is_clean_name('census')
+ True
+ >>> is_clean_name('0census')
+ True
+ >>> is_clean_name('census?')
+ False
+ >>> is_clean_name('cénsus')
+ False
+
+ """
+ if libgis.G_legal_filename(name) < 0:
+ return False
+ return True
+
+
+def coor2pixel(coord, region):
+ """Convert coordinates into a pixel row and col
+
+ >>> reg = Region()
+ >>> coor2pixel((reg.west, reg.north), reg)
+ (0.0, 0.0)
+ >>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
+ True
+
+ """
+ (east, north) = coord
+ return (libraster.Rast_northing_to_row(north, region.c_region),
+ libraster.Rast_easting_to_col(east, region.c_region))
+
+
+def pixel2coor(pixel, region):
+ """Convert row and col of a pixel into a coordinates
+
+ >>> reg = Region()
+ >>> pixel2coor((0, 0), reg) == (reg.north, reg.west)
+ True
+ >>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
+ True
+
+ """
+ (col, row) = pixel
+ return (libraster.Rast_row_to_northing(row, region.c_region),
+ libraster.Rast_col_to_easting(col, region.c_region))
+
+
+def get_raster_for_points(poi_vector, raster, column=None, region=None):
+ """Query a raster map for each point feature of a vector
+
+ Example
+
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> from grass.pygrass.raster import RasterRow
+ >>> ele = RasterRow('elevation')
+ >>> copy('schools','myschools','vect')
+ >>> sch = VectorTopo('myschools')
+ >>> sch.open(mode='r')
+ >>> get_raster_for_points(sch, ele) # doctest: +ELLIPSIS
+ [(1, 633649.2856743174, 221412.94434781274, 145.06602)...
+ >>> sch.table.columns.add('elevation','double precision')
+ >>> 'elevation' in sch.table.columns
+ True
+ >>> get_raster_for_points(sch, ele, 'elevation')
+ True
+ >>> sch.table.filters.select('NAMESHORT','elevation')
+ Filters(u'SELECT NAMESHORT, elevation FROM myschools;')
+ >>> cur = sch.table.execute()
+ >>> cur.fetchall() # doctest: +ELLIPSIS
+ [(u'SWIFT CREEK', 145.06602), ... (u'9TH GRADE CTR', None)]
+ >>> remove('myschools','vect')
+
+
+ :param point: point vector object
+ :param raster: raster object
+ :param str column: column name to update
+
+ """
+ from math import isnan
+ if not column:
+ result = []
+ if region is None:
+ from grass.pygrass.gis.region import Region
+ region = Region()
+ if not poi_vector.is_open():
+ poi_vector.open()
+ if not raster.is_open():
+ raster.open()
+ if poi_vector.num_primitive_of('point') == 0:
+ raise GrassError(_("Vector doesn't contain points"))
+ for poi in poi_vector.viter('points'):
+ val = raster.get_value(poi, region)
+ if column:
+ if val is not None and not isnan(val):
+ poi.attrs[column] = val
+ else:
+ if val is not None and not isnan(val):
+ result.append((poi.id, poi.x, poi.y, val))
+ else:
+ result.append((poi.id, poi.x, poi.y, None))
+ if not column:
+ return result
+ else:
+ poi.attrs.commit()
+ return True
+
+
+def r_export(rast, output='', fmt='png', **kargs):
+ from grass.pygrass.modules import Module
+ if rast.exist():
+ output = output if output else "%s_%s.%s" % (rast.name, rast.mapset,
+ fmt)
+ Module('r.out.%s' % fmt, input=rast.fullname(), output=output,
+ overwrite=True, **kargs)
+ return output
+ else:
+ raise ValueError('Raster map does not exist.')
+
+
+def get_lib_path(modname, libname):
+ """Return the path of the libname contained in the module.
+
+ >>> get_lib_path(modname='r.modis', libname='libmodis')
+ """
+ from os.path import isdir, join
+ from os import getenv
+
+ if isdir(join(getenv('GISBASE'), 'etc', modname)):
+ path = join(os.getenv('GISBASE'), 'etc', modname)
+ elif getenv('GRASS_ADDON_BASE') and \
+ isdir(join(getenv('GRASS_ADDON_BASE'), 'etc', modname)):
+ path = join(getenv('GRASS_ADDON_BASE'), 'etc', modname)
+ elif getenv('GRASS_ADDON_BASE') and \
+ isdir(join(getenv('GRASS_ADDON_BASE'), modname, modname)):
+ path = join(os.getenv('GRASS_ADDON_BASE'), modname, modname)
+ elif isdir(join('..', libname)):
+ path = join('..', libname)
+ else:
+ path = None
+ return path
+
+
+def split_in_chunk(iterable, lenght=10):
+ """Split a list in chunk.
+
+ >>> for chunk in split_in_chunk(range(25)): print chunk
+ (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+ (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
+ (20, 21, 22, 23, 24)
+ >>> for chunk in split_in_chunk(range(25), 3): print chunk
+ (0, 1, 2)
+ (3, 4, 5)
+ (6, 7, 8)
+ (9, 10, 11)
+ (12, 13, 14)
+ (15, 16, 17)
+ (18, 19, 20)
+ (21, 22, 23)
+ (24,)
+ """
+ it = iter(iterable)
+ while True:
+ chunk = tuple(itertools.islice(it, lenght))
+ if not chunk:
+ return
+ yield chunk
+
+
+def table_exist(cursor, table_name):
+ """Return True if the table exist False otherwise"""
+ try:
+ # sqlite
+ cursor.execute("SELECT name FROM sqlite_master"
+ " WHERE type='table' AND name='%s';" % table_name)
+ except OperationalError:
+ try:
+ # pg
+ cursor.execute("SELECT EXISTS(SELECT * FROM "
+ "information_schema.tables "
+ "WHERE table_name=%s)" % table_name)
+ except OperationalError:
+ return False
+ one = cursor.fetchone() if cursor else None
+ return True if one and one[0] else False
+
+
+def docstring_property(class_doc):
+ """Property attribute for docstrings.
+ Took from: https://gist.github.com/bfroehle/4041015
+
+ >>> class A(object):
+ ... '''Main docstring'''
+ ... def __init__(self, x):
+ ... self.x = x
+ ... @docstring_property(__doc__)
+ ... def __doc__(self):
+ ... return "My value of x is %s." % self.x
+
+ >>> A.__doc__
+ 'Main docstring'
+
+ >>> a = A(10)
+ >>> a.__doc__
+ 'My value of x is 10.'
+ """
+ def wrapper(fget):
+ return DocstringProperty(class_doc, fget)
+ return wrapper
+
+
+class DocstringProperty(object):
+ """Property for the `__doc__` attribute.
+
+ Different than `property` in the following two ways:
+
+ * When the attribute is accessed from the main class, it returns the value
+ of `class_doc`, *not* the property itself. This is necessary so Sphinx
+ and other documentation tools can access the class docstring.
+
+ * Only supports getting the attribute; setting and deleting raise an
+ `AttributeError`.
+ """
+
+ def __init__(self, class_doc, fget):
+ self.class_doc = class_doc
+ self.fget = fget
+
+ def __get__(self, obj, type=None):
+ if obj is None:
+ return self.class_doc
+ else:
+ return self.fget(obj)
+
+ def __set__(self, obj, value):
+ raise AttributeError("can't set attribute")
+
+ def __delete__(self, obj):
+ raise AttributeError("can't delete attribute")
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/vector/__init__.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/vector/__init__.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/vector/__init__.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -212,7 +212,7 @@
False
>>> cens.close()
- >>> from grass.pygrass.functions import copy, remove
+ >>> from grass.pygrass.utils import copy, remove
>>> copy('census','mycensus','vect')
>>> from grass.pygrass.modules.shortcuts import vector as v
>>> v.colors(map='mycensus', color='population', column='TOTAL_POP')
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/vector/abstract.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/vector/abstract.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/vector/abstract.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -9,7 +9,7 @@
import grass.lib.vector as libvect
from grass.pygrass.vector.vector_type import MAPTYPE
-from grass.pygrass import functions
+from grass.pygrass import utils
from grass.pygrass.errors import GrassError, OpenError, must_be_open
from grass.pygrass.vector.table import DBlinks, Link
from grass.pygrass.vector.find import PointFinder, BboxFinder, PolygonFinder
@@ -104,7 +104,7 @@
def _set_name(self, newname):
"""Private method to change the Vector name"""
- if not functions.is_clean_name(newname):
+ if not utils.is_clean_name(newname):
str_err = _("Map name {0} not valid")
raise ValueError(str_err.format(newname))
if self.exist():
@@ -268,7 +268,7 @@
"""
if self.exist():
if not self.is_open():
- functions.rename(self.name, newname, 'vect')
+ utils.rename(self.name, newname, 'vect')
else:
raise GrassError("The map is open, not able to renamed it.")
self._name = newname
@@ -281,10 +281,10 @@
"""Return if the Vector exists or not"""
if self.name:
if self.mapset == '':
- mapset = functions.get_mapset_vector(self.name, self.mapset)
+ mapset = utils.get_mapset_vector(self.name, self.mapset)
self.mapset = mapset if mapset else ''
return True if mapset else False
- return bool(functions.get_mapset_vector(self.name, self.mapset))
+ return bool(utils.get_mapset_vector(self.name, self.mapset))
else:
return False
@@ -388,7 +388,7 @@
self.layer = self.dblinks.by_layer(layer).layer
self.table = self.dblinks.by_layer(layer).table()
self.n_lines = self.table.n_rows()
- self.writable = self.mapset == functions.getenv("MAPSET")
+ self.writable = self.mapset == utils.getenv("MAPSET")
self.find = {'by_point': PointFinder(self.c_mapinfo, self.table,
self.writable),
'by_box': BboxFinder(self.c_mapinfo, self.table,
@@ -417,7 +417,7 @@
"""Remove vector map"""
if self.is_open():
self.close()
- functions.remove(self.name, 'vect')
+ utils.remove(self.name, 'vect')
def build(self):
"""Close the vector map and build vector Topology"""
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/vector/geometry.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/vector/geometry.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/vector/geometry.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -176,7 +176,7 @@
"""Set value of a given column of a table attribute.
>>> from grass.pygrass.vector import VectorTopo
- >>> from grass.pygrass.functions import copy, remove
+ >>> from grass.pygrass.utils import copy, remove
>>> copy('schools', 'myschools', 'vect')
>>> schools = VectorTopo('myschools')
>>> schools.open('r')
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/vector/table.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/vector/table.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/vector/table.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -25,7 +25,7 @@
import grass.lib.vector as libvect
from grass.pygrass.gis import Mapset
from grass.pygrass.errors import DBError
-from grass.pygrass.functions import table_exist
+from grass.pygrass.utils import table_exist
from grass.script.db import db_table_in_vector
from grass.script.core import warning
@@ -382,7 +382,7 @@
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
+ >>> from grass.pygrass.utils import copy, remove
>>> copy('census','mycensus','vect')
>>> cols_sqlite = Columns('mycensus',
... sqlite3.connect(get_path(path)))
@@ -441,7 +441,7 @@
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
+ >>> from grass.pygrass.utils import copy, remove
>>> copy('census','mycensus','vect')
>>> cols_sqlite = Columns('mycensus',
... sqlite3.connect(get_path(path)))
@@ -495,7 +495,7 @@
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
+ >>> from grass.pygrass.utils import copy, remove
>>> copy('census','mycensus','vect')
>>> cols_sqlite = Columns('mycensus',
... sqlite3.connect(get_path(path)))
@@ -536,7 +536,7 @@
>>> import sqlite3
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
+ >>> from grass.pygrass.utils import copy, remove
>>> copy('census','mycensus','vect')
>>> cols_sqlite = Columns('mycensus',
... sqlite3.connect(get_path(path)))
Modified: grass/branches/releasebranch_7_0/lib/python/pygrass/vector/testsuite/test_vector3d.py
===================================================================
--- grass/branches/releasebranch_7_0/lib/python/pygrass/vector/testsuite/test_vector3d.py 2014-10-26 17:18:34 UTC (rev 62385)
+++ grass/branches/releasebranch_7_0/lib/python/pygrass/vector/testsuite/test_vector3d.py 2014-10-26 17:25:09 UTC (rev 62386)
@@ -13,7 +13,7 @@
from grass.pygrass.vector import VectorTopo
from grass.pygrass.vector.geometry import Point
from grass.pygrass.gis.region import Region
-from grass.pygrass.functions import get_mapset_vector
+from grass.pygrass.utils import get_mapset_vector
def generate_coordinates(number, bbox=None, with_z=False):
More information about the grass-commit
mailing list