[GRASS-SVN] r64755 - grass-addons/grass7/raster/r.catchment

svn_grass at osgeo.org svn_grass at osgeo.org
Thu Feb 26 12:46:48 PST 2015


Author: isaacullah
Date: 2015-02-26 12:46:48 -0800 (Thu, 26 Feb 2015)
New Revision: 64755

Modified:
   grass-addons/grass7/raster/r.catchment/r.catchment.html
   grass-addons/grass7/raster/r.catchment/r.catchment.py
Log:
Updating script to PEP-8 conventions (except long lines), and fixing g.parser code so that the overwrite flag will be enabled. Fixed length of lines in the html man page.

Modified: grass-addons/grass7/raster/r.catchment/r.catchment.html
===================================================================
--- grass-addons/grass7/raster/r.catchment/r.catchment.html	2015-02-26 18:30:35 UTC (rev 64754)
+++ grass-addons/grass7/raster/r.catchment/r.catchment.html	2015-02-26 20:46:48 UTC (rev 64755)
@@ -1,28 +1,80 @@
 <h2>DESCRIPTION</h2>
 
-<em>r.catchment</em> is a module that facilitates modeling "catchments" around point locations according to a walking cost function. The module is particularly aimed at "Site Catchment Analysis" for archaeology, but could be potentially useful in any number of appliations where delimiting an area based on walking-costs is desireable. Although defining a catchment based on a threshold in walking-costs (or time) can be undertaken using <em>r.walk</em> or <em>r.cost</em> alone, this addon module allows the user to enter a pre-determined square meterage (option <b>area</b>) for the resultant catchment, which is a different approach. This is useful for applications where the user wants to make a catchment of a particular size (e.g., certain number of square meters needed for farmed fields), and doesn't want to spend time via trial and error experimenting with different cost radii. 
+<em>r.catchment</em> is a module that facilitates modeling 
+"catchments" around point locations according to a walking cost 
+function. The module is particularly aimed at "Site Catchment 
+Analysis" for archaeology, but could be potentially useful in any 
+number of appliations where delimiting an area based on 
+walking-costs is desireable. Although defining a catchment based on 
+a threshold in walking-costs (or time) can be undertaken using <em>
+r.walk</em> or <em>r.cost</em> alone, this addon module allows the 
+user to enter a pre-determined square meterage (option <b>area</b>) 
+for the resultant catchment, which is a different approach. This is 
+useful for applications where the user wants to make a catchment of 
+a particular size (e.g., certain number of square meters needed for 
+farmed fields), and doesn't want to spend time via trial and error 
+experimenting with different cost radii. 
 
-Additionally, this module allows the user to enter a slope threshold (option <b>sigma</b>), which will mask out areas of higher slope. This is useful for delimiting catchments that are of generally flat land (e.g., areas where agriculture are likely).
+Additionally, this module allows the user to enter a slope threshold 
+(option <b>sigma</b>), which will mask out areas of higher slope. 
+This is useful for delimiting catchments that are of generally flat 
+land (e.g., areas where agriculture are likely).
 
 <h3>Options and flags:</h3>
 
-<em>r.catchment</em> requires an input elevation map, <b>elevation</b>, and an input vector points map of starting locations, <b>start_points</b>. <b>area</b> is also requited, which is an integer value for the size of the desired catchment (in the map units of the defined location/region). The final required parameter is <b>map_val</b>, wich is the integer value to write to the areas defined as part of the catchment in the output map, <b>buffer</b>. The optional value, <b>sigma</b> is the slope threshold cut off value. Slopes above <b>sigma</b> will be masked out during the determination of the catchment configuration. There are two native flags for <em>r.catchment</em>. <b>-c</b> allows you to keep the interim cost surface maps made. <b>-l</b> allows you to show a list of the cost values in that cost map, along with the size of the catchments they delineate. All other flags and options are inherited from <em>r.walk</em> (see the<a href="r.walk.html">r.walk</a> help page fo
 r more information on these).
+<em>r.catchment</em> requires an input elevation map, <b>elevation
+</b>, and an input vector points map of starting locations, <b>
+start_points</b>. <b>area</b> is also requited, which is an integer 
+value for the size of the desired catchment (in the map units of the 
+defined location/region). The final required parameter is <b>map_val
+</b>, wich is the integer value to write to the areas defined as 
+part of the catchment in the output map, <b>buffer</b>. The optional 
+value, <b>sigma</b> is the slope threshold cut off value. Slopes 
+above <b>sigma</b> will be masked out during the determination of 
+the catchment configuration. There are two native flags for <em>
+r.catchment</em>. <b>-c</b> allows you to keep the interim cost 
+surface maps made. <b>-l</b> allows you to show a list of the cost 
+values in that cost map, along with the size of the catchments they 
+delineate. All other flags and options are inherited from <em>r.walk
+</em> (see the<a href="r.walk.html">r.walk</a> help page for more 
+information on these).
 
 <h2>NOTES</h2>
