[GRASS-SVN] r41773 - grass/branches/develbranch_6/lib/python

svn_grass at osgeo.org svn_grass at osgeo.org
Sat Apr 10 07:31:08 EDT 2010


Author: martinl
Date: 2010-04-10 07:31:07 -0400 (Sat, 10 Apr 2010)
New Revision: 41773

Added:
   grass/branches/develbranch_6/lib/python/array.py
Modified:
   grass/branches/develbranch_6/lib/python/core.py
   grass/branches/develbranch_6/lib/python/db.py
   grass/branches/develbranch_6/lib/python/raster.py
   grass/branches/develbranch_6/lib/python/vector.py
Log:
libpython sync'ed with trunk


Added: grass/branches/develbranch_6/lib/python/array.py
===================================================================
--- grass/branches/develbranch_6/lib/python/array.py	                        (rev 0)
+++ grass/branches/develbranch_6/lib/python/array.py	2010-04-10 11:31:07 UTC (rev 41773)
@@ -0,0 +1,112 @@
+"""!@package grass.script.array
+
+ at brief GRASS Python scripting module
+
+Functions to use GRASS rasters with NumPy.
+
+Usage:
+
+ at code
+from grass.script import array as garray
+...
+ at endcode
+
+(C) 2010 by Glynn Clements and the GRASS Development Team
+This program is free software under the GNU General Public
+License (>=v2). Read the file COPYING that comes with GRASS
+for details.
+
+ at author Glynn Clements
+
+"""
+
+import os
+import numpy
+
+import core as grass
+
+class array(numpy.memmap):
+    def __new__(cls, dtype = numpy.double):
+	reg = grass.region()
+	r = reg['rows']
+	c = reg['cols']
+	shape = (r, c)
+
+	filename = grass.tempfile()
+
+	self = numpy.memmap.__new__(
+	    cls,
+	    filename = filename,
+	    dtype = dtype,
+	    mode = 'w+',
+	    shape = shape)
+
+	self.filename = filename
+	return self
+
+    def _close(self):
+	numpy.memmap._close(self)
+	if isinstance(self, array):
+	    grass.try_remove(self.filename)
+
+    def read(self, mapname, null = None):
+	kind = self.dtype.kind
+	size = self.dtype.itemsize
+
+	if kind == 'f':
+	    flags = 'f'
+	elif kind in 'biu':
+	    flags = 'i'
+	else:
+	    raise ValueError('invalid kind <%s>' % kind)
+
+	if size not in [1,2,4,8]:
+	    raise ValueError('invalid size <%d>' % size)
+
+	return grass.run_command(
+	    'r.out.bin',
+	    flags = flags,
+	    input = mapname,
+	    output = self.filename,
+	    bytes = size,
+	    null = null,
+	    quiet = True)
+	
+
+    def write(self, mapname, title = None, null = None, overwrite = None):
+	kind = self.dtype.kind
+	size = self.dtype.itemsize
+
+	if kind == 'f':
+	    if size == 4:
+		flags = 'f'
+	    elif size == 8:
+		flags = 'd'
+	    else:
+		raise ValueError('invalid FP size <%d>' % size)
+	    size = None
+	elif kind in 'biu':
+	    if size not in [1,2,4]:
+		raise ValueError('invalid integer size <%d>' % size)
+	    flags = None
+	else:
+	    raise ValueError('invalid kind <%s>' % kind)
+
+	reg = grass.region()
+
+	return grass.run_command(
+	    'r.in.bin',
+	    flags = flags,
+	    input = self.filename,
+	    output = mapname,
+	    title = title,
+	    bytes = size,
+	    anull = null,
+	    overwrite = overwrite,
+	    verbose = True,
+	    north = reg['n'],
+	    south = reg['s'],
+	    east  = reg['e'],
+	    west  = reg['w'],
+	    rows  = reg['rows'],
+	    cols  = reg['cols'])


Property changes on: grass/branches/develbranch_6/lib/python/array.py
___________________________________________________________________
Added: svn:mime-type
   + text/x-python
Added: svn:keywords
   + Author Date Id
Added: svn:eol-style
   + native

Modified: grass/branches/develbranch_6/lib/python/core.py
===================================================================
--- grass/branches/develbranch_6/lib/python/core.py	2010-04-10 11:20:06 UTC (rev 41772)
+++ grass/branches/develbranch_6/lib/python/core.py	2010-04-10 11:31:07 UTC (rev 41773)
@@ -494,7 +494,10 @@
     @return dictionary of region values
     """
     s = read_command("g.region", flags='g')
-    return parse_key_val(s, val_type = float)
+    reg = parse_key_val(s, val_type = float)
+    for k in ['rows', 'cols']:
+	reg[k] = int(reg[k])
+    return reg
 
 def use_temp_region():
     """!Copies the current region to a temporary region with "g.region save=",
@@ -774,55 +777,59 @@
     s = start_command(cmd, 'help', stdout = subprocess.PIPE, stderr = subprocess.PIPE)
     out, err = s.communicate()
     
-    # Parameters
-    first, params = err.split('Parameters:')
-    paramlines = params.splitlines()
-    dict = {}
-    for line in paramlines:
+    sections = err.split('\n\n')
+
+    #Description
+    first, desc = sections[0].split(':\n', 1)
+    desclines = desc.splitlines()
+    for line in desclines:
+        line = line.strip()+' '
+    
+    # Keywords
+    first, keywords = sections[1].split(':\n', 1)
+    keylines = keywords.splitlines()
+    list = []
+    list = keywords.strip().split(',')
+    cmdinfo['keywords'] = list
+        
+    cmdinfo['description'] = ''.join(desclines).strip()
+
+    # Usage
+    first, usage = sections[2].split(':\n', 1)
+    usagelines = usage.splitlines()
+    list = []
+    for line in usagelines:        
         line = line.strip()
         if line == '': continue
