[GRASS-SVN] r70111 - grass-addons/grass7/raster/r.category.trim

svn_grass at osgeo.org svn_grass at osgeo.org
Wed Dec 21 03:40:42 PST 2016


Author: pvanbosgeo
Date: 2016-12-21 03:40:42 -0800 (Wed, 21 Dec 2016)
New Revision: 70111

Modified:
   grass-addons/grass7/raster/r.category.trim/r.category.trim.html
   grass-addons/grass7/raster/r.category.trim/r.category.trim.py
Log:
r.category.trim addon: code cleanup

Modified: grass-addons/grass7/raster/r.category.trim/r.category.trim.html
===================================================================
--- grass-addons/grass7/raster/r.category.trim/r.category.trim.html	2016-12-21 09:36:43 UTC (rev 70110)
+++ grass-addons/grass7/raster/r.category.trim/r.category.trim.html	2016-12-21 11:40:42 UTC (rev 70111)
@@ -1,28 +1,29 @@
 <h2>DESCRIPTION</h2>
 
 <h3>Trim redundant category labels and colors</h3>
-In GRASS you can 'cut out' a subset of a larger raster layer by 
-setting the extent to something smaller then the extent of the 
-original map using g.region and/or by setting a mask using r.mask, 
+In GRASS you can 'cut out' a subset of a larger raster layer by
+setting the extent to something smaller then the extent of the
+original map using g.region and/or by setting a mask using r.mask,
 after which you simply run r.mapcalc "newmap = oldmap".
 
-<p>You may have noticed that when creating the new map, all category 
-category labels and colour table of the original map are copied over 
-to the new map, even for category values that are not in the new 
-map. If you are working with categorical maps, this may not be what 
-you want. See <a href="https://pvanb.wordpress.com/2015/09/22/categorical-maps-and-legends/">
+<p>You may have noticed that when creating the new map, all category
+category labels and colour table of the original map are copied over
+to the new map, even for category values that are not in the new
+map. If you are working with categorical maps, this may not be what
+you want. See
+<a href="https://pvanb.wordpress.com/2015/09/22/categorical-maps-and-legends/" target="_blank">
 here</a> for a more detailed discussion.
 
-<p>With this addon you can trim the category and colour tables so it 
-only contains category labels and colour definitions for the values 
-present in the new map. You can do this on the input map, or do this 
+<p>With this addon you can trim the category and colour tables so it
+only contains category labels and colour definitions for the values
+present in the new map. You can do this on the input map, or do this
 on a copy of the map.
 
 <h3>Recode to consecutive category values</h3>