-The module will attempt to find the cost radius that defines an area close to the value of <b>area</b>, but em will likely slightly overestimate the catchement size. The module will display the actual area of the defined catchment in the Command Output.
+The module will attempt to find the cost radius that defines an area 
+close to the value of <b>area</b>, but em will likely slightly 
+overestimate the catchement size. The module will display the actual 
+area of the defined catchment in the Command Output.
 
-By default, <em>r.catchment</em> will create a <b>friction</b> map of value 0, which, when input into <em>r.walk</em> will yeild a cost surface based on walking times only. The user may optionally create a <b>friction</b> map, however, and, if used, r.walk will consider these costs this as well when determining the cost surface used to determine the catchment.
+By default, <em>r.catchment</em> will create a <b>friction</b> map 
+of value 0, which, when input into <em>r.walk</em> will yeild a cost 
+surface based on walking times only. The user may optionally create 
+a <b>friction</b> map, however, and, if used, r.walk will consider 
+these costs this as well when determining the cost surface used to 
+determine the catchment.
 
-The input vector points map can be manually digitized (with <em>v.digit</em>) over topographic or cultural features, or can be created as a series of random points (with <em>r.random</em> or <em>v.random</em>). 
+The input vector points map can be manually digitized (with <em>
+v.digit</em>) over topographic or cultural features, or can be 
+created as a series of random points (with <em>r.random</em> or <em>
+v.random</em>). 
 
-In the case of multiple input points, the routine will attempt to equally divide the area (<b>area</b>) between all input points to determine catchments for each point. The total area of all these catchments will sum (close) to <b>area</b>. If two input points are close, their catchments may overlap. In this case, the routine will "meld" the two, and the melded catchment will still be of an area close to <b>area</b>. If truly overlapping catchments are desired, then the routine should be run independantly for each individual start point.
+In the case of multiple input points, the routine will attempt to 
+equally divide the area (<b>area</b>) between all input points to 
+determine catchments for each point. The total area of all these 
+catchments will sum (close) to <b>area</b>. If two input points are 
+close, their catchments may overlap. In this case, the routine will 
+"meld" the two, and the melded catchment will still be of an area 
+close to <b>area</b>. If truly overlapping catchments are desired, 
+then the routine should be run independantly for each individual 
+start point.
 <p>
 
 <h2>EXAMPLES</h2>
-Delimit a catchment of 5,000,000 square meters around a single start point, ignoring areas of slope > 15 degrees:<br>
+Delimit a catchment of 5,000,000 square meters around a single start 
+point, ignoring areas of slope > 15 degrees:<br>
 
 <div class="code"><pre>
-r.catchment elevation=DEM10m start_points=site buffer=test_catchment sigma=15 area=5000000 map_val=1
+r.catchment elevation=DEM10m start_points=site buffer=test_catchment 
+sigma=15 area=5000000 map_val=1
 </pre></div>
 
 

Modified: grass-addons/grass7/raster/r.catchment/r.catchment.py
===================================================================
--- grass-addons/grass7/raster/r.catchment/r.catchment.py	2015-02-26 18:30:35 UTC (rev 64754)
+++ grass-addons/grass7/raster/r.catchment/r.catchment.py	2015-02-26 20:46:48 UTC (rev 64755)
@@ -2,25 +2,25 @@
 #
 ############################################################################
 #
-# MODULE:                   r.catchment
-# AUTHOR(S):		Isaac Ullah, Arizona State University
-# PURPOSE:		Creates a raster buffer of specified area around vector points
-#			using cost distances. Module requires r.walk.
-# ACKNOWLEDGEMENTS:	National Science Foundation Grant #BCS0410269
-# COPYRIGHT:		(C) 2015 by Isaac Ullah, Arizona State University
-#			This program is free software under the GNU General Public
-#			License (>=v2). Read the file COPYING that comes with GRASS
-#			for details.
+# MODULE:               r.catchment
+# AUTHOR(S):            Isaac Ullah, Arizona State University
+# PURPOSE:              Creates a raster buffer of specified area around vector points
+#                       using cost distances. Module requires r.walk.
+# ACKNOWLEDGEMENTS:     National Science Foundation Grant #BCS0410269
+# COPYRIGHT:            (C) 2015 by Isaac Ullah, Arizona State University
+#                       This program is free software under the GNU General Public
+#                       License (>=v2). Read the file COPYING that comes with GRASS
+#                       for details.
 #
 #############################################################################
 
 
 #%Module