-        param = line.split(' ',1)[0].strip()
-        pval = line.split(' ',1)[1].strip()
-        dict[param] = pval
+        line = line+' '
+        list.append(line)
         
-    cmdinfo['parameters'] = dict
-    
+    cmdinfo['usage'] = ''.join(list).strip()
+
     # Flags
-    first, flags = first.split('Flags:')
+    first, flags = sections[3].split(':\n', 1)
     flaglines = flags.splitlines()
     dict = {}
     for line in flaglines:
         line = line.strip()
         if line == '': continue
-        flag = line.split(' ',1)[0].strip()
-        fval = line.split(' ',1)[1].strip()
-        dict[flag] = fval
+        item = line.split(' ',1)[0].strip()
+        val = line.split(' ',1)[1].strip()
+        dict[item] = val
         
     cmdinfo['flags'] = dict
     
-    # Usage
-    first, usage = first.split('Usage:')
-    usagelines = usage.splitlines()
-    list = []
-    for line in usagelines:
-        line = line.strip()+' '
+    # Parameters
+    first, params = err.rsplit(':\n', 1)
+    paramlines = params.splitlines()
+    dict = {}
+    for line in paramlines:
+        line = line.strip()
         if line == '': continue
-        list.append(line)
-        
-    cmdinfo['usage'] = ''.join(list).strip()
-    
-    # Keywords
-    first, keywords = first.split('Keywords:')
-    list = []
-    list = keywords.strip().split(',')
-    cmdinfo['keywords'] = list
-        
-    #Description
-    first, desc = first.split('Description:')
-    desclines = desc.splitlines()
-    for line in desclines:
-        line = line.strip()+' '
-        
-    cmdinfo['description'] = ''.join(desclines).strip()
-            
+        item = line.split(' ',1)[0].strip()
+        val = line.split(' ',1)[1].strip()
+        dict[item] = val
+         
+    cmdinfo['parameters'] = dict
+                
     return cmdinfo

Modified: grass/branches/develbranch_6/lib/python/db.py
===================================================================
--- grass/branches/develbranch_6/lib/python/db.py	2010-04-10 11:20:06 UTC (rev 41772)
+++ grass/branches/develbranch_6/lib/python/db.py	2010-04-10 11:31:07 UTC (rev 41773)
@@ -26,12 +26,10 @@
 
 from core import *
 
-# run "db.describe -c ..." and parse output
-
 def db_describe(table, **args):
     """!Return the list of columns for a database table
     (interface to `db.describe -c'). Example:
-    
+
     \code
     >>> grass.db_describe('lakes')
     {'nrows': 15279, 'cols': [['cat', 'INTEGER', '11'], ['AREA', 'DOUBLE PRECISION', '20'],
@@ -108,4 +106,3 @@
         fatal(_("Fetching data from table <%s> failed") % table)
         
     return ofile.readlines()
-

Modified: grass/branches/develbranch_6/lib/python/raster.py
===================================================================
--- grass/branches/develbranch_6/lib/python/raster.py	2010-04-10 11:20:06 UTC (rev 41772)
+++ grass/branches/develbranch_6/lib/python/raster.py	2010-04-10 11:31:07 UTC (rev 41773)
@@ -33,6 +33,8 @@
     """!Set the command history for a raster map to the command used to
     invoke the script (interface to `r.support').
 
+    @param map map name
+
     @return True on success
     @return False on failure
     """
@@ -81,6 +83,5 @@
     """
     t = string.Template(exp)
     e = t.substitute(**kwargs)
-
     if write_command('r.mapcalc', stdin = e) != 0:
 	fatal("An error occurred while running r.mapcalc")

Modified: grass/branches/develbranch_6/lib/python/vector.py
===================================================================
--- grass/branches/develbranch_6/lib/python/vector.py	2010-04-10 11:20:06 UTC (rev 41772)
+++ grass/branches/develbranch_6/lib/python/vector.py	2010-04-10 11:31:07 UTC (rev 41773)
@@ -40,6 +40,7 @@
     \endcode
 
     @param map vector map
+    @param args
 
     @return dictionary { layer : { 'layer', 'table, 'database', 'driver', 'key' }
     """
@@ -71,7 +72,13 @@
 
 def vector_layer_db(map, layer):
     """!Return the database connection details for a vector map layer.
-    If db connection for given layer is not defined, fatal() is called."""
+    If db connection for given layer is not defined, fatal() is called.
+
+    @param map map name
+    @param layer layer number
+
+    @return parsed output
+    """
     try:
         f = vector_db(map)[int(layer)]
     except KeyError:
@@ -85,7 +92,7 @@
     """!Return a dictionary (or a list) of the columns for the
     database table connected to a vector map (interface to `v.info
     -c').
-    
+
     @code
     >>> vector_columns(urbanarea, getDict = True)
     {'UA_TYPE': {'index': 4, 'type': 'CHARACTER'}, 'UA': {'index': 2, 'type': 'CHARACTER'}, 'NAME': {'index': 3, 'type': 'CHARACTER'}, 'OBJECTID': {'index': 1, 'type': 'INTEGER'}, 'cat': {'index': 0, 'type': 'INTEGER'}}
@@ -123,6 +130,10 @@
 def vector_history(map):
     """!Set the command history for a vector map to the command used to
     invoke the script (interface to `v.support').
+
+    @param map mapname
+
+    @return v.support output
     """
     run_command('v.support', map = map, cmdhist = os.environ['CMDLINE'])
 



More information about the grass-commit mailing list