[GRASS-SVN] r60581 - in grass/trunk/lib/python/pygrass: docs messages modules/grid vector
svn_grass at osgeo.org
svn_grass at osgeo.org
Thu May 29 03:15:35 PDT 2014
Author: lucadelu
Date: 2014-05-29 03:15:35 -0700 (Thu, 29 May 2014)
New Revision: 60581
Added:
grass/trunk/lib/python/pygrass/docs/gridmodules.rst
grass/trunk/lib/python/pygrass/docs/messages.rst
grass/trunk/lib/python/pygrass/docs/vector_database.rst
Modified:
grass/trunk/lib/python/pygrass/docs/index.rst
grass/trunk/lib/python/pygrass/messages/__init__.py
grass/trunk/lib/python/pygrass/modules/grid/grid.py
grass/trunk/lib/python/pygrass/modules/grid/patch.py
grass/trunk/lib/python/pygrass/modules/grid/split.py
grass/trunk/lib/python/pygrass/vector/find.py
grass/trunk/lib/python/pygrass/vector/sql.py
grass/trunk/lib/python/pygrass/vector/table.py
Log:
pygrass doc: add gridmodule, vector database and messages documentation
Added: grass/trunk/lib/python/pygrass/docs/gridmodules.rst
===================================================================
--- grass/trunk/lib/python/pygrass/docs/gridmodules.rst (rev 0)
+++ grass/trunk/lib/python/pygrass/docs/gridmodules.rst 2014-05-29 10:15:35 UTC (rev 60581)
@@ -0,0 +1,24 @@
+GridModule
+============
+
+GridModule class permit to work with raster data and all the processors
+of your computer. It divides the input data into the number of choosen rows and
+columns and after it patches the results together to obtain only one output map.
+
+.. automodule:: pygrass.modules.grid.grid
+ :members:
+
+Functions
+------------
+
+Split
+^^^^^^^^
+
+.. automodule:: pygrass.modules.grid.split
+ :members:
+
+Patch
+^^^^^^^^
+
+.. automodule:: pygrass.modules.grid.patch
+ :members:
Modified: grass/trunk/lib/python/pygrass/docs/index.rst
===================================================================
--- grass/trunk/lib/python/pygrass/docs/index.rst 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/docs/index.rst 2014-05-29 10:15:35 UTC (rev 60581)
@@ -21,7 +21,9 @@
raster
vector
attributes
+ vector_database
modules
+ gridmodules
messages
Added: grass/trunk/lib/python/pygrass/docs/messages.rst
===================================================================
--- grass/trunk/lib/python/pygrass/docs/messages.rst (rev 0)
+++ grass/trunk/lib/python/pygrass/docs/messages.rst 2014-05-29 10:15:35 UTC (rev 60581)
@@ -0,0 +1,15 @@
+Messages
+==========
+
+The PyGRASS message interface is a fast and exit-safe
+interface to GRASS C-library message functions.
+
+.. autoclass:: pygrass.messages.Messenger
+ :members:
+
+.. autoclass:: pygrass.messages.FatalError
+ :members:
+
+.. autofunction:: pygrass.messages.message_server
+
+.. autofunction:: pygrass.messages.get_msgr
Added: grass/trunk/lib/python/pygrass/docs/vector_database.rst
===================================================================
--- grass/trunk/lib/python/pygrass/docs/vector_database.rst (rev 0)
+++ grass/trunk/lib/python/pygrass/docs/vector_database.rst 2014-05-29 10:15:35 UTC (rev 60581)
@@ -0,0 +1,38 @@
+Vector Databases
+=================
+
+DBlinks
+---------
+
+.. autoclass:: pygrass.vector.table.DBlinks
+ :members:
+
+Link
+---------
+
+.. autoclass:: pygrass.vector.table.Link
+ :members:
+
+Table
+---------
+
+.. autoclass:: pygrass.vector.table.Table
+ :members:
+
+Columns
+---------
+
+.. autoclass:: pygrass.vector.table.Columns
+ :members:
+
+Filters
+---------
+
+.. autoclass:: pygrass.vector.table.Filters
+ :members:
+
+SQL
+---------
+
+.. automodule:: pygrass.vector.sql
+ :members:
Modified: grass/trunk/lib/python/pygrass/messages/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/messages/__init__.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/messages/__init__.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-"""!@package grass.pygrass.massages
+"""@package grass.pygrass.massages
@brief PyGRASS message interface
@@ -19,7 +19,7 @@
class FatalError(Exception):
- """!This error will be raised in case raise_on_error was set True
+ """This error will be raised in case raise_on_error was set True
when creating the messenger object.
"""
def __init__(self, msg):
@@ -30,12 +30,13 @@
def message_server(lock, conn):
- """!The GRASS message server function designed to be a target for
+ """The GRASS message server function designed to be a target for
multiprocessing.Process
- @param lock A multiprocessing.Lock
- @param conn A multiprocessing.Pipe
+ :param lock: A multiprocessing.Lock
+ :param conn: A multiprocessing.Pipe
+
This function will use the G_* message C-functions from grass.lib.gis
to provide an interface to the GRASS C-library messaging system.
@@ -59,9 +60,11 @@
testing purpose
The that is end through the pipe must be a list of values:
+
- Messages: ["INFO|VERBOSE|WARNING|ERROR|FATAL", "MESSAGE"]
- - Debug: ["DEBUG", level, "MESSAGE"]
- - Percent: ["PERCENT", n, d, s]
+ - Debug: ["DEBUG", level, "MESSAGE"]
+ - Percent: ["PERCENT", n, d, s]
+
"""
libgis.G_debug(1, "Start messenger server")
@@ -110,7 +113,7 @@
class Messenger(object):
- """!Fast and exit-safe interface to GRASS C-library message functions
+ """Fast and exit-safe interface to GRASS C-library message functions
This class implements a fast and exit-safe interface to the GRASS
C-library message functions like: G_message(), G_warning(),
@@ -128,7 +131,6 @@
Usage:
- @code
>>> msgr = Messenger()
>>> msgr.debug(0, "debug 0")
>>> msgr.verbose("verbose message")
@@ -137,7 +139,6 @@
>>> msgr.percent(1, 1, 1)
>>> msgr.warning("Ohh")
>>> msgr.error("Ohh no")
-
D0/0: debug 0
message
important message
@@ -175,7 +176,6 @@
raise FatalError(message)
FatalError: Ohh no no no!
- @endcode
"""
def __init__(self, raise_on_error=False):
self.client_conn = None
@@ -188,6 +188,8 @@
self.stop()
def start_server(self):
+ """Start the messenger server and open the pipe
+ """
self.client_conn, self.server_conn = Pipe()
self.lock = Lock()
self.server = Process(target=message_server, args=(self.lock,
@@ -196,7 +198,7 @@
self.server.start()
def _check_restart_server(self):
- """!Restart the server if it was terminated
+ """Restart the server if it was terminated
"""
if self.server.is_alive() is True:
return
@@ -206,40 +208,55 @@
self.warning("Needed to restart the messenger server")
def message(self, message):
- """!Send a message to stderr
+ """Send a message to stderr
+ :param message: the text of message
+ :type message: str
+
G_message() will be called in the messenger server process
"""
self._check_restart_server()
self.client_conn.send(["INFO", message])
def verbose(self, message):
- """!Send a verbose message to stderr
+ """Send a verbose message to stderr
+ :param message: the text of message
+ :type message: str
+
G_verbose_message() will be called in the messenger server process
"""
self._check_restart_server()
self.client_conn.send(["VERBOSE", message])
def important(self, message):
- """!Send an important message to stderr
+ """Send an important message to stderr
+ :param message: the text of message
+ :type message: str
+
G_important_message() will be called in the messenger server process
"""
self._check_restart_server()
self.client_conn.send(["IMPORTANT", message])
def warning(self, message):
- """!Send a warning message to stderr
+ """Send a warning message to stderr
+ :param message: the text of message
+ :type message: str
+
G_warning() will be called in the messenger server process
"""
self._check_restart_server()
self.client_conn.send(["WARNING", message])
def error(self, message):
- """!Send an error message to stderr
+ """Send an error message to stderr
+ :param message: the text of message
+ :type message: str
+
G_important_message() with an additional "ERROR:" string at
the start will be called in the messenger server process
"""
@@ -247,8 +264,11 @@
self.client_conn.send(["ERROR", message])
def fatal(self, message):
- """!Send an error message to stderr, call sys.exit(1) or raise FatalError
+ """Send an error message to stderr, call sys.exit(1) or raise FatalError
+ :param message: the text of message
+ :type message: str
+
This function emulates the behavior of G_fatal_error(). It prints
an error message to stderr and calls sys.exit(1). If raise_on_error
is set True while creating the messenger object, a FatalError
@@ -264,23 +284,30 @@
sys.exit(1)
def debug(self, level, message):
- """!Send a debug message to stderr
+ """Send a debug message to stderr
+ :param message: the text of message
+ :type message: str
+
G_debug() will be called in the messenger server process
"""
self._check_restart_server()
self.client_conn.send(["DEBUG", level, message])
def percent(self, n, d, s):
- """!Send a percentage to stderr
+ """Send a percentage to stderr
+ :param message: the text of message
+ :type message: str
+
+
G_percent() will be called in the messenger server process
"""
self._check_restart_server()
self.client_conn.send(["PERCENT", n, d, s])
def stop(self):
- """!Stop the messenger server and close the pipe
+ """Stop the messenger server and close the pipe
"""
if self.server is not None and self.server.is_alive():
self.client_conn.send(["STOP", ])
@@ -290,26 +317,30 @@
self.client_conn.close()
def set_raise_on_error(self, raise_on_error=True):
- """!Set the fatal error behavior
+ """Set the fatal error behavior
- - If raise_on_error == True, a FatalError exception will be raised if fatal() is called
- - If raise_on_error == False, sys.exit(1) will be invoked if fatal() is called
+ :param raise_on_error: if True a FatalError exception will be
+ raised instead of calling sys.exit(1)
+ :type raise_on_error: bool
- @param raise_on_error If True a FatalError exception will be raised instead
- of calling sys.exit(1)
+ - If raise_on_error == True, a FatalError exception will be raised
+ if fatal() is called
+ - If raise_on_error == False, sys.exit(1) will be invoked if
+ fatal() is called
+
"""
self.raise_on_error = raise_on_error
def get_raise_on_error(self):
- """!Get the fatal error behavior
+ """Get the fatal error behavior
- @return True if a FatalError exception will be raised
- or False if sys.exit(1) will be called in case of invoking fatal()
+ :returns: True if a FatalError exception will be raised or False if
+ sys.exit(1) will be called in case of invoking fatal()
"""
return self.raise_on_error
def test_fatal_error(self, message):
- """!Force the messenger server to call G_fatal_error()
+ """Force the messenger server to call G_fatal_error()
"""
import time
self._check_restart_server()
@@ -318,18 +349,17 @@
def get_msgr(_instance=[None, ], *args, **kwargs):
- """!Return a Messenger instance.
+ """Return a Messenger instance.
- @return the Messenger instance.
- @code ::
+ :returns: the Messenger instance.
- >>> msgr0 = get_msgr()
- >>> msgr1 = get_msgr()
- >>> msgr2 = Messenger()
- >>> msgr0 is msgr1
- True
- >>> msgr0 is msgr2
- False
+ >>> msgr0 = get_msgr()
+ >>> msgr1 = get_msgr()
+ >>> msgr2 = Messenger()
+ >>> msgr0 is msgr1
+ True
+ >>> msgr0 is msgr2
+ False
"""
if not _instance[0]:
_instance[0] = Messenger(*args, **kwargs)
Modified: grass/trunk/lib/python/pygrass/modules/grid/grid.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/grid.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/modules/grid/grid.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -25,36 +25,21 @@
def select(parms, ptype):
"""Select only a certain type of parameters.
- Parameters
- ----------
+ :param parms: a DictType parameter with inputs or outputs of a Module class
+ :type parms: DictType parameters
+ :param ptype: String define the type of parameter that we want to select,
+ valid ptype are: 'raster', 'vector', 'group'
+ :type ptype: str
+ :returns: An iterator with the value of the parameter.
- params : DictType parameters
- A DictType parameter with inputs or outputs of a Module class.
- ptype : string
- String define the type of parameter that we want to select,
- valid ptype are: 'raster', 'vector', 'group'
-
-
- Returns
- -------
-
- An iterator with the value of the parameter.
-
-
- Examples
- --------
-
- ::
-
- >>> slp = Module('r.slope.aspect',
- ... elevation='ele', slope='slp', aspect='asp',
- ... run_=False)
- >>> for rast in select(slp.outputs, 'raster'):
- ... print rast
- ...
- slp
- asp
-
+ >>> slp = Module('r.slope.aspect',
+ ... elevation='ele', slope='slp', aspect='asp',
+ ... run_=False)
+ >>> for rast in select(slp.outputs, 'raster'):
+ ... print rast
+ ...
+ slp
+ asp
"""
for k in parms:
par = parms[k]
@@ -68,7 +53,13 @@
def copy_special_mapset_files(path_src, path_dst):
"""Copy all the special GRASS files that are contained in
- a mapset to another mapset."""
+ a mapset to another mapset
+
+ :param path_src: the path to the original mapset
+ :type path_src: str
+ :param path_dst: the path to the new mapset
+ :type path_dst: str
+ """
for fil in (fi for fi in os.listdir(path_src) if fi.isupper()):
sht.copy(os.path.join(path_src, fil), path_dst)
@@ -76,43 +67,30 @@
def copy_mapset(mapset, path):
"""Copy mapset to another place without copying raster and vector data.
- Parameters
- ----------
+ :param mapset: a Mapset instance to copy
+ :type mapset: Mapset object
+ :param path: path where the new mapset must be copied
+ :type path: str
+ :returns: the instance of the new Mapset.
- mapset : mapset_like
- A Mapset instance.
- path : string
- Path where the new mapset must be copied.
+ >>> mset = Mapset()
+ >>> mset.name
+ 'user1'
+ >>> import tempfile as tmp
+ >>> import os
+ >>> path = os.path.join(tmp.gettempdir(), 'my_loc', 'my_mset')
+ >>> copy_mapset(mset, path)
+ Mapset('user1')
+ >>> sorted(os.listdir(path))
+ [u'PERMANENT', u'user1']
+ >>> sorted(os.listdir(os.path.join(path, 'PERMANENT')))
+ [u'DEFAULT_WIND', u'PROJ_INFO', u'PROJ_UNITS', u'VAR', u'WIND']
+ >>> sorted(os.listdir(os.path.join(path, 'user1')))
+ [u'CURGROUP', u'SEARCH_PATH', u'VAR', u'WIND']
+ >>> import shutil
+ >>> shutil.rmtree(path)
- Returns
- -------
-
- The instance of the new Mapset.
-
-
- Examples
- --------
-
- ::
-
- >>> mset = Mapset()
- >>> mset.name
- 'user1'
- >>> import tempfile as tmp
- >>> import os
- >>> path = os.path.join(tmp.gettempdir(), 'my_loc', 'my_mset')
- >>> copy_mapset(mset, path)
- Mapset('user1')
- >>> sorted(os.listdir(path))
- [u'PERMANENT', u'user1']
- >>> sorted(os.listdir(os.path.join(path, 'PERMANENT')))
- [u'DEFAULT_WIND', u'PROJ_INFO', u'PROJ_UNITS', u'VAR', u'WIND']
- >>> sorted(os.listdir(os.path.join(path, 'user1')))
- [u'CURGROUP', u'SEARCH_PATH', u'VAR', u'WIND']
- >>> import shutil
- >>> shutil.rmtree(path)
-
"""
per_old = os.path.join(mapset.gisdbase, mapset.location, 'PERMANENT')
per_new = os.path.join(path, 'PERMANENT')
@@ -132,14 +110,13 @@
"""Read a GISRC file and return a tuple with the mapset, location
and gisdbase.
- Examples
- --------
+ :param gisrc: the path to GISRC file
+ :type gisrc: str
+ :returns: a tuple with the mapset, location and gisdbase
- ::
-
- >>> import os
- >>> read_gisrc(os.environ['GISRC']) # doctest: +ELLIPSIS
- (u'user1', ...)
+ >>> import os
+ >>> read_gisrc(os.environ['GISRC']) # doctest: +ELLIPSIS
+ (u'user1', ...)
"""
with open(gisrc, 'r') as gfile:
gis = dict([(k.strip(), v.strip())
@@ -150,19 +127,12 @@
def get_mapset(gisrc_src, gisrc_dst):
"""Get mapset from a GISRC source to a GISRC destination.
- Parameters
- ----------
+ :param gisrc_src: path to the GISRC source
+ :type gisrc_src: str
+ :param gisrc_dst: path to the GISRC destination
+ :type gisrc_dst: str
+ :returns: a tuple with Mapset(src), Mapset(dst)
- gisrc_src : path to the GISRC source
-
- gisrc_dst : path to the GISRC destination
-
-
- Returns
- -------
-
- A tuple with Mapset(src), Mapset(dst)
-
"""
msrc, lsrc, gsrc = read_gisrc(gisrc_src)
mdst, ldst, gdst = read_gisrc(gisrc_dst)
@@ -180,28 +150,21 @@
def copy_groups(groups, gisrc_src, gisrc_dst, region=None):
- """Copy group from one mapset to another, crop the raster to the region.
+ """Copy group from one mapset to another, crop the raster to the region
- Parameters
- ----------
+ :param groups: a list of strings with the group that must be copied
+ from a master to another.
+ :type groups: list of strings
+ :param gisrc_src: path of the GISRC file from where we want to copy the groups
+ :type gisrc_src: str
+ :param gisrc_dst: path of the GISRC file where the groups will be created
+ :type gisrc_dst: str
+ :param region: a region like object or a dictionary with the region
+ parameters that will be used to crop the rasters of the
+ groups
+ :type region: Region object or dictionary
+ :returns: None
- groups : list of strings
- A list of strings with the group that must be copied
- from a master to another.
- gisrc_src : path to the GISRC source
- Path of the GISRC file from where we want to copy the groups.
- gisrc_dst : path to the GISRC destination
- Path of the GISRC file where the groups will be created.
- region : region_like or dictionary
- A region like object or a dictionary with the region parameters that
- will be used to crop the rasters of the groups.
-
-
- Returns
- -------
-
- None.
-
"""
env = os.environ.copy()
# instantiate modules
@@ -233,24 +196,17 @@
def set_region(region, gisrc_src, gisrc_dst, env):
"""Set a region into two different mapsets.
- Parameters
- ----------
-
- region : region_like or dictionary
- A region like object or a dictionary with the region parameters that
- will be used to crop the rasters.
- gisrc_src : path to the GISRC source
- Path of the GISRC file from where we want to copy the rasters.
- gisrc_dst : path to the GISRC destination
- Path of the GISRC file where the rasters will be created.
- region : dictionary
- A dictionary with the variable environment to use.
-
-
- Returns
- -------
-
- None.
+ :param region: a region like object or a dictionary with the region
+ parameters that will be used to crop the rasters of the
+ groups
+ :type region: Region object or dictionary
+ :param gisrc_src: path of the GISRC file from where we want to copy the groups
+ :type gisrc_src: str
+ :param gisrc_dst: path of the GISRC file where the groups will be created
+ :type gisrc_dst: str
+ :param env:
+ :type env:
+ :returns: None
"""
reg_str = "g.region n=%(north)r s=%(south)r " \
"e=%(east)r w=%(west)r " \
@@ -265,25 +221,18 @@
def copy_rasters(rasters, gisrc_src, gisrc_dst, region=None):
"""Copy rasters from one mapset to another, crop the raster to the region.
- Parameters
- ----------
-
- rasters : list of strings
- A list of strings with the raster map that must be copied
- from a master to another.
- gisrc_src : path to the GISRC source
- Path of the GISRC file from where we want to copy the rasters.
- gisrc_dst : path to the GISRC destination
- Path of the GISRC file where the rasters will be created.
- region : region_like or dictionary
- A region like object or a dictionary with the region parameters that
- will be used to crop the rasters.
-
-
- Returns
- -------
-
- None.
+ :param rasters: a list of strings with the raster map that must be copied
+ from a master to another.
+ :type rasters: list
+ :param gisrc_src: path of the GISRC file from where we want to copy the groups
+ :type gisrc_src: str
+ :param gisrc_dst: path of the GISRC file where the groups will be created
+ :type gisrc_dst: str
+ :param region: a region like object or a dictionary with the region
+ parameters that will be used to crop the rasters of the
+ groups
+ :type region: Region object or dictionary
+ :returns: None
"""
env = os.environ.copy()
if region:
@@ -316,21 +265,14 @@
def copy_vectors(vectors, gisrc_src, gisrc_dst):
"""Copy vectors from one mapset to another, crop the raster to the region.
- Parameters
- ----------
-
- vectors : list of strings
- A list of strings with the raster map that must be copied
- from a master to another.
- gisrc_src : path to the GISRC source
- Path of the GISRC file from where we want to copy the vectors.
- gisrc_dst : path to the GISRC destination
- Path of the GISRC file where the vectors will be created.
-
- Returns
- -------
-
- None.
+ :param vectors: a list of strings with the vector map that must be copied
+ from a master to another.
+ :type vectors: list
+ :param gisrc_src: path of the GISRC file from where we want to copy the groups
+ :type gisrc_src: str
+ :param gisrc_dst: path of the GISRC file where the groups will be created
+ :type gisrc_dst: str
+ :returns: None
"""
env = os.environ.copy()
path_dst = os.path.join(*read_gisrc(gisrc_dst))
@@ -359,23 +301,14 @@
pickle a Module class and cnvert into a string that can be used with
`Popen(get_cmd(cmdd), shell=True)`.
- Parameters
- ----------
+ :param cmdd: a module dictionary with all the parameters
+ :type cmdd: dict
- cmdd : dict
- A module dictionary with all the parameters.
-
- Examples
- --------
-
- ::
-
- >>> slp = Module('r.slope.aspect',
- ... elevation='ele', slope='slp', aspect='asp',
- ... overwrite=True, run_=False)
- >>> get_cmd(slp.get_dict()) # doctest: +ELLIPSIS
- ['r.slope.aspect', 'elevation=ele', 'format=degrees', ..., '--o']
-
+ >>> slp = Module('r.slope.aspect',
+ ... elevation='ele', slope='slp', aspect='asp',
+ ... overwrite=True, run_=False)
+ >>> get_cmd(slp.get_dict()) # doctest: +ELLIPSIS
+ ['r.slope.aspect', 'elevation=ele', 'format=degrees', ..., '--o']
"""
cmd = [cmdd['name'], ]
cmd.extend(("%s=%s" % (k, v) for k, v in cmdd['inputs']
@@ -396,30 +329,23 @@
def cmd_exe(args):
"""Create a mapset, and execute a cmd inside.
- Parameters
- ----------
+ :param args: is a tuple that contains several information see below
+ :type args: tuple
+ :returns: None
- `args` is a tuple that contains:
+ The puple has to contain:
- bbox : dict
- A dict with the region parameters (n, s, e, w, etc.)
- that we want to set before to apply the command.
- mapnames : dict
- A dictionary to substitute the input if the domain has
- been splitted in several tiles.
- gisrc_src : path to the GISRC source
- Path of the GISRC file from where we want to copy the groups.
- gisrc_dst : path to the GISRC destination
- Path of the GISRC file where the groups will be created.
- cmd : dictionary
- A dictionary with all the parameter of a GRASS module.
- groups: list
- A list of strings with the groups that we want to copy in the mapset.
+ - bbox (dict): a dict with the region parameters (n, s, e, w, etc.)
+ that we want to set before to apply the command.
+ - mapnames (dict): a dictionary to substitute the input if the domain has
+ been splitted in several tiles.
+ - gisrc_src (str): path of the GISRC file from where we want to copy the
+ groups.
+ - gisrc_dst (str): path of the GISRC file where the groups will be created.
+ - cmd (dict): a dictionary with all the parameter of a GRASS module.
+ - groups (list): a list of strings with the groups that we want to copy in
+ the mapset.
- Returns
- -------
-
- None.
"""
bbox, mapnames, gisrc_src, gisrc_dst, cmd, groups = args
src, dst = get_mapset(gisrc_src, gisrc_dst)
@@ -447,39 +373,32 @@
class GridModule(object):
+ # TODO maybe also i.* could be supported easily
"""Run GRASS raster commands in a multiproccessing mode.
- Parameters
- -----------
+ :param cmd: raster GRASS command, only command staring with r.* are valid.
+ :type cmd: str
+ :param width: width of the tile, in pixel
+ :type width: int
+ :param height: height of the tile, in pixel.
+ :type height: int
+ :param overlap: overlap between tiles, in pixel.
+ :type overlap: int
+ :param processes: number of threads, default value is equal to the number
+ of processor available.
+ :param split: if True use r.tile to split all the inputs.
+ :type split: bool
+ :param run_: if False only instantiate the object
+ :type run_: bool
+ :param args: give all the parameters to the command
+ :param kargs: give all the parameters to the command
- cmd: raster GRASS command
- Only command staring with r.* are valid.
- width: integer
- Width of the tile, in pixel.
- height: integer
- Height of the tile, in pixel.
- overlap: integer
- Overlap between tiles, in pixel.
- processes: number of threads
- Default value is equal to the number of processor available.
- split: boolean
- If True use r.tile to split all the inputs.
- run_: boolean
- If False only instantiate the object.
- args and kargs: cmd parameters
- Give all the parameters to the command.
-
- Examples
- --------
-
- ::
-
- >>> grd = GridModule('r.slope.aspect',
- ... width=500, height=500, overlap=2,
- ... processes=None, split=False,
- ... elevation='elevation',
- ... slope='slope', aspect='aspect', overwrite=True)
- >>> grd.run()
+ >>> grd = GridModule('r.slope.aspect',
+ ... width=500, height=500, overlap=2,
+ ... processes=None, split=False,
+ ... elevation='elevation',
+ ... slope='slope', aspect='aspect', overwrite=True)
+ >>> grd.run()
"""
def __init__(self, cmd, width=None, height=None, overlap=0, processes=None,
split=False, debug=False, region=None, move=None, log=False,
@@ -531,7 +450,11 @@
os.remove(self.gisrc_dst)
def clean_location(self, location=None):
- """Remove all created mapsets."""
+ """Remove all created mapsets.
+
+ :param location: a Location instance where we are running the analysis
+ :type location: Location object
+ """
if location is None:
if self.n_mset:
self.n_mset.current()
@@ -599,7 +522,14 @@
inm.value = inm.value + '@%s' % mset
def run(self, patch=True, clean=True):
- """Run the GRASS command."""
+ """Run the GRASS command
+
+ :param patch: set False if you does not want to patch the results
+ :type patch: bool
+ :param clean: set False if you does not want to remove all the stuff
+ created by GridModule
+ :type clean: bool
+ """
self.module.flags.overwrite = True
self.define_mapset_inputs()
if self.debug:
Modified: grass/trunk/lib/python/pygrass/modules/grid/patch.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/patch.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/modules/grid/patch.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -14,6 +14,10 @@
def get_start_end_index(bbox_list):
"""Convert a Bounding Box to a list of the index of
column start, end, row start and end
+
+ :param bbox_list: a list of BBox object to convert
+ :type bbox_list: list of BBox object
+
"""
ss_list = []
reg = Region()
@@ -25,7 +29,15 @@
def rpatch_row(rast, rasts, bboxes):
- """Patch a row of bound boxes."""
+ """Patch a row of bound boxes.
+
+ :param rast: a Raster object to write
+ :type rast: Raster object
+ :param rasts: a list of Raster object to read
+ :type rasts: list of Raster object
+ :param bboxes: a list of BBox object
+ :type bboxes: list of BBox object
+ """
sei = get_start_end_index(bboxes)
# instantiate two buffer
buff = rasts[0][0]
@@ -41,7 +53,26 @@
def rpatch_map(raster, mapset, mset_str, bbox_list, overwrite=False,
start_row=0, start_col=0, prefix=''):
- """Patch raster using a bounding box list to trim the raster."""
+ # TODO is prefix useful??
+ """Patch raster using a bounding box list to trim the raster.
+
+ :param raster: the name of output raster
+ :type raster: str
+ :param mapset: the name of mapset to use
+ :type mapset: str
+ :param mset_str:
+ :type mset_str: str
+ :param bbox_list: a list of BBox object to convert
+ :type bbox_list: list of BBox object
+ :param overwrite: overwrite existing raster
+ :type overwrite: bool
+ :param start_row: the starting row of original raster
+ :type start_row: int
+ :param start_col: the starting column of original raster
+ :type start_col: int
+ :param prefix: the prefix of output raster
+ :type prefix: str
+ """
# Instantiate the RasterRow input objects
rast = RasterRow(prefix + raster, mapset)
rtype = RasterRow(name=raster, mapset=mset_str % (0, 0))
Modified: grass/trunk/lib/python/pygrass/modules/grid/split.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/split.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/modules/grid/split.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -11,7 +11,21 @@
def get_bbox(reg, row, col, width, height, overlap):
- """Return a Bbox"""
+ """Return a Bbox
+
+ :param reg: a Region object to split
+ :type reg: Region object
+ :param row: the number of row
+ :type row: int
+ :param col: the number of row
+ :type col: int
+ :param width: the width of tiles
+ :type width: int
+ :param height: the width of tiles
+ :type height: int
+ :param overlap: the value of overlap between tiles
+ :type overlap: int
+ """
north = reg.north - (row * height - overlap) * reg.nsres
south = reg.north - ((row + 1) * height + overlap) * reg.nsres
east = reg.west + ((col + 1) * width + overlap) * reg.ewres
@@ -23,25 +37,34 @@
def split_region_tiles(region=None, width=100, height=100, overlap=0):
- """Spit a region into a list of Bbox. ::
+ """Spit a region into a list of Bbox.
- >>> reg = Region()
- >>> reg.north = 1350
- >>> reg.south = 0
- >>> reg.nsres = 1
- >>> reg.east = 1500
- >>> reg.west = 0
- >>> reg.ewres = 1
- >>> reg.cols
- 1500
- >>> reg.rows
- 1350
- >>> split_region_tiles(region=reg, width=1000, height=700, overlap=0) # doctest: +NORMALIZE_WHITESPACE
- [[Bbox(1350.0, 650.0, 1000.0, 0.0), Bbox(1350.0, 650.0, 1500.0, 1000.0)],
- [Bbox(650.0, 0.0, 1000.0, 0.0), Bbox(650.0, 0.0, 1500.0, 1000.0)]]
- >>> split_region_tiles(region=reg, width=1000, height=700, overlap=10) # doctest: +NORMALIZE_WHITESPACE
- [[Bbox(1350.0, 640.0, 1010.0, 0.0), Bbox(1350.0, 640.0, 1500.0, 990.0)],
- [Bbox(660.0, 0.0, 1010.0, 0.0), Bbox(660.0, 0.0, 1500.0, 990.0)]]
+ :param region: a Region object to split
+ :type region: Region object
+ :param width: the width of tiles
+ :type width: int
+ :param height: the width of tiles
+ :type height: int
+ :param overlap: the value of overlap between tiles
+ :type overlap: int
+
+ >>> reg = Region()
+ >>> reg.north = 1350
+ >>> reg.south = 0
+ >>> reg.nsres = 1
+ >>> reg.east = 1500
+ >>> reg.west = 0
+ >>> reg.ewres = 1
+ >>> reg.cols
+ 1500
+ >>> reg.rows
+ 1350
+ >>> split_region_tiles(region=reg, width=1000, height=700, overlap=0) # doctest: +NORMALIZE_WHITESPACE
+ [[Bbox(1350.0, 650.0, 1000.0, 0.0), Bbox(1350.0, 650.0, 1500.0, 1000.0)],
+ [Bbox(650.0, 0.0, 1000.0, 0.0), Bbox(650.0, 0.0, 1500.0, 1000.0)]]
+ >>> split_region_tiles(region=reg, width=1000, height=700, overlap=10) # doctest: +NORMALIZE_WHITESPACE
+ [[Bbox(1350.0, 640.0, 1010.0, 0.0), Bbox(1350.0, 640.0, 1500.0, 990.0)],
+ [Bbox(660.0, 0.0, 1010.0, 0.0), Bbox(660.0, 0.0, 1500.0, 990.0)]]
"""
reg = region if region else Region()
ncols = (reg.cols + width - 1) // width
@@ -58,25 +81,16 @@
def get_overlap_region_tiles(region=None, width=100, height=100, overlap=0):
- """Get the Bbox ov the overlapped region. ::
+ """Get the Bbox of the overlapped region.
- >>> reg = Region()
- >>> reg.north = 1350
- >>> reg.south = 0
- >>> reg.nsres = 1
- >>> reg.east = 1500
- >>> reg.west = 0
- >>> reg.ewres = 1
- >>> reg.cols
- 1500
- >>> reg.rows
- 1350
- >>> split_region_tiles(region=reg, width=1000, height=700, overlap=0) # doctest: +NORMALIZE_WHITESPACE
- [[Bbox(1350.0, 650.0, 1000.0, 0.0), Bbox(1350.0, 650.0, 1500.0, 1000.0)],
- [Bbox(650.0, 0.0, 1000.0, 0.0), Bbox(650.0, 0.0, 1500.0, 1000.0)]]
- >>> split_region_tiles(region=reg, width=1000, height=700, overlap=10) # doctest: +NORMALIZE_WHITESPACE
- [[Bbox(1350.0, 640.0, 1010.0, 0.0), Bbox(1350.0, 640.0, 1500.0, 990.0)],
- [Bbox(660.0, 0.0, 1010.0, 0.0), Bbox(660.0, 0.0, 1500.0, 990.0)]]
+ :param region: a Region object to split
+ :type region: Region object
+ :param width: the width of tiles
+ :type width: int
+ :param height: the width of tiles
+ :type height: int
+ :param overlap: the value of overlap between tiles
+ :type overlap: int
"""
reg = region if region else Region()
ncols = (reg.cols + width - 1) // width
Modified: grass/trunk/lib/python/pygrass/vector/find.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/find.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/vector/find.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -14,7 +14,10 @@
class AbstractFinder(object):
def __init__(self, c_mapinfo, table=None, writable=False):
- """Find geometry feature around a point.
+ """AbstractFinder
+ -----------------
+
+ Find geometry feature around a point.
"""
self.c_mapinfo = c_mapinfo
self.table = table
@@ -32,7 +35,9 @@
class PointFinder(AbstractFinder):
- """Find the geomtry features of a vector map that are close to a point. ::
+ """PointFinder
+ ------------------
+ Find the geomtry features of a vector map that are close to a point. ::
>>> from grass.pygrass.vector import VectorTopo
>>> zipcodes = VectorTopo('zipcodes', 'PERMANENT')
Modified: grass/trunk/lib/python/pygrass/vector/sql.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/sql.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/vector/sql.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -3,15 +3,13 @@
SQL
===
-It is a collection of strings to avoid to repeat the code. ::
+It is a collection of strings to avoid to repeat the code.
>>> SELECT.format(cols=', '.join(['cat', 'area']), tname='table')
'SELECT cat, area FROM table;'
>>> SELECT_WHERE.format(cols=', '.join(['cat', 'area']),
... tname='table', condition='area>10000')
'SELECT cat, area FROM table WHERE area>10000;'
-
-
"""
#
Modified: grass/trunk/lib/python/pygrass/vector/table.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/table.py 2014-05-29 09:55:28 UTC (rev 60580)
+++ grass/trunk/lib/python/pygrass/vector/table.py 2014-05-29 10:15:35 UTC (rev 60581)
@@ -393,9 +393,9 @@
"""
def check_col(col_type):
"""Check the column type if it is supported by GRASS
-
+
:param col_type: the type of column
- :type col_type: str
+ :type col_type: str
"""
valid_type = ('DOUBLE PRECISION', 'DOUBLE', 'INT', 'INTEGER',
'DATE')
@@ -868,23 +868,21 @@
def add(self, link):
"""Add a new link. Need to open vector map in write mode
- :param link: the Link to add to the DBlinks
- :type link: a Link object
- ::
+ :param link: the Link to add to the DBlinks
+ :type link: a Link object
- >>> from grass.pygrass.vector import VectorTopo
- >>> municip = VectorTopo('census')
- >>> municip.open()
- >>> dblinks = DBlinks(municip.c_mapinfo)
- >>> dblinks
- DBlinks([Link(1, census, sqlite)])
- >>> link = Link(2, 'pg_link', 'boundary_municp_pg', 'cat',
- ... 'host=localhost dbname=grassdb', 'pg') # doctest: +SKIP
- >>> dblinks.add(link) # doctest: +SKIP
- >>> dblinks # doctest: +SKIP
- DBlinks([Link(1, boundary_municp, sqlite)])
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> municip = VectorTopo('census')
+ >>> municip.open()
+ >>> dblinks = DBlinks(municip.c_mapinfo)
+ >>> dblinks
+ DBlinks([Link(1, census, sqlite)])
+ >>> link = Link(2, 'pg_link', 'boundary_municp_pg', 'cat',
+ ... 'host=localhost dbname=grassdb', 'pg') # doctest: +SKIP
+ >>> dblinks.add(link) # doctest: +SKIP
+ >>> dblinks # doctest: +SKIP
+ DBlinks([Link(1, boundary_municp, sqlite)])
- ..
"""
#TODO: check if open in write mode or not.
libvect.Vect_map_add_dblink(self.c_mapinfo,
@@ -892,19 +890,25 @@
link.key, link.database, link.driver)
def remove(self, key, force=False):
- """Remove a link. If force set to true remove also the table ::
+ """Remove a link. If force set to true remove also the table
- >>> from grass.pygrass.vector import VectorTopo
- >>> municip = VectorTopo('census')
- >>> municip.open()
- >>> dblinks = DBlinks(municip.c_mapinfo)
- >>> dblinks
- DBlinks([Link(1, census, sqlite)])
- >>> dblinks.remove('pg_link') # doctest: +SKIP
- >>> dblinks # need to open vector map in write mode
- DBlinks([Link(1, census, sqlite)])
+ :param key: the key of Link
+ :type key: str
+ :param force: if True remove also the table from database otherwise
+ only the link between table and vector
+ :type force: boole
- ..
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> municip = VectorTopo('census')
+ >>> municip.open()
+ >>> dblinks = DBlinks(municip.c_mapinfo)
+ >>> dblinks
+ DBlinks([Link(1, census, sqlite)])
+ >>> dblinks.remove('pg_link') # doctest: +SKIP
+ >>> dblinks # need to open vector map in write mode
+ DBlinks([Link(1, census, sqlite)])
+
+
"""
if force:
link = self.by_name(key)
@@ -944,7 +948,11 @@
return self._name
def _set_name(self, new_name):
- """Private method to set the name of table"""
+ """Private method to set the name of table
+
+ :param new_name: the new name of table
+ :type new_name: str
+ """
old_name = self._name
cur = self.conn.cursor()
cur.execute(sql.RENAME_TAB.format(old_name=old_name,
@@ -987,8 +995,16 @@
return self.n_rows()
def drop(self, cursor=None, force=False):
- """Method to drop table from database"""
+ """Method to drop table from database
+ :param cursor: the cursor to connect, if None it use the cursor
+ of connection table object
+ :type cursor: Cursor object
+ :param force: True to remove the table, by default False to print
+ advice
+ :type force: bool
+ """
+
cur = cursor if cursor else self.conn.cursor()
if self.exist(cursor=cur):
used = db_table_in_vector(self.name)
@@ -1020,19 +1036,29 @@
def execute(self, sql_code=None, cursor=None, many=False, values=None):
"""Execute SQL code from a given string or build with filters and
- return a cursor object. ::
+ return a cursor object.
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> tab_sqlite = Table(name='census',
- ... connection=sqlite3.connect(get_path(path)))
- >>> tab_sqlite.filters.select('cat', 'TOTAL_POP').order_by('AREA')
- Filters(u'SELECT cat, TOTAL_POP FROM census ORDER BY AREA;')
- >>> cur = tab_sqlite.execute()
- >>> cur.fetchone()
- (1856, 0)
+ :param sql_code: the SQL code to execute, if not pass it use filters
+ variable
+ :type sql_code: str
+ :param cursor: the cursor to connect, if None it use the cursor
+ of connection table object
+ :type cursor: Cursor object
+ :param many: True to run executemany function
+ :type many: bool
+ :param values: The values to substitute into sql_code string
+ :type values: list of tuple
- ..
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> tab_sqlite = Table(name='census',
+ ... connection=sqlite3.connect(get_path(path)))
+ >>> tab_sqlite.filters.select('cat', 'TOTAL_POP').order_by('AREA')
+ Filters(u'SELECT cat, TOTAL_POP FROM census ORDER BY AREA;')
+ >>> cur = tab_sqlite.execute()
+ >>> cur.fetchone()
+ (1856, 0)
+
"""
try:
sqlc = sql_code if sql_code else self.filters.get_sql()
@@ -1045,26 +1071,62 @@
raise ValueError("The SQL is not correct:\n%r" % sqlc)
def exist(self, cursor=None):
- """Return True if the table already exist in the DB, False otherwise"""
+ """Return True if the table already exist in the DB, False otherwise
+ :param cursor: the cursor to connect, if None it use the cursor
+ of connection table object
+ :type cursor: Cursor object
+ """
cur = cursor if cursor else self.conn.cursor()
return table_exist(cur, self.name)
def insert(self, values, cursor=None, many=False):
- """Insert a new row"""
+ """Insert a new row
+
+ :param values: a tuple of values to insert, it is possible to insert
+ more rows using a list of tuple and paramater `many`
+ :type values: tuple
+ :param cursor: the cursor to connect, if None it use the cursor
+ of connection table object
+ :type cursor: Cursor object
+ :param many: True to run executemany function
+ :type many: bool
+ """
cur = cursor if cursor else self.conn.cursor()
if many:
return cur.executemany(self.columns.insert_str, values)
return cur.execute(self.columns.insert_str, values)
def update(self, key, values, cursor=None, many=False):
- """Update a column for each row"""
+ """Update a column for each row
+
+ :param key: the name of column
+ :param values: the values to insert
+ :type values: str
+ :param cursor: the cursor to connect, if None it use the cursor
+ of connection table object
+ :type cursor: Cursor object
+ :param many: True to run executemany function
+ :type many: bool
+ """
cur = cursor if cursor else self.conn.cursor()
vals = list(values)
vals.append(key)
return cur.execute(self.columns.update_str, vals)
def create(self, cols, name=None, overwrite=False, cursor=None):
- """Create a new table"""
+ """Create a new table
+
+ :param cols:
+ :type cols:
+ :param name: the name of table to create, None for the name of Table object
+ :type name: str
+ :param overwrite: overwrite existing table
+ :type overwrite: bool
+ :param cursor: the cursor to connect, if None it use the cursor
+ of connection table object
+ :type cursor: Cursor object
+
+ """
cur = cursor if cursor else self.conn.cursor()
coldef = ',\n'.join(['%s %s' % col for col in cols])
if name:
More information about the grass-commit
mailing list