-#%  description: Creates a raster buffer of specified area around vector points using cost distances using r.walk. NOTE: please run g.region first to make sure region boundaries and resolution match input elevation map.
+#%  description: Creates a raster buffer of specified area around vector pointsusing cost distances using r.walk. NOTE: please run g.region first to make sure region boundaries and resolution match input elevation map.
 #%END
 
 
-#%option G_OPT_R_ELEV
+#%option G_OPT_R_INPUT
 #% key: elevation
 #% description: Input elevation map (DEM)
 #% required : yes
@@ -83,7 +83,7 @@
 #% answer: -0.2125
 #% required : no
 #%END
-#%option G_OPT_R_INPUT
+#%option G_OPT_R_OUTPUT
 #% key: buffer
 #% description: Output buffer map
 #% required : yes
@@ -127,25 +127,34 @@
 import os
 import subprocess
 import tempfile
-#import random
+
+# Just in case system can't find where grass.script is
 grass_install_tree = os.getenv('GISBASE')
 sys.path.append(grass_install_tree + os.sep + 'etc' + os.sep + 'python')
+
+
 import grass.script as grass
-# first define a useful custom method
 
-# m is a grass/bash command that will generate some list of keyed info to stdout where the keys are numeric values, n is the character that separates the key from the data, o is a defined blank dictionary to write results to
+
+# m is a grass/bash command that will generate some list of keyed info to
+# stdout where the keys are numeric values, n is the character that separates
+# the key from the data, o is a defined blank dictionary to write results to
 def out2dictnum(m, n, o):
+    """Execute a grass command, and parse it to a dictionary"""
     p1 = subprocess.Popen('%s' % m, stdout=subprocess.PIPE, shell='bash')
     p2 = p1.stdout.readlines()
     for y in p2:
-        y0,y1 = y.split('%s' % n)
+        y0, y1 = y.split('%s' % n)
         y0num = float(y0)
         o[y0num] = y1.strip('\n')
 
-#main block of code starts here
+
+# main block of code starts here
 def main():
+    """Creates a raster buffer of specified area around
+    vector points using cost distances using r.walk."""
     pid = os.getpid()
-    #setting up variables for use later on
+    # setting up variables for use later on
     elevation = options["elevation"]
     start_points = options["start_points"]
     lambda_ = options["lambda"]
@@ -158,12 +167,12 @@
     area = float(options["area"])
     buff = options["buffer"]
     mapval = options["map_val"]
-    w_coefs = a + ',' +  b + ',' + c + ',' + d
+    w_coefs = a + ',' + b + ',' + c + ',' + d
     if "MASK" in grass.list_grouped('rast')[grass.gisenv()['MAPSET']] and bool(options["sigma"]) is True:
         grass.message('There is already a MASK in place, and you have also selected to mask slope values above %s.\n The high slope areas (slope mask) will be temporarily added to current MASKED areas for the calcualtion of the catchment geometry.\n The original MASK will be restored when the module finishes' % sigma)
         ismask = 2
         tempmask = "temporary.mask.%s" % pid
-        grass.run_command('g.rename', quiet = True, overwrite = grass.overwrite(), raster = "MASK,%s" % tempmask)
+        grass.run_command('g.rename', quiet=True, overwrite=grass.overwrite(), raster="MASK,%s" % tempmask)
     elif "MASK" in grass.list_grouped('rast')[grass.gisenv()['MAPSET']]:
         grass.message('There is a MASK in place. The areas MASKed out will be ignored while calculating catchment geometry.')
         ismask = 1
@@ -185,24 +194,24 @@
         else:
             grass.message('Calculating for time costs only')
             friction = "temporary.friction.%s" % pid
-            grass.mapcalc("${out} = if(isnull(${rast1}), null(), 0)", overwrite = grass.overwrite(), quiet = True, out = friction,  rast1 = elevation)
+            grass.mapcalc("${out} = if(isnull(${rast1}), null(), 0)", overwrite=grass.overwrite(), quiet=True, out=friction, rast1=elevation)
         if flags["k"] is True:
             grass.message('Using Knight\'s move\n')
             #NOTE! because "lambda" is an internal python variable, it is impossible to enter the value for key "lambda" in r.walk. It ends up with a python error.