-If you prefer the map to have consecutive values (i.e., without 
-gaps), there is the option to change the category values to a 
-consecutive series by setting the n-flag. For example, if the map 
-has the following categories values and labels (after the redundant 
+If you prefer the map to have consecutive values (i.e., without
+gaps), there is the option to change the category values to a
+consecutive series by setting the n-flag. For example, if the map
+has the following categories values and labels (after the redundant
 category labels have been removed):
 
 <div class="code"><pre>2 label2
@@ -38,30 +39,30 @@
 </pre></div>
 
 <h3>Export QGIS color map file</h3>
-The addon let's you export the categories, category labels and 
-colours as QGIS colour map file. This is just a simple text file 
-with the raster categories and corresponding colour definitions and 
-category labels. QGIS can use this to set the colour and labels for 
-a raster layer. See 
-<a href="https://pvanb.wordpress.com/grass-gis-categorical-raster-layers-in-qgis">
-this blogpost</a> for more details how to use the colour map 
-file in QGIS. Alternatively, you can also export the categories and 
-category labels as a normal comma separated calues (CSV) file file, 
-which can be easily viewed in a spreadsheet program such as 
-Libre/Open Office Calc, Microsoft Excel, or Google Docs and can be 
-easily shared together with an exported raster file for users that 
+The addon let's you export the categories, category labels and
+colours as QGIS colour map file. This is just a simple text file
+with the raster categories and corresponding colour definitions and
+category labels. QGIS can use this to set the colour and labels for
+a raster layer. See
+<a href="https://pvanb.wordpress.com/2015/09/22/categorical-maps-and-legends/" target="_blank">
+this blogpost</a> for more details how to use the colour map
+file in QGIS. Alternatively, you can also export the categories and
+category labels as a normal comma separated calues (CSV) file file,
+which can be easily viewed in a spreadsheet program such as
+Libre/Open Office Calc, Microsoft Excel, or Google Docs and can be
+easily shared together with an exported raster file for users that
 use other GIS programs
 
 
 <h2>NOTE</h2>
-The file is only useful for categorical maps. 
+The file is only useful for categorical maps.
 Therefore only integer maps are accepted as input.
 
-<p>When you use the option to recode the map, you need to set an 
-output map as well. It uses the <em><a href="r.recode">r.recode </a></em> 
-function, with the 'a' flag set, i.e., the region is 
+<p>When you use the option to recode the map, you need to set an
+output map as well. It uses the <em><a href="r.recode">r.recode </a></em>
+function, with the 'a' flag set, i.e., the region is
 aligned to the input raster map.
-   
+
 <h2>Examples</h2>
 See <a href="https://pvanb.wordpress.com/grass-gis-categorical-raster-layers-in-qgis">here</a> for examples
 

Modified: grass-addons/grass7/raster/r.category.trim/r.category.trim.py
===================================================================
--- grass-addons/grass7/raster/r.category.trim/r.category.trim.py	2016-12-21 09:36:43 UTC (rev 70110)
+++ grass-addons/grass7/raster/r.category.trim/r.category.trim.py	2016-12-21 11:40:42 UTC (rev 70111)
@@ -86,16 +86,18 @@
 import sys
 from subprocess import PIPE
 from grass.pygrass.modules import Module
-import grass.script as grass
+import grass.script as gs
 
-# Check if running in GRASS
-if not os.environ.has_key("GISBASE"):
-    grass.message("You must be in GRASS GIS to run this program.")
-    sys.exit(1)
 
-# main function
-def main():
+def main(options, flags):
 
+    # Check if running in GRASS
+    gisbase = os.getenv("GISBASE")
+    if not gisbase:
+        gs.fatal(_("$GISBASE not defined. You must be in GRASS GIS to run \
+        this program"))
+        return 0
+
     # Input
     IP = options['input']
     OP = options['output']
@@ -104,47 +106,52 @@
     flags_n = flags['n']
 
     # Check if raster is integer
-    iscell = grass.raster.raster_info(IP)["datatype"]
+    iscell = gs.raster.raster_info(IP)["datatype"]
     if iscell != u'CELL':
-        grass.error('Input should be an integer raster layer')
+        gs.error(_('Input should be an integer raster layer'))
 
     # Get map category values and their labels
     CATV = Module('r.category', map=IP, stdout_=PIPE).outputs.stdout
     RCAT = CATV.split('\n')
-    RCAT = filter(None,RCAT)
+    RCAT = filter(None, RCAT)
     RID = [z.split('\t')[0] for z in RCAT]
     RIDI = map(int, RID)
 
     # Get full color table
-    RCOL = grass.read_command("r.colors.out", map=IP).split('\n')
-    RCOL = [ x for x in RCOL if "nv" not in x and 'default' not in x]
+    RCOL = gs.read_command("r.colors.out", map=IP).split('\n')
+    RCOL = [x for x in RCOL if "nv" not in x and 'default' not in x]
     RCOL = filter(None, RCOL)
     CCAT = [z.split(' ')[0] for z in RCOL]
     CCAT = map(int, CCAT)
 
     # Set strings / list to be used in loop
-    CR = ""; RECO = ""; CL = ""; CV = []
+    CR = ""
+    RECO = ""
+    CL = ""
+    CV = []
 
     # recode to consecutive category values
     if flags_n:
         RIDN = range(1, len(RID) + 1)
         RLAB = [z.split('\t')[1] for z in RCAT]
         for j in xrange(len(RID)):
-            RECO = RECO + RID[j] + ":" + RID[j] + ":" + str(RIDN[j]) + "\n"
+            RECO = '{0}{1}:{1}:{2}\n'.format(RECO, RID[j], RIDN[J])
             A = map(int, [i for i, x in enumerate(CCAT) if x == RIDI[j]])
             CV.append(RCOL[A[0]].split(' ')[1])
-            CR = CR + str(RIDN[j]) + " " + CV[j] + "\n"
-            CL = CL + str(RIDN[j]) + "|" + RLAB[j] + "\n"
+            CR = '{}{} {}\n'.format(CR, RIDN[j], CV[j])
+            CL = '{}{}|{}\n'.format(CL, RIDN[j], RLAB[j])
 
-        CR = CR + 'nv 255:255:255\ndefault 255:255:255\n'
-        Module("r.recode", flags="a", input=IP, output=OP, rules="-", stdin_=RECO, quiet=True)
+        CR = '{}nv 255:255:255\ndefault 255:255:255\n'.format(CR)
+        Module("r.recode", flags="a", input=IP, output=OP, rules="-",
+               stdin_=RECO, quiet=True)
         Module("r.colors", map=OP, rules="-", stdin_=CR, quiet=True)
-        Module("r.category", map=OP, rules="-", stdin_=CL, quiet=True, separator="pipe")
+        Module("r.category", map=OP, rules="-", stdin_=CL, quiet=True,
+               separator="pipe")
     else:
         # Check if new layer should be created
         if len(OP) > 0:
-            k = IP + "," + OP
-            grass.run_command("g.copy", raster=k)
+            k = '{},{}'.format(IP, OP)
+            gs.run_command("g.copy", raster=k)
         else:
             OP = IP
 
@@ -156,42 +163,41 @@
             A = map(int, [i for i, x in enumerate(CCAT) if x == RIDI[j]])
             CV.append(RCOL[A[0]].split(' ')[1])
             CR = CR + str(RIDI[j]) + " " + CV[j] + "\n"
-        CR = CR + 'nv 255:255:255\ndefault 255:255:255\n'
+        CR = '{}nv 255:255:255\ndefault 255:255:255\n'.format(CR)
         Module("r.colors", map=OP, rules="-", stdin_=CR, quiet=True)
 
     # If attribute table (csv format) should be written
     if len(CSV) > 0:
         if flags_n:
-            RCAT1 = CL.split('\n'); RCAT1 = filter(None,RCAT1)
-            RCAT1 = [w.replace('|', ',') for w in RCAT1]
+            RCAT1 = [w.replace('|', ',') for w in filter(None, CL.split('\n'))]
         else:
             RCAT1 = [w.replace('\t', ',') for w in RCAT]
         RCAT1.insert(0, "CATEGORY,CATEGORY LABEL")
-        CV1 = list(CV); CV1.insert(0,"RGB")
+        CV1 = list(CV)
+        CV1.insert(0,"RGB")
         text_file = open(CSV, "w")
         for k in xrange(len(RCAT1)):
-            text_file.write(RCAT1[k] + "," + CV1[k] + "\n")
+            text_file.write('{},{}\n'.format(RCAT1[k], CV1[k]))
         text_file.close()
 
     # If QGIS Color Map text files should be written
     if len(QGIS) > 0:
         RGB = [w.replace(':', ',') for w in CV]
         if flags_n:
-            RCAT = CL.split('\n'); RCAT = filter(None,RCAT)
+            RCAT = filter(None, CL.split('\n'))
             RCAT = [w.replace('|', ',') for w in RCAT]
         else:
             RCAT = [w.replace('\t', ',') for w in RCAT]
         text_file = open(QGIS, "w")
-        text_file.write("# QGIS color map for " + OP + "\n")
+        text_file.write('# QGIS color map for {}\n'.format(OP))
         text_file.write("INTERPOLATION:EXACT\n")
         for k in xrange(len(RCAT)):
             RC2 = RCAT[k].split(',')
-            text_file.write(RC2[0] + "," + RGB[k] + ",255," + RC2[1] + "\n")
+            text_file.write('{},{},255,{}\n'.format(RC2[0], RGB[k], RC2[1]))
         text_file.close()
 
 if __name__ == "__main__":
-    options, flags = grass.parser()
-    sys.exit(main())
+    sys.exit(main(*gs.parser()))
 
 
 
@@ -211,8 +217,3 @@
 
 
 
-
-
-
-
-



More information about the grass-commit mailing list