[GRASS-SVN] r61944 - in grass/trunk/lib/python: gunittest imaging pygrass pygrass/modules/interface pygrass/raster pygrass/shell pygrass/vector script
svn_grass at osgeo.org
svn_grass at osgeo.org
Sun Sep 14 06:47:40 PDT 2014
Author: lucadelu
Date: 2014-09-14 06:47:40 -0700 (Sun, 14 Sep 2014)
New Revision: 61944
Modified:
grass/trunk/lib/python/gunittest/case.py
grass/trunk/lib/python/gunittest/gmodules.py
grass/trunk/lib/python/imaging/images2gif.py
grass/trunk/lib/python/imaging/images2swf.py
grass/trunk/lib/python/pygrass/functions.py
grass/trunk/lib/python/pygrass/modules/interface/flag.py
grass/trunk/lib/python/pygrass/modules/interface/module.py
grass/trunk/lib/python/pygrass/raster/__init__.py
grass/trunk/lib/python/pygrass/raster/abstract.py
grass/trunk/lib/python/pygrass/raster/category.py
grass/trunk/lib/python/pygrass/shell/conversion.py
grass/trunk/lib/python/pygrass/vector/__init__.py
grass/trunk/lib/python/pygrass/vector/basic.py
grass/trunk/lib/python/pygrass/vector/find.py
grass/trunk/lib/python/pygrass/vector/geometry.py
grass/trunk/lib/python/pygrass/vector/table.py
grass/trunk/lib/python/script/db.py
grass/trunk/lib/python/script/raster.py
grass/trunk/lib/python/script/task.py
grass/trunk/lib/python/script/utils.py
grass/trunk/lib/python/script/vector.py
Log:
lib python: documentation cleanup, fix sphinx warning
Modified: grass/trunk/lib/python/gunittest/case.py
===================================================================
--- grass/trunk/lib/python/gunittest/case.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/gunittest/case.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -489,6 +489,7 @@
Or in command line, use ``md5sum`` command if available:
.. code-block:: sh
+
md5sum some_file.txt
Finaly, you can use Python ``hashlib`` to obtain MD5::
@@ -955,7 +956,7 @@
errors=errors)
# TODO: use this also in assert and apply when appropriate
if expecting_stdout and not module.outputs.stdout.strip():
-
+
if module.outputs.stderr:
errors = " The errors are:\n" + module.outputs.stderr
else:
Modified: grass/trunk/lib/python/gunittest/gmodules.py
===================================================================
--- grass/trunk/lib/python/gunittest/gmodules.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/gunittest/gmodules.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -21,7 +21,7 @@
class SimpleModule(Module):
"""Simple wrapper around pygrass.modules.Module to make sure that
- run_, finish_, stdout and stderr are set correctly.
+ run\_, finish\_, stdout and stderr are set correctly.
>>> mapcalc = SimpleModule('r.mapcalc', expression='test_a = 1',
... overwrite=True)
Modified: grass/trunk/lib/python/imaging/images2gif.py
===================================================================
--- grass/trunk/lib/python/imaging/images2gif.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/imaging/images2gif.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -35,10 +35,10 @@
Note that since July 2004, all patents on the LZW compression patent have
expired. Therefore the GIF format may now be used freely.
-Acknowledgements
-----------------
+Acknowledgements:
Many thanks to Ant1 for:
+
* noting the use of "palette=PIL.Image.ADAPTIVE", which significantly
improves the results.
* the modifications to save each image with its own palette, or optionally
@@ -56,8 +56,8 @@
distribution of PIL)
-Usefull links
--------------
+Usefull links:
+
* http://tronche.com/computer-graphics/gif/
* http://en.wikipedia.org/wiki/Graphics_Interchange_Format
* http://www.w3.org/Graphics/GIF/spec-gif89a.txt
@@ -225,8 +225,8 @@
"""Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
- Dispose
- -------
+ Dispose:
+
* 0 - No disposal specified.
* 1 - Do not dispose. The graphic is to be left in place.
* 2 - Restore to background color. The area used by the graphic
@@ -398,12 +398,12 @@
def writeGifToFile(self, fp, images, durations, loops, xys, disposes):
""" writeGifToFile(fp, images, durations, loops, xys, disposes)
-
+
Given a set of images writes the bytes to the specified stream.
Requires different handling of palette for PIL and Pillow:
based on https://github.com/rec/echomesh/blob/master/
code/python/external/images2gif.py
-
+
"""
# Obtain palette for all images and count each occurance
@@ -476,44 +476,39 @@
fp.write(";") # end gif
return frames
-## Exposed functions
+
def writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None):
"""Write an animated gif from the specified images.
- Parameters
- ----------
- filename : string
- The name of the file to write the image to.
- images : list
- Should be a list consisting of PIL images or numpy arrays.
- The latter should be between 0 and 255 for integer types, and
- between 0 and 1 for float types.
- duration : scalar or list of scalars
- The duration for all frames, or (if a list) for each frame.
- repeat : bool or integer
- The amount of loops. If True, loops infinitetely.
- dither : bool
- Whether to apply dithering
- nq : integer
- If nonzero, applies the NeuQuant quantization algorithm to create
- the color palette. This algorithm is superior, but slower than
- the standard PIL algorithm. The value of nq is the quality
- parameter. 1 represents the best quality. 10 is in general a
- good tradeoff between quality and speed. When using this option,
- better results are usually obtained when subRectangles is False.
- subRectangles : False, True, or a list of 2-element tuples
- Whether to use sub-rectangles. If True, the minimal rectangle that
- is required to update each frame is automatically detected. This
- can give significant reductions in file size, particularly if only
- a part of the image changes. One can also give a list of x-y
- coordinates if you want to do the cropping yourself. The default
- is True.
- dispose : int
- How to dispose each frame. 1 means that each frame is to be left
- in place. 2 means the background color should be restored after
- each frame. 3 means the decoder should restore the previous frame.
- If subRectangles==False, the default is 2, otherwise it is 1.
+ :param str filename: the name of the file to write the image to.
+ :param list images: should be a list consisting of PIL images or numpy
+ arrays. The latter should be between 0 and 255 for
+ integer types, and between 0 and 1 for float types.
+ :param duration: scalar or list of scalars The duration for all frames, or
+ (if a list) for each frame.
+ :param repeat: bool or integer The amount of loops. If True, loops infinitetely.
+ :param bool dither: whether to apply dithering
+ :param int nq: If nonzero, applies the NeuQuant quantization algorithm to
+ create the color palette. This algorithm is superior, but
+ slower than the standard PIL algorithm. The value of nq is
+ the quality parameter. 1 represents the best quality. 10 is
+ in general a good tradeoff between quality and speed. When
+ using this option, better results are usually obtained when
+ subRectangles is False.
+ :param subRectangles: False, True, or a list of 2-element tuples
+ Whether to use sub-rectangles. If True, the minimal
+ rectangle that is required to update each frame is
+ automatically detected. This can give significant
+ reductions in file size, particularly if only a part
+ of the image changes. One can also give a list of x-y
+ coordinates if you want to do the cropping yourself.
+ The default is True.
+ :param int dispose: how to dispose each frame. 1 means that each frame is
+ to be left in place. 2 means the background color
+ should be restored after each frame. 3 means the
+ decoder should restore the previous frame. If
+ subRectangles==False, the default is 2, otherwise it is 1.
"""
@@ -636,8 +631,7 @@
See also:
http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
- License of the NeuQuant Neural-Net Quantization Algorithm
- ---------------------------------------------------------
+ **License of the NeuQuant Neural-Net Quantization Algorithm**
Copyright (c) 1994 Anthony Dekker
Ported to python by Marius van Voorden in 2010
Modified: grass/trunk/lib/python/imaging/images2swf.py
===================================================================
--- grass/trunk/lib/python/imaging/images2swf.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/imaging/images2swf.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -55,6 +55,7 @@
This module requires Python 2.x and numpy.
sources and tools:
+
- SWF on wikipedia
- Adobes "SWF File Format Specification" version 10
(http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v10.pdf)
Modified: grass/trunk/lib/python/pygrass/functions.py
===================================================================
--- grass/trunk/lib/python/pygrass/functions.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/functions.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -48,6 +48,7 @@
def findmaps(type, pattern=None, mapset='', location='', gisdbase=''):
"""Return a list of tuple contining the names of the:
+
* map
* mapset,
* location,
@@ -118,17 +119,17 @@
def getenv(env):
- """Return the current grass environment variables ::
+ """Return the current grass environment variables
- >>> getenv("MAPSET")
- 'user1'
+ >>> getenv("MAPSET")
+ 'user1'
"""
return libgis.G__getenv(env)
def get_mapset_raster(mapname, mapset=''):
- """Return the mapset of the raster map ::
+ """Return the mapset of the raster map
>>> get_mapset_raster('elevation')
'PERMANENT'
@@ -138,7 +139,7 @@
def get_mapset_vector(mapname, mapset=''):
- """Return the mapset of the vector map ::
+ """Return the mapset of the vector map
>>> get_mapset_vector('census')
'PERMANENT'
@@ -148,7 +149,7 @@
def is_clean_name(name):
- """Return if the name is valid ::
+ """Return if the name is valid
>>> is_clean_name('census')
True
@@ -166,13 +167,14 @@
def coor2pixel(coord, region):
- """Convert coordinates into a pixel row and col ::
+ """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
+ >>> 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),
@@ -180,13 +182,14 @@
def pixel2coor(pixel, region):
- """Convert row and col of a pixel into a coordinates ::
+ """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
+ >>> 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),
@@ -196,37 +199,33 @@
def get_raster_for_points(poi_vector, raster, column=None):
"""Query a raster map for each point feature of a vector
- Example ::
+ 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()
- >>> 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')
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> from grass.pygrass.raster import RasterRow
+ >>> ele = RasterRow('elevation')
+ >>> copy('schools','myschools','vect')
+ >>> sch = VectorTopo('myschools')
+ >>> sch.open()
+ >>> 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')
- Parameters
- -------------
+ :param point: point vector object
+ :param raster: raster object
+ :param str column: column name to update
- point: point vector object
-
- raster: raster object
-
- column: column name to update
"""
from math import isnan
if not column:
@@ -268,9 +267,9 @@
def get_lib_path(modname, libname):
- """Return the path of the libname contained in the module. ::
+ """Return the path of the libname contained in the module.
- >>> get_lib_path(modname='r.modis', libname='libmodis')
+ >>> get_lib_path(modname='r.modis', libname='libmodis')
"""
from os.path import isdir, join
from os import getenv
@@ -338,9 +337,6 @@
"""Property attribute for docstrings.
Took from: https://gist.github.com/bfroehle/4041015
- Usage
- -----
-
>>> class A(object):
... '''Main docstring'''
... def __init__(self, x):
Modified: grass/trunk/lib/python/pygrass/modules/interface/flag.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/flag.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/modules/interface/flag.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -8,21 +8,21 @@
class Flag(object):
"""The Flag object store all information about a flag of module.
- It is possible to set flags of command using this object. ::
+ It is possible to set flags of command using this object.
- >>> flag = Flag(diz=dict(name='a', description='Flag description',
- ... default=True))
- >>> flag.name
- u'a'
- >>> flag.special
- False
- >>> flag.description
- u'Flag description'
- >>> flag = Flag(diz=dict(name='overwrite'))
- >>> flag.name
- u'overwrite'
- >>> flag.special
- True
+ >>> flag = Flag(diz=dict(name='a', description='Flag description',
+ ... default=True))
+ >>> flag.name
+ u'a'
+ >>> flag.special
+ False
+ >>> flag.description
+ u'Flag description'
+ >>> flag = Flag(diz=dict(name='overwrite'))
+ >>> flag.name
+ u'overwrite'
+ >>> flag.special
+ True
"""
def __init__(self, xflag=None, diz=None):
self.value = False
@@ -35,21 +35,21 @@
self.guisection = diz.get('guisection', None)
def get_bash(self):
- """Return the BASH representation of a flag. ::
+ """Return the BASH representation of a flag.
- >>> flag = Flag(diz=dict(name='a', description='Flag description',
- ... default=True))
- >>> flag.get_bash()
- u''
- >>> flag.value = True
- >>> flag.get_bash()
- u'-a'
- >>> flag = Flag(diz=dict(name='overwrite'))
- >>> flag.get_bash()
- u''
- >>> flag.value = True
- >>> flag.get_bash()
- u'--o'
+ >>> flag = Flag(diz=dict(name='a', description='Flag description',
+ ... default=True))
+ >>> flag.get_bash()
+ u''
+ >>> flag.value = True
+ >>> flag.get_bash()
+ u'-a'
+ >>> flag = Flag(diz=dict(name='overwrite'))
+ >>> flag.get_bash()
+ u''
+ >>> flag.value = True
+ >>> flag.get_bash()
+ u'--o'
"""
if self.value:
if self.special:
@@ -60,21 +60,21 @@
return ''
def get_python(self):
- """Return the python representation of a flag. ::
+ """Return the python representation of a flag.
- >>> flag = Flag(diz=dict(name='a', description='Flag description',
- ... default=True))
- >>> flag.get_python()
- u''
- >>> flag.value = True
- >>> flag.get_python()
- u'a'
- >>> flag = Flag(diz=dict(name='overwrite'))
- >>> flag.get_python()
- u''
- >>> flag.value = True
- >>> flag.get_python()
- u'overwrite=True'
+ >>> flag = Flag(diz=dict(name='a', description='Flag description',
+ ... default=True))
+ >>> flag.get_python()
+ u''
+ >>> flag.value = True
+ >>> flag.get_python()
+ u'a'
+ >>> flag = Flag(diz=dict(name='overwrite'))
+ >>> flag.get_python()
+ u''
+ >>> flag.value = True
+ >>> flag.get_python()
+ u'overwrite=True'
"""
if self.value:
return '%s=True' % self.name if self.special else self.name
@@ -95,20 +95,17 @@
{name}: {default}
{description}
- ::
+ >>> flag = Flag(diz=dict(name='a', description='Flag description',
+ ... default=True))
+ >>> print(flag.__doc__)
+ a: True
+ Flag description
- >>> flag = Flag(diz=dict(name='a', description='Flag description',
- ... default=True))
- >>> print(flag.__doc__)
- a: True
- Flag description
+ >>> flag = Flag(diz=dict(name='overwrite'))
+ >>> print(flag.__doc__)
+ overwrite: None
+ None
- >>> flag = Flag(diz=dict(name='overwrite'))
- >>> print(flag.__doc__)
- overwrite: None
- None
-
- ..
"""
return read.DOC['flag'].format(name=self.name,
default=repr(self.default),
Modified: grass/trunk/lib/python/pygrass/modules/interface/module.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/module.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/modules/interface/module.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -23,51 +23,51 @@
class ParallelModuleQueue(object):
"""This class is designed to run an arbitrary number of pygrass Module
- processes in parallel.
+ processes in parallel.
- Objects of type grass.pygrass.modules.Module can be put into the
- queue using put() method. When the queue is full with the maximum
- number of parallel processes it will wait for all processes to finish,
- sets the stdout and stderr of the Module object and removes it
- from the queue when its finished.
+ Objects of type grass.pygrass.modules.Module can be put into the
+ queue using put() method. When the queue is full with the maximum
+ number of parallel processes it will wait for all processes to finish,
+ sets the stdout and stderr of the Module object and removes it
+ from the queue when its finished.
- This class will raise a GrassError in case a Module process exits
- with a return code other than 0.
+ This class will raise a GrassError in case a Module process exits
+ with a return code other than 0.
- Usage:
+ Usage:
- >>> import copy
- >>> from grass.pygrass.modules import Module, ParallelModuleQueue
- >>> mapcalc_list = []
- >>> mapcalc = Module("r.mapcalc", overwrite=True, run_=False)
- >>> queue = ParallelModuleQueue(nprocs=3)
- >>> for i in xrange(5):
- ... new_mapcalc = copy.deepcopy(mapcalc)
- ... mapcalc_list.append(new_mapcalc)
- ... new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
- ... queue.put(new_mapcalc)
- Module('r.mapcalc')
- Module('r.mapcalc')
- Module('r.mapcalc')
- Module('r.mapcalc')
- Module('r.mapcalc')
+ >>> import copy
+ >>> from grass.pygrass.modules import Module, ParallelModuleQueue
+ >>> mapcalc_list = []
+ >>> mapcalc = Module("r.mapcalc", overwrite=True, run_=False)
+ >>> queue = ParallelModuleQueue(nprocs=3)
+ >>> for i in xrange(5):
+ ... new_mapcalc = copy.deepcopy(mapcalc)
+ ... mapcalc_list.append(new_mapcalc)
+ ... new_mapcalc(expression="test_pygrass_%i = %i"%(i, i))
+ ... queue.put(new_mapcalc)
+ Module('r.mapcalc')
+ Module('r.mapcalc')
+ Module('r.mapcalc')
+ Module('r.mapcalc')
+ Module('r.mapcalc')
- >>> queue.wait()
- >>> for mapcalc in mapcalc_list:
- ... print(mapcalc.popen.returncode)
- 0
- 0
- 0
- 0
- 0
+ >>> queue.wait()
+ >>> for mapcalc in mapcalc_list:
+ ... print(mapcalc.popen.returncode)
+ 0
+ 0
+ 0
+ 0
+ 0
"""
def __init__(self, nprocs=1):
"""Constructor
:param nprocs: The maximum number of Module processes that
- can be run in parallel, defualt is 1, if None
- then use all the available CPUs.
+ can be run in parallel, defualt is 1, if None
+ then use all the available CPUs.
:type nprocs: int
"""
nprocs = int(nprocs) if nprocs else cpu_count()
@@ -78,12 +78,12 @@
def put(self, module):
"""Put the next Module object in the queue
- To run the Module objects in parallel the run_ and finish_ options
- of the Module must be set to False.
+ To run the Module objects in parallel the run\_ and finish\_ options
+ of the Module must be set to False.
- :param module: a preconfigured Module object with run_ and finish_
- set to False
- :type module: Module object
+ :param module: a preconfigured Module object with run\_ and finish\_
+ set to False
+ :type module: Module object
"""
self._list[self._proc_count] = module
# Force that finish is False, otherwise the execution
@@ -98,9 +98,9 @@
def get(self, num):
"""Get a Module object from the queue
- :param num: the number of the object in queue
- :type num: int
- :returns: the Module object or None if num is not in the queue
+ :param num: the number of the object in queue
+ :type num: int
+ :returns: the Module object or None if num is not in the queue
"""
if num < self._num_procs:
return self._list[num]
@@ -108,10 +108,10 @@
def get_num_run_procs(self):
"""Get the number of Module processes that are in the queue running
- or finished
+ or finished
- :returns: the maximum number fo Module processes running/finished in
- the queue
+ :returns: the maximum number fo Module processes running/finished in
+ the queue
"""
return len(self._list)
@@ -124,8 +124,8 @@
"""Set the maximum number of Module processes that should run
in parallel
- :param nprocs: The maximum number of Module processes that
- can be run in parallel
+ :param nprocs: The maximum number of Module processes that can be
+ run in parallel
:type nprocs: int
"""
self._num_procs = int(nprocs)
@@ -133,7 +133,7 @@
def wait(self):
"""Wait for all Module processes that are in the list to finish
- and set the modules stdout and stderr output options
+ and set the modules stdout and stderr output options
"""
for proc in self._list:
if proc:
@@ -155,130 +155,130 @@
the ``--interface-description`` in order to understand which parameters
are required which optionals. ::
- >>> from grass.pygrass.modules import Module
- >>> from subprocess import PIPE
- >>> import copy
+ >>> from grass.pygrass.modules import Module
+ >>> from subprocess import PIPE
+ >>> import copy
- >>> region = Module("g.region")
- >>> region.flags.p = True # set flags
- >>> region.flags.u = True
- >>> region.flags["3"].value = True # set numeric flags
- >>> region.get_bash()
- u'g.region -p -3 -u'
- >>> new_region = copy.deepcopy(region)
- >>> new_region.inputs.res = "10"
- >>> new_region.get_bash()
- u'g.region res=10 -p -3 -u'
+ >>> region = Module("g.region")
+ >>> region.flags.p = True # set flags
+ >>> region.flags.u = True
+ >>> region.flags["3"].value = True # set numeric flags
+ >>> region.get_bash()
+ u'g.region -p -3 -u'
+ >>> new_region = copy.deepcopy(region)
+ >>> new_region.inputs.res = "10"
+ >>> new_region.get_bash()
+ u'g.region res=10 -p -3 -u'
- >>> neighbors = Module("r.neighbors")
- >>> neighbors.inputs.input = "mapA"
- >>> neighbors.outputs.output = "mapB"
- >>> neighbors.inputs.size = 5
- >>> neighbors.inputs.quantile = 0.5
- >>> neighbors.get_bash()
- u'r.neighbors input=mapA method=average size=5 quantile=0.5 output=mapB'
+ >>> neighbors = Module("r.neighbors")
+ >>> neighbors.inputs.input = "mapA"
+ >>> neighbors.outputs.output = "mapB"
+ >>> neighbors.inputs.size = 5
+ >>> neighbors.inputs.quantile = 0.5
+ >>> neighbors.get_bash()
+ u'r.neighbors input=mapA method=average size=5 quantile=0.5 output=mapB'
- >>> new_neighbors1 = copy.deepcopy(neighbors)
- >>> new_neighbors1.inputs.input = "mapD"
- >>> new_neighbors1.inputs.size = 3
- >>> new_neighbors1.inputs.quantile = 0.5
- >>> new_neighbors1.get_bash()
- u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
+ >>> new_neighbors1 = copy.deepcopy(neighbors)
+ >>> new_neighbors1.inputs.input = "mapD"
+ >>> new_neighbors1.inputs.size = 3
+ >>> new_neighbors1.inputs.quantile = 0.5
+ >>> new_neighbors1.get_bash()
+ u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
- >>> new_neighbors2 = copy.deepcopy(neighbors)
- >>> new_neighbors2(input="mapD", size=3, run_=False)
- Module('r.neighbors')
- >>> new_neighbors2.get_bash()
- u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
+ >>> new_neighbors2 = copy.deepcopy(neighbors)
+ >>> new_neighbors2(input="mapD", size=3, run_=False)
+ Module('r.neighbors')
+ >>> new_neighbors2.get_bash()
+ u'r.neighbors input=mapD method=average size=3 quantile=0.5 output=mapB'
- >>> neighbors = Module("r.neighbors")
- >>> neighbors.get_bash()
- u'r.neighbors method=average size=3'
+ >>> neighbors = Module("r.neighbors")
+ >>> neighbors.get_bash()
+ u'r.neighbors method=average size=3'
- >>> new_neighbors3 = copy.deepcopy(neighbors)
- >>> new_neighbors3(input="mapA", size=3, output="mapB", run_=False)
- Module('r.neighbors')
- >>> new_neighbors3.get_bash()
- u'r.neighbors input=mapA method=average size=3 output=mapB'
+ >>> new_neighbors3 = copy.deepcopy(neighbors)
+ >>> new_neighbors3(input="mapA", size=3, output="mapB", run_=False)
+ Module('r.neighbors')
+ >>> new_neighbors3.get_bash()
+ u'r.neighbors input=mapA method=average size=3 output=mapB'
- >>> mapcalc = Module("r.mapcalc", expression="test_a = 1",
- ... overwrite=True, run_=False)
- >>> mapcalc.run()
- Module('r.mapcalc')
- >>> mapcalc.popen.returncode
- 0
+ >>> mapcalc = Module("r.mapcalc", expression="test_a = 1",
+ ... overwrite=True, run_=False)
+ >>> mapcalc.run()
+ Module('r.mapcalc')
+ >>> mapcalc.popen.returncode
+ 0
- >>> colors = Module("r.colors", map="test_a", rules="-",
- ... run_=False, stdout_=PIPE,
- ... stderr_=PIPE, stdin_="1 red")
- >>> colors.run()
- Module('r.colors')
- >>> colors.popen.returncode
- 0
- >>> colors.inputs["stdin"].value
- u'1 red'
- >>> colors.outputs["stdout"].value
- u''
- >>> colors.outputs["stderr"].value.strip()
- "Color table for raster map <test_a> set to 'rules'"
+ >>> colors = Module("r.colors", map="test_a", rules="-",
+ ... run_=False, stdout_=PIPE,
+ ... stderr_=PIPE, stdin_="1 red")
+ >>> colors.run()
+ Module('r.colors')
+ >>> colors.popen.returncode
+ 0
+ >>> colors.inputs["stdin"].value
+ u'1 red'
+ >>> colors.outputs["stdout"].value
+ u''
+ >>> colors.outputs["stderr"].value.strip()
+ "Color table for raster map <test_a> set to 'rules'"
- >>> colors = Module("r.colors", map="test_a", rules="-",
- ... run_=False, finish_=False, stdin_=PIPE)
- >>> colors.run()
- Module('r.colors')
- >>> stdout, stderr = colors.popen.communicate(input="1 red")
- >>> colors.popen.returncode
- 0
- >>> stdout
- >>> stderr
+ >>> colors = Module("r.colors", map="test_a", rules="-",
+ ... run_=False, finish_=False, stdin_=PIPE)
+ >>> colors.run()
+ Module('r.colors')
+ >>> stdout, stderr = colors.popen.communicate(input="1 red")
+ >>> colors.popen.returncode
+ 0
+ >>> stdout
+ >>> stderr
- >>> colors = Module("r.colors", map="test_a", rules="-",
- ... run_=False, finish_=False,
- ... stdin_=PIPE, stderr_=PIPE)
- >>> colors.run()
- Module('r.colors')
- >>> stdout, stderr = colors.popen.communicate(input="1 red")
- >>> colors.popen.returncode
- 0
- >>> stdout
- >>> stderr.strip()
- "Color table for raster map <test_a> set to 'rules'"
+ >>> colors = Module("r.colors", map="test_a", rules="-",
+ ... run_=False, finish_=False,
+ ... stdin_=PIPE, stderr_=PIPE)
+ >>> colors.run()
+ Module('r.colors')
+ >>> stdout, stderr = colors.popen.communicate(input="1 red")
+ >>> colors.popen.returncode
+ 0
+ >>> stdout
+ >>> stderr.strip()
+ "Color table for raster map <test_a> set to 'rules'"
- Run a second time
- >>> colors.run()
- Module('r.colors')
- >>> stdout, stderr = colors.popen.communicate(input="1 blue")
- >>> colors.popen.returncode
- 0
- >>> stdout
- >>> stderr.strip()
- "Color table for raster map <test_a> set to 'rules'"
+ Run a second time
+ >>> colors.run()
+ Module('r.colors')
+ >>> stdout, stderr = colors.popen.communicate(input="1 blue")
+ >>> colors.popen.returncode
+ 0
+ >>> stdout
+ >>> stderr.strip()
+ "Color table for raster map <test_a> set to 'rules'"
- Multiple run test
- >>> colors = Module("r.colors", map="test_a",
- ... color="ryb", run_=False)
- >>> colors.run()
- Module('r.colors')
- >>> colors(color="gyr")
- Module('r.colors')
- >>> colors.run()
- Module('r.colors')
- >>> colors(color="ryg")
- Module('r.colors')
- >>> colors(stderr_=PIPE)
- Module('r.colors')
- >>> colors.run()
- Module('r.colors')
- >>> print(colors.outputs["stderr"].value.strip())
- Color table for raster map <test_a> set to 'ryg'
- >>> colors(color="byg")
- Module('r.colors')
- >>> colors(stdout_=PIPE)
- Module('r.colors')
- >>> colors.run()
- Module('r.colors')
- >>> print(colors.outputs["stderr"].value.strip())
- Color table for raster map <test_a> set to 'byg'
+ Multiple run test
+ >>> colors = Module("r.colors", map="test_a",
+ ... color="ryb", run_=False)
+ >>> colors.run()
+ Module('r.colors')
+ >>> colors(color="gyr")
+ Module('r.colors')
+ >>> colors.run()
+ Module('r.colors')
+ >>> colors(color="ryg")
+ Module('r.colors')
+ >>> colors(stderr_=PIPE)
+ Module('r.colors')
+ >>> colors.run()
+ Module('r.colors')
+ >>> print(colors.outputs["stderr"].value.strip())
+ Color table for raster map <test_a> set to 'ryg'
+ >>> colors(color="byg")
+ Module('r.colors')
+ >>> colors(stdout_=PIPE)
+ Module('r.colors')
+ >>> colors.run()
+ Module('r.colors')
+ >>> print(colors.outputs["stderr"].value.strip())
+ Color table for raster map <test_a> set to 'byg'
Often in the Module class you can find ``*args`` and ``kwargs`` annotation
in methods, like in the __call__ method.
@@ -289,20 +289,20 @@
for arg in args:
print arg
- therefore if we call the function like: ::
+ therefore if we call the function like:
- >>> f('grass', 'gis', 'modules') # doctest: +SKIP
- grass
- gis
- modules
+ >>> f('grass', 'gis', 'modules') # doctest: +SKIP
+ grass
+ gis
+ modules
- or we can define a new list: ::
+ or we can define a new list:
- >>> words = ['grass', 'gis', 'modules'] # doctest: +SKIP
- >>> f(*words) # doctest: +SKIP
- grass
- gis
- modules
+ >>> words = ['grass', 'gis', 'modules'] # doctest: +SKIP
+ >>> f(*words) # doctest: +SKIP
+ grass
+ gis
+ modules
we can do the same with keyword arguments, rewrite the above function: ::
@@ -312,27 +312,26 @@
for key, value in kargs.items():
print "%s = %r" % (key, value)
- now we can use the new function, with: ::
+ now we can use the new function, with:
- >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
- ... # doctest: +SKIP
- grass
- gis
- modules
- os = 'linux'
- language = 'python'
+ >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python')
+ ... # doctest: +SKIP
+ grass
+ gis
+ modules
+ os = 'linux'
+ language = 'python'
or, as before we can, define a dictionary and give the dictionary to
- the function, like: ::
+ the function, like:
- >>> keywords = {'os' : 'linux', 'language' : 'python'}
- ... # doctest: +SKIP
- >>> f(*words, **keywords) # doctest: +SKIP
- grass
- gis
- modules
- os = 'linux'
- language = 'python'
+ >>> keywords = {'os' : 'linux', 'language' : 'python'} # doctest: +SKIP
+ >>> f(*words, **keywords) # doctest: +SKIP
+ grass
+ gis
+ modules
+ os = 'linux'
+ language = 'python'
In the Module class we heavily use this language feature to pass arguments
and keyword arguments to the grass module.
Modified: grass/trunk/lib/python/pygrass/raster/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/__init__.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/raster/__init__.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -40,6 +40,7 @@
class RasterRow(RasterAbstractBase):
"""Raster_row_access": Inherits: "Raster_abstract_base" and implements
the default row access of the Rast library.
+
* Implements row access using row id
* The get_row() method must accept a Row object as argument that will
be used for value storage, so no new buffer will be allocated
@@ -53,58 +54,57 @@
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
- (56, 156)
- >>> 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: 56, 156
- proj: 99
- <BLANKLINE>
+ >>> 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
+ (56, 156)
+ >>> 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: 56, 156
+ proj: 99
+ <BLANKLINE>
Each Raster map have an attribute call ``cats`` that allow user
- to interact with the raster categories. ::
+ to interact with the raster categories.
- >>> land = RasterRow('geology')
- >>> land.open()
- >>> land.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
- [('Zml', 1, None),
- ...
- ('Tpyw', 1832, None)]
+ >>> land = RasterRow('geology')
+ >>> land.open()
+ >>> land.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
+ [('Zml', 1, None),
+ ...
+ ('Tpyw', 1832, None)]
- Open a raster map using the *with statement*: ::
+ Open a raster map using the *with statement*:
- >>> 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
+ >>> 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
"""
def __init__(self, name, mapset='', *args, **kargs):
@@ -148,24 +148,23 @@
def open(self, mode=None, mtype=None, overwrite=None):
"""Open the raster if exist or created a new one.
- :param mode: Specify if the map will be open with read or write mode
+ :param str mode: Specify if the map will be open with read or write mode
('r', 'w')
- :type mode: str
- :param type: If a new map is open, specify the type of the map(`CELL`,
+ :param str type: If a new map is open, specify the type of the map(`CELL`,
`FCELL`, `DCELL`)
- :type type: str
- :param overwrite: Use this flag to set the overwrite mode of existing
+ :param bool overwrite: Use this flag to set the overwrite mode of existing
raster maps
- :type overwrite: bool
+ if the map already exist, automatically check the type and set:
- if the map already exist, automatically check the type and set:
* self.mtype
Set all the privite, attributes:
+
* self._fd;
* self._gtype
* self._rows and self._cols
+
"""
self.mode = mode if mode else self.mode
self.mtype = mtype if mtype else self.mtype
@@ -262,6 +261,7 @@
class RasterSegment(RasterAbstractBase):
"""Raster_segment_access": Inherits "Raster_abstract_base" and uses the
segment library for cached randomly reading and writing access.
+
* Implements the [row][col] operator for read and write access using
segement_get() and segment_put() functions internally
* Implements row read and write access with the [row] operator using
@@ -274,6 +274,7 @@
* No mathematical operation like __add__ and stuff for the Raster
object (only for rows), since r.mapcalc is more sophisticated and
faster
+
"""
def __init__(self, name, srows=64, scols=64, maxmem=100,
*args, **kargs):
@@ -475,6 +476,7 @@
"""Raster_cached_narray": Inherits "Raster_abstract_base" and
"numpy.memmap". Its purpose is to allow numpy narray like access to
raster maps without loading the map into the main memory.
+
* Behaves like a numpy array and supports all kind of mathematical
operations: __add__, ...
* Overrides the open and close methods
@@ -593,8 +595,8 @@
def _read(self):
"""!Read raster map into array
- @return 0 on success
- @return non-zero code on failure
+ :return: 0 on success
+ :return: non-zero code on failure
"""
with RasterRow(self.name, self.mapset, mode='r') as rst:
buff = rst[0]
Modified: grass/trunk/lib/python/pygrass/raster/abstract.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/abstract.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/raster/abstract.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -167,6 +167,7 @@
class RasterAbstractBase(object):
"""Raster_abstract_base: The base class from which all sub-classes
inherit. It does not implement any row or map access methods:
+
* Implements raster metadata information access (Type, ...)
* Implements an open method that will be overwritten by the sub-classes
* Implements the close method that might be overwritten by sub-classes
@@ -174,18 +175,19 @@
* Implements get and set region methods
* Implements color, history and category handling
* Renaming, deletion, ...
+
"""
def __init__(self, name, mapset="", *aopen, **kwopen):
"""The constructor need at least the name of the map
- *optional* field is the `mapset`. ::
+ *optional* field is the `mapset`.
- >>> ele = RasterAbstractBase('elevation')
- >>> ele.name
- u'elevation'
- >>> ele.exist()
- True
- >>> ele.mapset
- 'PERMANENT'
+ >>> ele = RasterAbstractBase('elevation')
+ >>> ele.name
+ u'elevation'
+ >>> ele.exist()
+ True
+ >>> ele.mapset
+ 'PERMANENT'
..
"""
@@ -320,11 +322,11 @@
"""Return True if the map already exist, and
set the mapset if were not set.
- call the C function `G_find_raster`. ::
+ call the C function `G_find_raster`.
- >>> ele = RasterAbstractBase('elevation')
- >>> ele.exist()
- True
+ >>> ele = RasterAbstractBase('elevation')
+ >>> ele.exist()
+ True
"""
if self.name:
if self.mapset == '':
@@ -336,11 +338,11 @@
return False
def is_open(self):
- """Return True if the map is open False otherwise. ::
+ """Return True if the map is open False otherwise.
- >>> ele = RasterAbstractBase('elevation')
- >>> ele.is_open()
- False
+ >>> ele = RasterAbstractBase('elevation')
+ >>> ele.is_open()
+ False
"""
return True if self._fd is not None and self._fd >= 0 else False
@@ -365,11 +367,11 @@
return "{name}@{mapset}".format(name=self.name, mapset=self.mapset)
def name_mapset(self, name=None, mapset=None):
- """Return the full name of the Raster. ::
+ """Return the full name of the Raster.
- >>> ele = RasterAbstractBase('elevation')
- >>> ele.name_mapset()
- u'elevation at PERMANENT'
+ >>> ele = RasterAbstractBase('elevation')
+ >>> ele.name_mapset()
+ u'elevation at PERMANENT'
"""
if name is None:
@@ -415,10 +417,7 @@
def get_value(self, point, region=None):
"""This method returns the pixel value of a given pair of coordinates:
- Parameters
- ------------
-
- point = pair of coordinates in tuple object
+ :param point: pair of coordinates in tuple object
"""
if not region:
region = Region()
Modified: grass/trunk/lib/python/pygrass/raster/category.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/category.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/raster/category.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -297,11 +297,9 @@
0.5:1.0:road
1.0:1.5:urban
- :param filename: the name of file with categories rules
- :type filename: str
- :param sep: the separator used to divide values and category
- :type sep: str
- ..
+ :param str filename: the name of file with categories rules
+ :param str sep: the separator used to divide values and category
+
"""
self.reset()
with open(filename, 'r') as f:
@@ -329,11 +327,8 @@
0.5:1.0:road
1.0:1.5:urban
- :param filename: the name of file with categories rules
- :type filename: str
- :param sep: the separator used to divide values and category
- :type sep: str
- ..
+ :param str filename: the name of file with categories rules
+ :param str sep: the separator used to divide values and category
"""
with open(filename, 'w') as f:
cats = []
Modified: grass/trunk/lib/python/pygrass/shell/conversion.py
===================================================================
--- grass/trunk/lib/python/pygrass/shell/conversion.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/shell/conversion.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -17,76 +17,61 @@
vfmt='%s', vdec='', vfun=None):
"""Return a html repr of a dictionary.
- Parameters
- -----------
+ :param dict dic: dictionary or object with `keys` and `items` methods
+ :param keys: iterable objectwith only the keys that we want to display
+ :param str border: could be: "0", "1", etc.
+ :param str kfmt: string to format the key string (i.e. "%r", etc.)
+ :param str kdec: string to decorate the key (i.e. "b", "i", etc.)
+ :param str vfmt: string to format the value string (i.e. "%r", etc.)
+ :param str vdec: string to decorate the value (i.e. "b", "i", etc.)
- dic: dictionary, required
- Dictionary or object with `keys` and `items` methods
- keys: iterable, optional
- Iterable objectwith only the keys that we want to display
- border: string, optional
- Could be: "0", "1", etc.
- kfmt: string, optional
- String to format the key string (i.e. "%r", etc.)
- kdec: string, optional
- String to decorate the key (i.e. "b", "i", etc.)
- vfmt: string, optional
- String to format the value string (i.e. "%r", etc.)
- vdec: string, optional
- String to decorate the value (i.e. "b", "i", etc.)
-
- Examples
- ---------
-
- ::
-
- >>> dic = {'key 0': 0, 'key 1': 1}
- >>> print dict2html(dic)
- <table>
- <tr>
- <td>key 0</td>
- <td>0</td>
- </tr>
- <tr>
- <td>key 1</td>
- <td>1</td>
- </tr>
- </table>
- >>> print dict2html(dic, border="1")
- <table border='1'>
- <tr>
- <td>key 0</td>
- <td>0</td>
- </tr>
- <tr>
- <td>key 1</td>
- <td>1</td>
- </tr>
- </table>
- >>> print dict2html(dic, kdec='b', vfmt='%05d', vdec='i')
- <table>
- <tr>
- <td><b>key 0</b></td>
- <td><i>00000</i></td>
- </tr>
- <tr>
- <td><b>key 1</b></td>
- <td><i>00001</i></td>
- </tr>
- </table>
- >>> dic = {'key 0': (2, 3), 'key 1': (10, 5)}
- >>> print dict2html(dic, kdec='b', vdec='i',
- ... vfun=lambda x: "%d<sup>%.1f</sup>" % x)
- <table>
- <tr>
- <td><b>key 0</b></td>
- <td><i>2<sup>3.0</sup></i></td>
- </tr>
- <tr>
- <td><b>key 1</b></td>
- <td><i>10<sup>5.0</sup></i></td>
- </tr>
- </table>
+ >>> dic = {'key 0': 0, 'key 1': 1}
+ >>> print dict2html(dic)
+ <table>
+ <tr>
+ <td>key 0</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>key 1</td>
+ <td>1</td>
+ </tr>
+ </table>
+ >>> print dict2html(dic, border="1")
+ <table border='1'>
+ <tr>
+ <td>key 0</td>
+ <td>0</td>
+ </tr>
+ <tr>
+ <td>key 1</td>
+ <td>1</td>
+ </tr>
+ </table>
+ >>> print dict2html(dic, kdec='b', vfmt='%05d', vdec='i')
+ <table>
+ <tr>
+ <td><b>key 0</b></td>
+ <td><i>00000</i></td>
+ </tr>
+ <tr>
+ <td><b>key 1</b></td>
+ <td><i>00001</i></td>
+ </tr>
+ </table>
+ >>> dic = {'key 0': (2, 3), 'key 1': (10, 5)}
+ >>> print dict2html(dic, kdec='b', vdec='i',
+ ... vfun=lambda x: "%d<sup>%.1f</sup>" % x)
+ <table>
+ <tr>
+ <td><b>key 0</b></td>
+ <td><i>2<sup>3.0</sup></i></td>
+ </tr>
+ <tr>
+ <td><b>key 1</b></td>
+ <td><i>10<sup>5.0</sup></i></td>
+ </tr>
+ </table>
"""
def fun(x):
return x
Modified: grass/trunk/lib/python/pygrass/vector/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/__init__.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/vector/__init__.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -471,33 +471,31 @@
def read(self, feature_id):
"""Return a geometry object given the feature id.
- :param feature_id: the id of feature to obtain
- :type feature_id: int
+ :param int feature_id: the id of feature to obtain
+ >>> cens = VectorTopo('census')
+ >>> cens.open(mode='r')
+ >>> feature1 = cens.read(0) #doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ ValueError: The index must be >0, 0 given.
+ >>> feature1 = cens.read(1)
+ >>> feature1
+ Boundary(v_id=1)
+ >>> feature1.length()
+ 444.54490917696944
+ >>> cens.read(-1)
+ Centoid(642963.159711, 214994.016279)
+ >>> len(cens)
+ 8920
+ >>> cens.read(8920)
+ Centoid(642963.159711, 214994.016279)
+ >>> cens.read(8921) #doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ IndexError: Index out of range
+ >>> cens.close()
- >>> cens = VectorTopo('census')
- >>> cens.open(mode='r')
- >>> feature1 = cens.read(0) #doctest: +ELLIPSIS
- Traceback (most recent call last):
- ...
- ValueError: The index must be >0, 0 given.
- >>> feature1 = cens.read(1)
- >>> feature1
- Boundary(v_id=1)
- >>> feature1.length()
- 444.54490917696944
- >>> cens.read(-1)
- Centoid(642963.159711, 214994.016279)
- >>> len(cens)
- 8920
- >>> cens.read(8920)
- Centoid(642963.159711, 214994.016279)
- >>> cens.read(8921) #doctest: +ELLIPSIS
- Traceback (most recent call last):
- ...
- IndexError: Index out of range
- >>> cens.close()
-
"""
return read_line(feature_id, self.c_mapinfo, self.table, self.writable,
is2D=not self.is_3D())
Modified: grass/trunk/lib/python/pygrass/vector/basic.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/basic.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/vector/basic.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -14,27 +14,27 @@
class Bbox(object):
"""Instantiate a Bounding Box class that contains
a ctypes pointer to the C struct bound_box, that could be used
- by C GRASS functions. ::
+ by C GRASS functions.
- >>> bbox = Bbox()
- >>> bbox
- Bbox(0.0, 0.0, 0.0, 0.0)
+ >>> bbox = Bbox()
+ >>> bbox
+ Bbox(0.0, 0.0, 0.0, 0.0)
The default parameters are 0. It is possible to set or change
- the parameters later, with: ::
+ the parameters later, with:
- >>> bbox.north = 10
- >>> bbox.south = -10
- >>> bbox.east = -20
- >>> bbox.west = 20
- >>> bbox
- Bbox(10.0, -10.0, -20.0, 20.0)
+ >>> bbox.north = 10
+ >>> bbox.south = -10
+ >>> bbox.east = -20
+ >>> bbox.west = 20
+ >>> bbox
+ Bbox(10.0, -10.0, -20.0, 20.0)
- Or directly istantiate the class with the values, with: ::
+ Or directly istantiate the class with the values, with:
- >>> bbox = Bbox(north=100, south=0, east=0, west=100)
- >>> bbox
- Bbox(100.0, 0.0, 0.0, 100.0)
+ >>> bbox = Bbox(north=100, south=0, east=0, west=100)
+ >>> bbox
+ Bbox(100.0, 0.0, 0.0, 100.0)
..
"""
@@ -351,7 +351,7 @@
with a list of integers
:param ilist: the ilist to append
- :type ilist: a Ilist object
+ :type ilist: a Ilist object
"""
if isinstance(ilist, Ilist):
libvect.Vect_list_append_list(self.c_ilist, ilist.ilist)
@@ -378,36 +378,35 @@
class Cats(object):
"""Instantiate a Category class that contains a ctypes pointer
- to the C line_cats struct. ::
+ to the C line_cats struct.
- >>> cats = Cats()
- >>> for cat in xrange(100, 110): cats.set(cat, layer=cat-50)
- >>> cats.n_cats
- 10
- >>> cats.cat
- [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
- >>> cats.layer
- [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
- >>> cats.get() # default layer is 1
- (-1, 0)
- >>> cats.get(50)
- (100, 1)
- >>> cats.get(51)
- (101, 1)
- >>> cats.set(1001, 52)
- >>> cats.cat
- [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 1001]
- >>> cats.layer
- [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 52]
- >>> cats.get(52)
- (102, 2)
- >>> cats.reset()
- >>> cats.layer
- []
- >>> cats.cat
- []
+ >>> cats = Cats()
+ >>> for cat in xrange(100, 110): cats.set(cat, layer=cat-50)
+ >>> cats.n_cats
+ 10
+ >>> cats.cat
+ [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
+ >>> cats.layer
+ [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
+ >>> cats.get() # default layer is 1
+ (-1, 0)
+ >>> cats.get(50)
+ (100, 1)
+ >>> cats.get(51)
+ (101, 1)
+ >>> cats.set(1001, 52)
+ >>> cats.cat
+ [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 1001]
+ >>> cats.layer
+ [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 52]
+ >>> cats.get(52)
+ (102, 2)
+ >>> cats.reset()
+ >>> cats.layer
+ []
+ >>> cats.cat
+ []
-
"""
@property
def layer(self):
@@ -497,25 +496,25 @@
class CatsList(object):
- """::
+ """
- >>> cats_list = CatsList()
- >>> cats_list.min
- []
- >>> cats_list.max
- []
- >>> cats_list.n_ranges
- 0
- >>> cats_list.layer
- 0
- >>> string = "2,3,5-9,20"
- >>> cats_list.from_string(string)
- >>> cats_list.min
- [2, 3, 5, 20]
- >>> cats_list.max
- [2, 3, 9, 20]
- >>> cats_list.n_ranges
- 4
+ >>> cats_list = CatsList()
+ >>> cats_list.min
+ []
+ >>> cats_list.max
+ []
+ >>> cats_list.n_ranges
+ 0
+ >>> cats_list.layer
+ 0
+ >>> string = "2,3,5-9,20"
+ >>> cats_list.from_string(string)
+ >>> cats_list.min
+ [2, 3, 5, 20]
+ >>> cats_list.max
+ [2, 3, 9, 20]
+ >>> cats_list.n_ranges
+ 4
"""
@property
Modified: grass/trunk/lib/python/pygrass/vector/find.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/find.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/vector/find.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -36,39 +36,39 @@
class PointFinder(AbstractFinder):
"""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')
- >>> schools = VectorTopo('schools', 'PERMANENT')
- >>> zipcodes.open('r')
- >>> schools.open('r')
- >>> result = []
- >>> for school in schools:
- ... zipcode = zipcodes.find['by_point'].area(school)
- ... result.append((school.attrs['NAMESHORT'],
- ... zipcode.attrs['ZIPCODE']))
- ...
- >>> result[0]
- (u'SWIFT CREEK', u'RALEIGH 27606')
- >>> result[1]
- (u'BRIARCLIFF', u'CARY 27511')
- >>> result[2]
- (u'FARMINGTON WOODS', u'CARY 27511')
- >>> from grass.pygrass.vector.geometry import Point
- >>> pnt = Point(631213.349291, 224684.900084)
- >>> school = schools.find['by_point'].geo(pnt, maxdist=300.)
- >>> school.attrs['NAMELONG']
- u'ADAMS ELEMENTARY'
- >>> for school in schools.find['by_point'].geos(pnt, maxdist=1000.):
- ... print school.attrs['NAMELONG']
- ...
- CARY HIGH
- EAST CARY MIDDLE SITE
- ADAMS ELEMENTARY
- >>> schools.close()
- >>> zipcodes.close()
+ Find the geomtry features of a vector map that are close to a point.
+
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> zipcodes = VectorTopo('zipcodes', 'PERMANENT')
+ >>> schools = VectorTopo('schools', 'PERMANENT')
+ >>> zipcodes.open('r')
+ >>> schools.open('r')
+ >>> result = []
+ >>> for school in schools:
+ ... zipcode = zipcodes.find['by_point'].area(school)
+ ... result.append((school.attrs['NAMESHORT'],
+ ... zipcode.attrs['ZIPCODE']))
+ ...
+ >>> result[0]
+ (u'SWIFT CREEK', u'RALEIGH 27606')
+ >>> result[1]
+ (u'BRIARCLIFF', u'CARY 27511')
+ >>> result[2]
+ (u'FARMINGTON WOODS', u'CARY 27511')
+ >>> from grass.pygrass.vector.geometry import Point
+ >>> pnt = Point(631213.349291, 224684.900084)
+ >>> school = schools.find['by_point'].geo(pnt, maxdist=300.)
+ >>> school.attrs['NAMELONG']
+ u'ADAMS ELEMENTARY'
+ >>> for school in schools.find['by_point'].geos(pnt, maxdist=1000.):
+ ... print school.attrs['NAMELONG']
+ ...
+ CARY HIGH
+ EAST CARY MIDDLE SITE
+ ADAMS ELEMENTARY
+ >>> schools.close()
+ >>> zipcodes.close()
"""
def __init__(self, c_mapinfo, table=None, writable=False):
"""Find geometry feature around a point.
Modified: grass/trunk/lib/python/pygrass/vector/geometry.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/geometry.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/vector/geometry.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -26,39 +26,43 @@
def read_WKT(string):
"""Read the string and return a geometry object
- WKT:
- POINT(0 0)
- LINESTRING(0 0,1 1,1 2)
- POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
- MULTIPOINT(0 0,1 2)
- MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
- MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)),
- ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
- GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
+ **WKT**:
+ ::
+ POINT(0 0)
+ LINESTRING(0 0,1 1,1 2)
+ POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
+ MULTIPOINT(0 0,1 2)
+ MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4))
+ MULTIPOLYGON(((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1)),
+ ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
+ GEOMETRYCOLLECTION(POINT(2 3),LINESTRING(2 3,3 4))
- EWKT:
- POINT(0 0 0) -- XYZ
- SRID=32632;POINT(0 0) -- XY with SRID
- POINTM(0 0 0) -- XYM
- POINT(0 0 0 0) -- XYZM
- SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID
- MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
- POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
- MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),
- (1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),
- ((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
- GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
- MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
- POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
- ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
- ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
- ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
- ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
- ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
- TRIANGLE ((0 0, 0 9, 9 0, 0 0))
- TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
+ **EWKT**:
+ ::
+
+ POINT(0 0 0) -- XYZ
+ SRID=32632;POINT(0 0) -- XY with SRID
+ POINTM(0 0 0) -- XYM
+ POINT(0 0 0 0) -- XYZM
+ SRID=4326;MULTIPOINTM(0 0 0,1 2 1) -- XYM with SRID
+ MULTILINESTRING((0 0 0,1 1 0,1 2 1),(2 3 1,3 2 1,5 4 1))
+ POLYGON((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),(1 1 0,2 1 0,2 2 0,1 2 0,1 1 0))
+ MULTIPOLYGON(((0 0 0,4 0 0,4 4 0,0 4 0,0 0 0),
+ (1 1 0,2 1 0,2 2 0,1 2 0,1 1 0)),
+ ((-1 -1 0,-1 -2 0,-2 -2 0,-2 -1 0,-1 -1 0)))
+ GEOMETRYCOLLECTIONM( POINTM(2 3 9), LINESTRINGM(2 3 4, 3 4 5) )
+ MULTICURVE( (0 0, 5 5), CIRCULARSTRING(4 0, 4 4, 8 4) )
+ POLYHEDRALSURFACE( ((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),
+ ((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),
+ ((0 0 0, 1 0 0, 1 0 1, 0 0 1, 0 0 0)),
+ ((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),
+ ((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),
+ ((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)) )
+ TRIANGLE ((0 0, 0 9, 9 0, 0 0))
+ TIN( ((0 0 0, 0 0 1, 0 1 0, 0 0 0)), ((0 0 0, 0 1 0, 1 1 0, 0 0 0)) )
+
"""
for regexp, obj in WKT.items():
if re.match(regexp, string):
@@ -72,12 +76,12 @@
def intersects(lineA, lineB, with_z=False):
- """Return a list of points ::
+ """Return a list of points
- >>> lineA = Line([(0, 0), (4, 0)])
- >>> lineB = Line([(2, 2), (2, -2)])
- >>> intersects(lineA, lineB)
- Line([Point(2.000000, 0.000000)])
+ >>> lineA = Line([(0, 0), (4, 0)])
+ >>> lineB = Line([(2, 2), (2, -2)])
+ >>> intersects(lineA, lineB)
+ Line([Point(2.000000, 0.000000)])
"""
line = Line()
if libvect.Vect_line_get_intersections(lineA.c_points, lineB.c_points,
@@ -92,21 +96,20 @@
def get_xyz(pnt):
- """Return a tuple with: x, y, z. ::
+ """Return a tuple with: x, y, z.
- >>> pnt = Point(0, 0)
- >>> get_xyz(pnt)
- (0.0, 0.0, 0.0)
- >>> get_xyz((1, 1))
- (1, 1, 0.0)
- >>> get_xyz((1, 1, 2))
- (1, 1, 2)
- >>> get_xyz((1, 1, 2, 2)) #doctest: +ELLIPSIS
- Traceback (most recent call last):
- ...
- ValueError: The the format of the point is not supported: (1, 1, 2, 2)
+ >>> pnt = Point(0, 0)
+ >>> get_xyz(pnt)
+ (0.0, 0.0, 0.0)
+ >>> get_xyz((1, 1))
+ (1, 1, 0.0)
+ >>> get_xyz((1, 1, 2))
+ (1, 1, 2)
+ >>> get_xyz((1, 1, 2, 2)) #doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ ValueError: The the format of the point is not supported: (1, 1, 2, 2)
- ..
"""
if isinstance(pnt, Point):
if pnt.is2D:
@@ -147,17 +150,16 @@
doc="Set and obtain cat value")
def __getitem__(self, key):
- """Return the value stored in the attribute table. ::
+ """Return the value stored in the attribute table.
- >>> from grass.pygrass.vector import VectorTopo
- >>> schools = VectorTopo('schools')
- >>> schools.open('r')
- >>> school = schools[1]
- >>> attrs = Attrs(school.cat, schools.table)
- >>> attrs['TAG']
- u'568'
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> schools = VectorTopo('schools')
+ >>> schools.open('r')
+ >>> school = schools[1]
+ >>> attrs = Attrs(school.cat, schools.table)
+ >>> attrs['TAG']
+ u'568'
-
"""
#SELECT {cols} FROM {tname} WHERE {condition};
try:
@@ -171,20 +173,20 @@
return results[0] if len(results) == 1 else results
def __setitem__(self, key, value):
- """Set value of a given column of a table attribute. ::
+ """Set value of a given column of a table attribute.
- >>> from grass.pygrass.vector import VectorTopo
- >>> from grass.pygrass.functions import copy, remove
- >>> copy('schools', 'myschools', 'vect')
- >>> schools = VectorTopo('myschools')
- >>> schools.open('r')
- >>> school = schools[1]
- >>> attrs = Attrs(school.cat, schools.table, True)
- >>> attrs['TAG'] = 'New Label'
- >>> attrs['TAG']
- u'New Label'
- >>> attrs.table.conn.close()
- >>> remove('myschools','vect')
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> from grass.pygrass.functions import copy, remove
+ >>> copy('schools', 'myschools', 'vect')
+ >>> schools = VectorTopo('myschools')
+ >>> schools.open('r')
+ >>> school = schools[1]
+ >>> attrs = Attrs(school.cat, schools.table, True)
+ >>> attrs['TAG'] = 'New Label'
+ >>> attrs['TAG']
+ u'New Label'
+ >>> attrs.table.conn.close()
+ >>> remove('myschools','vect')
"""
if self.writable:
#UPDATE {tname} SET {new_col} = {old_col} WHERE {condition}
@@ -194,8 +196,7 @@
condition=self.cond))
#self.table.conn.commit()
else:
- str_err = "You can only read the attributes if the map is \
-in another mapset"
+ str_err = "You can only read the attributes if the map is in another mapset"
raise GrassError(str_err)
def __dict__(self):
@@ -1252,9 +1253,6 @@
def perimeter(self):
"""Return the perimeter value of an Isle.
- ::
- double Vect_area_perimeter()
-
"""
border = self.points()
return libvect.Vect_area_perimeter(border.c_points)
@@ -1297,30 +1295,31 @@
.. warning::
Not implemented yet.
+
"""
pass
class Area(Geo):
"""
- 'Vect_build_line_area',
- 'Vect_find_area',
- 'Vect_get_area_box',
- 'Vect_get_area_points_geos',
- 'Vect_get_centroid_area',
+ Vect_build_line_area,
+ Vect_find_area,
+ Vect_get_area_box,
+ Vect_get_area_points_geos,
+ Vect_get_centroid_area,
- 'Vect_get_isle_area',
- 'Vect_get_line_areas',
- 'Vect_get_num_areas',
- 'Vect_get_point_in_area',
- 'Vect_isle_find_area',
- 'Vect_point_in_area',
- 'Vect_point_in_area_outer_ring',
+ Vect_get_isle_area,
+ Vect_get_line_areas,
+ Vect_get_num_areas,
+ Vect_get_point_in_area,
+ Vect_isle_find_area,
+ Vect_point_in_area,
+ Vect_point_in_area_outer_ring,
- 'Vect_read_area_geos',
- 'Vect_remove_small_areas',
- 'Vect_select_areas_by_box',
- 'Vect_select_areas_by_polygon']
+ Vect_read_area_geos,
+ Vect_remove_small_areas,
+ Vect_select_areas_by_box,
+ Vect_select_areas_by_polygon
"""
# geometry type
gtype = libvect.GV_AREA
@@ -1389,8 +1388,7 @@
def area(self):
"""Returns area of area without areas of isles.
- double Vect_get_area_area (const struct Map_info *Map, int area)
-
+ double Vect_get_area_area (const struct Map_info \*Map, int area)
"""
return libvect.Vect_get_area_area(self.c_mapinfo, self.id)
@@ -1451,8 +1449,8 @@
def boundaries(self, ilist=False):
"""Creates list of boundaries for given area.
- int Vect_get_area_boundaries(const struct Map_info *Map,
- int area, struct ilist *List)
+ int Vect_get_area_boundaries(const struct Map_info \*Map,
+ int area, struct ilist \*List)
"""
ilst = Ilist()
libvect.Vect_get_area_boundaries(self.c_mapinfo, self.id,
@@ -1474,7 +1472,7 @@
def get_first_cat(self):
"""Find FIRST category of given field and area.
- int Vect_get_area_cat(const struct Map_info *Map, int area, int field)
+ int Vect_get_area_cat(const struct Map_info \*Map, int area, int field)
"""
pass
@@ -1494,7 +1492,7 @@
def perimeter(self):
"""Calculate area perimeter.
- double Vect_area_perimeter (const struct line_pnts *Points)
+ :return: double Vect_area_perimeter (const struct line_pnts \*Points)
"""
border = self.get_points()
Modified: grass/trunk/lib/python/pygrass/vector/table.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/table.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/pygrass/vector/table.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -4,8 +4,6 @@
@author: pietro
-
-
"""
from __future__ import (nested_scopes, generators, division, absolute_import,
with_statement, print_function, unicode_literals)
@@ -38,7 +36,7 @@
def get_path(path):
"""Return the full path to the database; replacing environment variable
- with real values ::
+ with real values
>>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
>>> new_path = get_path(path)
@@ -60,19 +58,18 @@
class Filters(object):
- """Help user to build a simple sql query. ::
+ """Help user to build a simple sql query.
- >>> filter = Filters('table')
- >>> filter.get_sql()
- u'SELECT * FROM table;'
- >>> filter.where("area<10000").get_sql()
- u'SELECT * FROM table WHERE area<10000;'
- >>> filter.select("cat", "area").get_sql()
- u'SELECT cat, area FROM table WHERE area<10000;'
- >>> filter.order_by("area").limit(10).get_sql()
- u'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
+ >>> filter = Filters('table')
+ >>> filter.get_sql()
+ u'SELECT * FROM table;'
+ >>> filter.where("area<10000").get_sql()
+ u'SELECT * FROM table WHERE area<10000;'
+ >>> filter.select("cat", "area").get_sql()
+ u'SELECT cat, area FROM table WHERE area<10000;'
+ >>> filter.order_by("area").limit(10).get_sql()
+ u'SELECT cat, area FROM table WHERE area<10000 ORDER BY area LIMIT 10;'
- ..
"""
def __init__(self, tname):
self.tname = tname
@@ -168,24 +165,23 @@
It is possible to instantiate a Columns object given the table name and
the database connection.
- For a sqlite table: ::
+ For a sqlite table:
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> cols_sqlite = Columns('census',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.tname
- u'census'
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> cols_sqlite = Columns('census',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.tname
+ u'census'
- For a postgreSQL table: ::
+ For a postgreSQL table:
- >>> import psycopg2 as pg #doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
- >>> cols_pg.tname #doctest: +SKIP
- 'boundary_municp_pg' #doctest: +SKIP
+ >>> import psycopg2 as pg #doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
+ >>> cols_pg.tname #doctest: +SKIP
+ 'boundary_municp_pg' #doctest: +SKIP
- ..
"""
def __init__(self, tname, connection, key='cat'):
self.tname = tname
@@ -236,21 +232,20 @@
__hash__ = object.__hash__
def is_pg(self):
- """Return True if is a psycopg connection. ::
+ """Return True if is a psycopg connection.
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> cols_sqlite = Columns('census',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.is_pg()
- False
- >>> import psycopg2 as pg #doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
- >>> cols_pg.is_pg() #doctest: +SKIP
- True
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> cols_sqlite = Columns('census',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.is_pg()
+ False
+ >>> import psycopg2 as pg #doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
+ >>> cols_pg.is_pg() #doctest: +SKIP
+ True
- ..
"""
return hasattr(self.conn, 'xid')
@@ -293,19 +288,19 @@
def sql_descr(self, remove=None):
"""Return a string with description of columns.
- Remove it is used to remove a columns.::
+ Remove it is used to remove a columns.
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> cols_sqlite = Columns('census',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS
- u'cat integer, OBJECTID integer, AREA double precision, ...'
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
- >>> cols_pg.sql_descr() # doctest: +ELLIPSIS +SKIP
- 'cat int4, objectid int4, area float8, perimeter float8, ...'
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> cols_sqlite = Columns('census',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS
+ u'cat integer, OBJECTID integer, AREA double precision, ...'
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
+ >>> cols_pg.sql_descr() # doctest: +ELLIPSIS +SKIP
+ 'cat int4, objectid int4, area float8, perimeter float8, ...'
"""
if remove:
return ', '.join(['%s %s' % (key, val) for key, val in self.items()
@@ -315,43 +310,39 @@
for key, val in self.items()])
def types(self):
- """Return a list with the column types. ::
+ """Return a list with the column types.
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> cols_sqlite = Columns('census',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.types() # doctest: +ELLIPSIS
- [u'integer', u'integer', ...]
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
- >>> cols_pg.types() # doctest: +ELLIPSIS +SKIP
- ['int4', 'int4', 'float8', 'float8', 'float8', ...]
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> cols_sqlite = Columns('census',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.types() # doctest: +ELLIPSIS
+ [u'integer', u'integer', ...]
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
+ >>> cols_pg.types() # doctest: +ELLIPSIS +SKIP
+ ['int4', 'int4', 'float8', 'float8', 'float8', ...]
-
- ..
"""
return self.odict.values()
def names(self, remove=None, unicod=True):
"""Return a list with the column names.
- Remove it is used to remove a columns.::
+ Remove it is used to remove a columns.
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> cols_sqlite = Columns('census',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.names() # doctest: +ELLIPSIS
- [u'cat', u'OBJECTID', u'AREA', u'PERIMETER', ...]
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg', # doctest: +SKIP
- ... pg.connect('host=localhost dbname=grassdb'))
- >>> cols_pg.names() # doctest: +ELLIPSIS +SKIP
- ['cat', 'objectid', 'area', 'perimeter', ...]
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> cols_sqlite = Columns('census',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.names() # doctest: +ELLIPSIS
+ [u'cat', u'OBJECTID', u'AREA', u'PERIMETER', ...]
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg', # doctest: +SKIP
+ ... pg.connect('host=localhost dbname=grassdb'))
+ >>> cols_pg.names() # doctest: +ELLIPSIS +SKIP
+ ['cat', 'objectid', 'area', 'perimeter', ...]
-
- ..
"""
if remove:
nams = self.odict.keys()
@@ -364,21 +355,20 @@
return [str(name) for name in nams]
def items(self):
- """Return a list of tuple with column name and column type. ::
+ """Return a list of tuple with column name and column type.
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> cols_sqlite = Columns('census',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.items() # doctest: +ELLIPSIS
- [(u'cat', u'integer'), ...]
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
- >>> cols_pg.items() # doctest: +ELLIPSIS +SKIP
- [('cat', 'int4'), ('objectid', 'int4'), ('area', 'float8'), ...]
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> cols_sqlite = Columns('census',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.items() # doctest: +ELLIPSIS
+ [(u'cat', u'integer'), ...]
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
+ >>> cols_pg.items() # doctest: +ELLIPSIS +SKIP
+ [('cat', 'int4'), ('objectid', 'int4'), ('area', 'float8'), ...]
- ..
"""
return self.odict.items()
@@ -389,26 +379,24 @@
:type col_name: str
:param col_type: the tipe of column to add
:type col_type: str
- ::
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
- >>> copy('census','mycensus','vect')
- >>> cols_sqlite = Columns('mycensus',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.add(['n_pizza'], ['INT'])
- >>> 'n_pizza' in cols_sqlite
- True
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
- >>> cols_pg.add('n_pizza', 'INT') # doctest: +SKIP
- >>> 'n_pizza' in cols_pg # doctest: +SKIP
- True
- >>> remove('mycensus', 'vect')
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
+ >>> from grass.pygrass.functions import copy, remove
+ >>> copy('census','mycensus','vect')
+ >>> cols_sqlite = Columns('mycensus',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.add(['n_pizza'], ['INT'])
+ >>> 'n_pizza' in cols_sqlite
+ True
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP
+ >>> cols_pg.add('n_pizza', 'INT') # doctest: +SKIP
+ >>> 'n_pizza' in cols_pg # doctest: +SKIP
+ True
+ >>> remove('mycensus', 'vect')
- ..
"""
def check_col(col_type):
"""Check the column type if it is supported by GRASS
@@ -450,34 +438,32 @@
:type old_name: str
:param new_name: the name of new column
:type new_name: str
- ::
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
- >>> copy('census','mycensus','vect')
- >>> cols_sqlite = Columns('mycensus',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.add(['n_pizza'], ['INT'])
- >>> 'n_pizza' in cols_sqlite
- True
- >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS
- >>> 'n_pizza' in cols_sqlite
- False
- >>> 'n_pizzas' in cols_sqlite
- True
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
+ >>> from grass.pygrass.functions import copy, remove
+ >>> copy('census','mycensus','vect')
+ >>> cols_sqlite = Columns('mycensus',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.add(['n_pizza'], ['INT'])
+ >>> 'n_pizza' in cols_sqlite
+ True
+ >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS
+ >>> 'n_pizza' in cols_sqlite
+ False
+ >>> 'n_pizzas' in cols_sqlite
+ True
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
- >>> cols_pg.rename('n_pizza', 'n_pizzas') # doctest: +SKIP
- >>> 'n_pizza' in cols_pg # doctest: +SKIP
- False
- >>> 'n_pizzas' in cols_pg # doctest: +SKIP
- True
- >>> remove('mycensus', 'vect')
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
+ >>> cols_pg.rename('n_pizza', 'n_pizzas') # doctest: +SKIP
+ >>> 'n_pizza' in cols_pg # doctest: +SKIP
+ False
+ >>> 'n_pizzas' in cols_pg # doctest: +SKIP
+ True
+ >>> remove('mycensus', 'vect')
- ..
"""
cur = self.conn.cursor()
if self.is_pg():
@@ -506,31 +492,30 @@
:type col_name: str
:param new_type: the new type of column
:type new_type: str
- ::
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
- >>> copy('census','mycensus','vect')
- >>> cols_sqlite = Columns('mycensus',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.add(['n_pizzas'], ['INT'])
- >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS
- Traceback (most recent call last):
- ...
- DBError: SQLite does not support to cast columns.
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
- >>> cols_pg.cast('n_pizzas', 'float8') # doctest: +SKIP
- >>> cols_pg['n_pizzas'] # doctest: +SKIP
- 'float8'
- >>> remove('mycensus', 'vect')
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
+ >>> from grass.pygrass.functions import copy, remove
+ >>> copy('census','mycensus','vect')
+ >>> cols_sqlite = Columns('mycensus',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.add(['n_pizzas'], ['INT'])
+ >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS
+ Traceback (most recent call last):
+ ...
+ DBError: SQLite does not support to cast columns.
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
+ >>> cols_pg.cast('n_pizzas', 'float8') # doctest: +SKIP
+ >>> cols_pg['n_pizzas'] # doctest: +SKIP
+ 'float8'
+ >>> remove('mycensus', 'vect')
- .. warning ::
+ .. warning ::
- It is not possible to cast a column with sqlite
- ..
+ It is not possible to cast a column with sqlite
+
"""
if self.is_pg():
cur = self.conn.cursor()
@@ -548,27 +533,25 @@
:param col_name: the name of column to remove
:type col_name: str
- ::
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
- >>> from grass.pygrass.functions import copy, remove
- >>> copy('census','mycensus','vect')
- >>> cols_sqlite = Columns('mycensus',
- ... sqlite3.connect(get_path(path)))
- >>> cols_sqlite.drop('CHILD') # doctest: +ELLIPSIS
- >>> 'CHILD' in cols_sqlite
- False
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
+ >>> from grass.pygrass.functions import copy, remove
+ >>> copy('census','mycensus','vect')
+ >>> cols_sqlite = Columns('mycensus',
+ ... sqlite3.connect(get_path(path)))
+ >>> cols_sqlite.drop('CHILD') # doctest: +ELLIPSIS
+ >>> 'CHILD' in cols_sqlite
+ False
- >>> import psycopg2 as pg # doctest: +SKIP
- >>> cols_pg = Columns('boundary_municp_pg',
- ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
- >>> cols_pg.drop('CHILD') # doctest: +SKIP
- >>> 'CHILD' in cols_pg # doctest: +SKIP
- False
- >>> remove('mycensus','vect')
+ >>> import psycopg2 as pg # doctest: +SKIP
+ >>> cols_pg = Columns('boundary_municp_pg',
+ ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP
+ >>> cols_pg.drop('CHILD') # doctest: +SKIP
+ >>> 'CHILD' in cols_pg # doctest: +SKIP
+ False
+ >>> remove('mycensus','vect')
- ..
"""
cur = self.conn.cursor()
if self.is_pg():
@@ -592,50 +575,48 @@
"""Define a Link between vector map and the attributes table.
It is possible to define a Link object or given all the information
- (layer, name, table name, key, database, driver): ::
+ (layer, name, table name, key, database, driver):
- >>> link = Link(1, 'link0', 'census', 'cat',
- ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
- >>> link.layer
- 1
- >>> link.name
- 'link0'
- >>> link.table_name
- 'census'
- >>> link.key
- 'cat'
- >>> link.database
- '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> link.driver
- 'sqlite'
- >>> link
- Link(1, link0, sqlite)
+ >>> link = Link(1, 'link0', 'census', 'cat',
+ ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite')
+ >>> link.layer
+ 1
+ >>> link.name
+ 'link0'
+ >>> link.table_name
+ 'census'
+ >>> link.key
+ 'cat'
+ >>> link.database
+ '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> link.driver
+ 'sqlite'
+ >>> link
+ Link(1, link0, sqlite)
- It is possible to change parameters with: ::
+ It is possible to change parameters with:
- >>> link.driver = 'pg' # doctest: +SKIP
- >>> link.driver # doctest: +SKIP
- 'pg'
- >>> link.driver = 'postgres' # doctest: +ELLIPSIS +SKIP
- Traceback (most recent call last):
- ...
- TypeError: Driver not supported, use: sqlite, pg.
- >>> link.driver # doctest: +SKIP
- 'pg'
- >>> link.number = 0 # doctest: +ELLIPSIS +SKIP
- Traceback (most recent call last):
- ...
- TypeError: Number must be positive and greater than 0.
+ >>> link.driver = 'pg' # doctest: +SKIP
+ >>> link.driver # doctest: +SKIP
+ 'pg'
+ >>> link.driver = 'postgres' # doctest: +ELLIPSIS +SKIP
+ Traceback (most recent call last):
+ ...
+ TypeError: Driver not supported, use: sqlite, pg.
+ >>> link.driver # doctest: +SKIP
+ 'pg'
+ >>> link.number = 0 # doctest: +ELLIPSIS +SKIP
+ Traceback (most recent call last):
+ ...
+ TypeError: Number must be positive and greater than 0.
Or given a c_fieldinfo object that is a ctypes pointer to the field_info C
struct. ::
- >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info()))
+ >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info()))
-
- ..
"""
def _get_layer(self):
return self.c_fieldinfo.contents.number
@@ -742,22 +723,21 @@
__hash__ = object.__hash__
def connection(self):
- """Return a connection object. ::
+ """Return a connection object.
- >>> link = Link(1, 'link0', 'census', 'cat',
- ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
- ... 'sqlite')
- >>> conn = link.connection()
- >>> cur = conn.cursor()
- >>> cur.execute("SELECT cat,TOTAL_POP,PERIMETER FROM %s" %
- ... link.table_name) # doctest: +ELLIPSIS
- <sqlite3.Cursor object at ...>
- >>> cur.fetchone()
- (1, 44, 757.669)
- >>> cur.close()
- >>> conn.close()
+ >>> link = Link(1, 'link0', 'census', 'cat',
+ ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
+ ... 'sqlite')
+ >>> conn = link.connection()
+ >>> cur = conn.cursor()
+ >>> cur.execute("SELECT cat,TOTAL_POP,PERIMETER FROM %s" %
+ ... link.table_name) # doctest: +ELLIPSIS
+ <sqlite3.Cursor object at ...>
+ >>> cur.fetchone()
+ (1, 44, 757.669)
+ >>> cur.close()
+ >>> conn.close()
- ...
"""
if self.driver == 'sqlite':
import sqlite3
@@ -786,38 +766,36 @@
raise TypeError(str_err)
def table(self):
- """Return a Table object. ::
+ """Return a Table object.
- >>> link = Link(1, 'link0', 'census', 'cat',
- ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
- ... 'sqlite')
- >>> table = link.table()
- >>> table.filters.select('cat', 'TOTAL_POP', 'PERIMETER')
- Filters(u'SELECT cat, TOTAL_POP, PERIMETER FROM census;')
- >>> cur = table.execute()
- >>> cur.fetchone()
- (1, 44, 757.669)
- >>> cur.close()
+ >>> link = Link(1, 'link0', 'census', 'cat',
+ ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
+ ... 'sqlite')
+ >>> table = link.table()
+ >>> table.filters.select('cat', 'TOTAL_POP', 'PERIMETER')
+ Filters(u'SELECT cat, TOTAL_POP, PERIMETER FROM census;')
+ >>> cur = table.execute()
+ >>> cur.fetchone()
+ (1, 44, 757.669)
+ >>> cur.close()
- ..
"""
return Table(self.table_name, self.connection(), self.key)
def info(self):
- """Print information of the link. ::
+ """Print information of the link.
- >>> link = Link(1, 'link0', 'census', 'cat',
- ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
- ... 'sqlite')
- >>> link.info()
- layer: 1
- name: link0
- table: census
- key: cat
- database: $GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db
- driver: sqlite
+ >>> link = Link(1, 'link0', 'census', 'cat',
+ ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
+ ... 'sqlite')
+ >>> link.info()
+ layer: 1
+ name: link0
+ table: census
+ key: cat
+ database: $GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db
+ driver: sqlite
- ..
"""
print("layer: ", self.layer)
print("name: ", self.name)
@@ -828,21 +806,20 @@
class DBlinks(object):
- """Interface containing link to the table DB. ::
+ """Interface containing link to the table DB.
- >>> from grass.pygrass.vector import VectorTopo
- >>> cens = VectorTopo('census')
- >>> cens.open(mode='r')
- >>> dblinks = DBlinks(cens.c_mapinfo)
- >>> dblinks
- DBlinks([Link(1, census, sqlite)])
- >>> dblinks[0]
- Link(1, census, sqlite)
- >>> dblinks['census']
- Link(1, census, sqlite)
- >>> cens.close()
+ >>> from grass.pygrass.vector import VectorTopo
+ >>> cens = VectorTopo('census')
+ >>> cens.open(mode='r')
+ >>> dblinks = DBlinks(cens.c_mapinfo)
+ >>> dblinks
+ DBlinks([Link(1, census, sqlite)])
+ >>> dblinks[0]
+ Link(1, census, sqlite)
+ >>> dblinks['census']
+ Link(1, census, sqlite)
+ >>> cens.close()
- ..
"""
def __init__(self, c_mapinfo):
self.c_mapinfo = c_mapinfo
@@ -965,22 +942,21 @@
class Table(object):
- """::
+ """
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> tab_sqlite = Table(name='census',
- ... connection=sqlite3.connect(get_path(path)))
- >>> tab_sqlite.name
- u'census'
- >>> import psycopg2 # doctest: +SKIP
- >>> tab_pg = Table('boundary_municp_pg',
- ... psycopg2.connect('host=localhost dbname=grassdb',
- ... 'pg')) # doctest: +SKIP
- >>> tab_pg.columns # doctest: +ELLIPSIS +SKIP
- Columns([('cat', 'int4'), ...])
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> tab_sqlite = Table(name='census',
+ ... connection=sqlite3.connect(get_path(path)))
+ >>> tab_sqlite.name
+ u'census'
+ >>> import psycopg2 # doctest: +SKIP
+ >>> tab_pg = Table('boundary_municp_pg',
+ ... psycopg2.connect('host=localhost dbname=grassdb',
+ ... 'pg')) # doctest: +SKIP
+ >>> tab_pg.columns # doctest: +ELLIPSIS +SKIP
+ Columns([('cat', 'int4'), ...])
- ..
"""
def _get_name(self):
"""Private method to return the name of table"""
@@ -1012,16 +988,15 @@
self.filters = Filters(self.name)
def __repr__(self):
- """::
+ """
- >>> import sqlite3
- >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
- >>> tab_sqlite = Table(name='census',
- ... connection=sqlite3.connect(get_path(path)))
- >>> tab_sqlite
- Table(u'census')
+ >>> import sqlite3
+ >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+ >>> tab_sqlite = Table(name='census',
+ ... connection=sqlite3.connect(get_path(path)))
+ >>> tab_sqlite
+ Table(u'census')
- ..
"""
return "Table(%r)" % (self.name)
@@ -1111,9 +1086,9 @@
def exist(self, cursor=None):
"""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
+ of connection table object
"""
cur = cursor if cursor else self.conn.cursor()
return table_exist(cur, self.name)
@@ -1125,7 +1100,7 @@
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
+ of connection table object
:type cursor: Cursor object
:param many: True to run executemany function
:type many: bool
Modified: grass/trunk/lib/python/script/db.py
===================================================================
--- grass/trunk/lib/python/script/db.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/script/db.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -1,7 +1,4 @@
-"""@package grass.script.db
-
- at brief GRASS Python scripting module (database functions)
-
+"""
Database related functions to be used in Python scripts.
Usage:
@@ -28,7 +25,7 @@
def db_describe(table, **args):
"""Return the list of columns for a database table
- (interface to `db.describe -c'). Example:
+ (interface to `db.describe -c`). Example:
>>> run_command('g.copy', vect='firestations,myfirestations')
0
@@ -94,7 +91,7 @@
def db_connection():
"""Return the current database connection parameters
- (interface to `db.connect -g'). Example:
+ (interface to `db.connect -g`). Example:
>>> db_connection()
{'group': '', 'schema': '', 'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'}
Modified: grass/trunk/lib/python/script/raster.py
===================================================================
--- grass/trunk/lib/python/script/raster.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/script/raster.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -1,7 +1,4 @@
-"""@package grass.script.raster
-
- at brief GRASS Python scripting module (raster functions)
-
+"""
Raster related functions to be used in Python scripts.
Usage:
@@ -32,7 +29,7 @@
def raster_history(map):
"""Set the command history for a raster map to the command used to
- invoke the script (interface to `r.support').
+ invoke the script (interface to `r.support`).
:param str map: map name
@@ -52,7 +49,7 @@
def raster_info(map):
"""Return information about a raster map (interface to
- `r.info -gre'). Example:
+ `r.info -gre`). Example:
>>> raster_info('elevation') # doctest: +ELLIPSIS
{'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
Modified: grass/trunk/lib/python/script/task.py
===================================================================
--- grass/trunk/lib/python/script/task.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/script/task.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -30,17 +30,15 @@
class grassTask:
- """This class holds the structures needed for filling by the
- parser
+ """This class holds the structures needed for filling by the parser
Parameter blackList is a dictionary with fixed structure, eg.
::
- blackList = {'items' : {'d.legend' : { 'flags' : ['m'], 'params' : [] }},
- 'enabled': True}
+ blackList = {'items' : {'d.legend' : { 'flags' : ['m'], 'params' : [] }},
+ 'enabled': True}
-
:param str path: full path
:param blackList: hide some options in the GUI (dictionary)
"""
Modified: grass/trunk/lib/python/script/utils.py
===================================================================
--- grass/trunk/lib/python/script/utils.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/script/utils.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -150,7 +150,7 @@
def parse_key_val(s, sep='=', dflt=None, val_type=None, vsep=None):
"""Parse a string into a dictionary, where entries are separated
- by newlines and the key and value are separated by `sep' (default: `=')
+ by newlines and the key and value are separated by `sep` (default: `=`)
>>> parse_key_val('min=20\\nmax=50') == {'min': '20', 'max': '50'}
True
Modified: grass/trunk/lib/python/script/vector.py
===================================================================
--- grass/trunk/lib/python/script/vector.py 2014-09-14 13:37:13 UTC (rev 61943)
+++ grass/trunk/lib/python/script/vector.py 2014-09-14 13:47:40 UTC (rev 61944)
@@ -28,7 +28,7 @@
def vector_db(map, **args):
"""Return the database connection details for a vector map
- (interface to `v.db.connect -g'). Example:
+ (interface to `v.db.connect -g`). Example:
>>> vector_db('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
{1: {'layer': 1, ... 'table': 'geology'}}
@@ -87,8 +87,7 @@
def vector_columns(map, layer=None, getDict=True, **args):
"""Return a dictionary (or a list) of the columns for the
- database table connected to a vector map (interface to `v.info
- -c').
+ database table connected to a vector map (interface to `v.info -c`).
>>> vector_columns('geology', getDict=True) # doctest: +NORMALIZE_WHITESPACE
{'PERIMETER': {'index': 2, 'type': 'DOUBLE PRECISION'}, 'GEOL250_':
@@ -136,7 +135,7 @@
def vector_history(map):
"""Set the command history for a vector map to the command used to
- invoke the script (interface to `v.support').
+ invoke the script (interface to `v.support`).
:param str map: mapname
@@ -146,8 +145,8 @@
def vector_info_topo(map):
- """Return information about a vector map (interface to `v.info
- -t'). Example:
+ """Return information about a vector map (interface to `v.info -t`).
+ Example:
>>> vector_info_topo('geology') # doctest: +NORMALIZE_WHITESPACE
{'lines': 0, 'centroids': 1832, 'boundaries': 3649, 'points': 0,
@@ -168,7 +167,7 @@
def vector_info(map):
"""Return information about a vector map (interface to
- `v.info'). Example:
+ `v.info`). Example:
>>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
{'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917}
More information about the grass-commit
mailing list