-            grass.run_command('r.walk', quiet = True, overwrite = grass.overwrite(), flags = 'k', elevation = elevation, friction = friction, output = cost, start_points = start_points, walk_coeff = w_coefs, memory = '100', slope_factor = slope_factor, lambda_ = lambda_)
+            grass.run_command('r.walk', quiet=True, overwrite=grass.overwrite(), flags='k', elevation=elevation, friction=friction, output=cost, start_points=start_points, walk_coeff=w_coefs, memory='100', slope_factor=slope_factor, lambda_=lambda_)
         else:
-            grass.run_command('r.walk', quiet = True, overwrite = grass.overwrite(), elevation = elevation, friction = friction, output = cost, start_points = start_points, memory = '100', walk_coeff = w_coefs, slope_factor = slope_factor, lambda_ = lambda_)
+            grass.run_command('r.walk', quiet=True, overwrite=grass.overwrite(), elevation=elevation, friction=friction, output=cost, start_points=start_points, memory='100', walk_coeff=w_coefs, slope_factor=slope_factor, lambda_=lambda_)
         if bool(options["friction"]) is False:
-            grass.run_command('g.remove', quiet = True, flags = 'f', type = 'raster', name = friction)
+            grass.run_command('g.remove', quiet=True, flags='f', type='raster', name=friction)
 #################################################
     if bool(options["sigma"]) is True:
         grass.message('\n\nCreating optional slope mask\n')
         slope = "temporary.slope.%s" % pid
-        grass.run_command('r.slope.aspect', quiet = True, overwrite = grass.overwrite(),  elevation = elevation,  slope = slope)
+        grass.run_command('r.slope.aspect', quiet=True, overwrite=grass.overwrite(), elevation=elevation, slope=slope)
         if ismask == 2:
-            grass.mapcalc("MASK=if(${rast1} <= ${sigma}, 1, if(${tempmask}, 1, null()))", overwrite = grass.overwrite(), quiet = True, sigma = sigma, rast1 = slope,  tempmask = tempmask)
+            grass.mapcalc("MASK=if(${rast1} <= ${sigma}, 1, if(${tempmask}, 1, null()))", overwrite=grass.overwrite(), quiet=True, sigma=sigma, rast1=slope, tempmask=tempmask)
         else:
-            grass.mapcalc("MASK=if(${rast1} <= ${sigma}, 1, null())", overwrite = grass.overwrite(), quiet = True, sigma = sigma, rast1 = slope)
+            grass.mapcalc("MASK=if(${rast1} <= ${sigma}, 1, null())", overwrite=grass.overwrite(), quiet=True, sigma=sigma, rast1=slope)
     else:
         grass.message('No slope mask created')
 ##################################################
@@ -214,30 +223,30 @@
             testarea = 0
             #start the loop, and list the values
             for key in sorted(areadict):
-                testarea = testarea +  int(float(areadict[key]))
-                grass.message("%s | %s" % (int(key),  testarea))
+                testarea = testarea + int(float(areadict[key]))
+                grass.message("%s | %s" % (int(key), testarea))
             if flags["c"] is True:
                 if bool(options["in_cost"]) is False:
-                    grass.run_command('g.rename', overwrite = grass.overwrite(),  quiet = True,  rast = 'temporary.cost.%s,%s_cost_surface' % (pid, buff))
+                    grass.run_command('g.rename', overwrite=grass.overwrite(), quiet=True, rast='temporary.cost.%s,%s_cost_surface' % (pid, buff))
                     grass.message('Cleaning up...(keeping cost map)')
-                    grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s' % pid)
+                    grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s' % pid)
                 else:
                     grass.message('Cleaning up...1')
-                    grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s' % pid)
+                    grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s' % pid)
             else:
                 if bool(options["in_cost"]) is False:
                     grass.message('Cleaning up...2')
-                    grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s,temporary.cost.%s' % (pid, pid))
+                    grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s,temporary.cost.%s' % (pid, pid))
                 else:
                     grass.message('Cleaning up...3')
-                    grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s' % pid)
+                    grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s' % pid)
             if bool(options["sigma"]) is True:
-                grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = slope)
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name=slope)
             if ismask == 2:
                 grass.message('Reinstating original MASK...')
-                grass.run_command('g.rename', overwrite = grass.overwrite(), quiet = "True", rast = tempmask +',MASK')
+                grass.run_command('g.rename', overwrite=grass.overwrite(), quiet="True", rast=tempmask + ',MASK')
             elif ismask == 0 and bool(options["sigma"]) is True:
-                grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'MASK')
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='MASK')
             elif ismask == 1:
                 grass.message('Keeping original MASK')
             grass.message('     DONE!')
@@ -250,13 +259,13 @@
         for key in sorted(areadict):
             tot_area = tot_area + int(float(areadict[key]))
             maxcost = key
-        grass.message("Maximum cost distance value %s covers an area of %s square map units\n\nCommencing to find a catchment configuration.....\n\n" % (int(maxcost),  tot_area))
+        grass.message("Maximum cost distance value %s covers an area of %s square map units\n\nCommencing to find a catchment configuration.....\n\n" % (int(maxcost), tot_area))
         testarea = 0
         lastarea = 0
         lastkey = 0
         #start the loop, and home in on the target range
         for key in sorted(areadict):
-            testarea = testarea +  int(float(areadict[key]))
+            testarea = testarea + int(float(areadict[key]))
             if testarea >= area:
                 break
             lastkey = key
@@ -273,39 +282,40 @@
         temp = tempfile.NamedTemporaryFile()
         temp.write('0 thru %s = %s\n' % (int(cutoff),  mapval))
         temp.flush()
-        grass.run_command('r.reclass', overwrite = grass.overwrite(),  input = cost,  output = 'cost.reclass.%s' % pid,  rules = temp.name)
+        grass.run_command('r.reclass', overwrite=grass.overwrite(), input=cost, output='cost.reclass.%s' % pid, rules=temp.name)
         temp.close()
-        grass.mapcalc("${out}=if(isnull(${cost}), null(), ${cost})", overwrite = grass.overwrite(), quiet = True, cost = "cost.reclass.%s" % pid, out = buff)
+        grass.mapcalc("${out}=if(isnull(${cost}), null(), ${cost})", overwrite=grass.overwrite(), quiet=True, cost="cost.reclass.%s" % pid, out=buff)
         grass.message("\nThe output catchment map will be named %s" % buff)
-        grass.run_command('r.colors', quiet = True,  map = buff, color = 'ryb')
+        grass.run_command('r.colors', quiet=True, map=buff, color='ryb')
         if flags["c"] is True:
             if bool(options["in_cost"]) is False:
-                grass.run_command('g.rename', overwrite = grass.overwrite(),  quiet = True,  rast = 'temporary.cost,%s_cost_surface' % (buff))
+                grass.run_command('g.rename', overwrite=grass.overwrite(), quiet=True, rast='temporary.cost,%s_cost_surface' % (buff))
                 grass.message('Cleaning up...(keeping cost map)')
-                grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s' % pid)
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s' % pid)
             else:
                 grass.message('Cleaning up...1')
-                grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s' % pid)
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s' % pid)
         else:
             if bool(options["in_cost"]) is False:
                 grass.message('Cleaning up...2')
-                grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name = 'cost.reclass.%s,temporary.cost.%s' % (pid, pid))
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s,temporary.cost.%s' % (pid, pid))
             else:
                 grass.message('Cleaning up...3')
-                grass.run_command('g.remove',  quiet = True,  flags = 'f', type = 'raster', name = 'cost.reclass.%s' % pid)
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='cost.reclass.%s' % pid)
             if bool(options["sigma"]) is True:
-                grass.run_command('g.remove',  quiet = True,  flags = 'f', type = 'raster', name = slope)
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name=slope)
             if ismask == 2:
                 grass.message('Reinstating original MASK...')
-                grass.run_command('g.rename', overwrite = grass.overwrite(), quiet = "True", rast = tempmask +',MASK')
+                grass.run_command('g.rename', overwrite=grass.overwrite(), quiet="True", rast=tempmask + ',MASK')
             elif ismask == 0 and bool(options["sigma"]) is True:
-                grass.run_command('g.remove',  quiet = True, flags = 'f', type = 'raster', name ='MASK')
+                grass.run_command('g.remove', quiet=True, flags='f', type='raster', name='MASK')
             elif ismask == 1:
                 grass.message('Keeping original MASK')
         grass.message('     DONE!')
         return
 
-# here is where the code in "main" actually gets executed. This way of programming is neccessary for the way g.parser needs to run in GRASS 7.
+# here is where the code in "main" actually gets executed.
+# This way of programming is neccessary for the way g.parser needs to run in GRASS 7.
 if __name__ == "__main__":
     options, flags = grass.parser()
     main()



More information about the grass-commit mailing list