[GRASS-SVN] r67821 - in grass-addons/grass7/raster: . r.neighborhoodmatrix

svn_grass at osgeo.org svn_grass at osgeo.org
Sat Feb 13 07:23:47 PST 2016


Author: mlennert
Date: 2016-02-13 07:23:47 -0800 (Sat, 13 Feb 2016)
New Revision: 67821

Added:
   grass-addons/grass7/raster/r.neighborhoodmatrix/
   grass-addons/grass7/raster/r.neighborhoodmatrix/Makefile
   grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.html
   grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.py
Log:
r.neighborhoodmatrix: new module to calculate neighborhood matrix of raster regions/segments


Added: grass-addons/grass7/raster/r.neighborhoodmatrix/Makefile
===================================================================
--- grass-addons/grass7/raster/r.neighborhoodmatrix/Makefile	                        (rev 0)
+++ grass-addons/grass7/raster/r.neighborhoodmatrix/Makefile	2016-02-13 15:23:47 UTC (rev 67821)
@@ -0,0 +1,7 @@
+MODULE_TOPDIR = ../..
+
+PGM = r.neighborhoodmatrix
+
+include $(MODULE_TOPDIR)/include/Make/Script.make
+
+default: script

Added: grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.html
===================================================================
--- grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.html	                        (rev 0)
+++ grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.html	2016-02-13 15:23:47 UTC (rev 67821)
@@ -0,0 +1,61 @@
+<h2>DESCRIPTION</h2>
+
+<em>r.neighborhoodmatrix</em> identifies all adjacency relations between
+segments (or clumps) in a raster map and exports these as a 2xn matrix 
+where n is the number of neighborhood relations with each relation listed 
+in both directions (i.e. if a is neighbor of b, the list will contain 
+a,b and b,a).
+
+Neighborhood relations are determined pixel by pixel, and by default only 
+pixels that share a common pixel boundary are considered neighbors. When
+the <em>-d</em> flag is set pixels sharing a common corner (i.e. diagonal
+neighbors) are also taken into account.
+
+If a path to an output file is specified, the matrix will be written to that 
+file, otherwise it will be sent to standard output.
+
+<h2>NOTES</h2>
+
+The module (without the <em>-d</em> flag) should give the same result as the equivalent call to 
+<a href="v.neighborhoodmatrix.html">v.neighborhoodmatrix</a> with the <em>-b</em>
+flag. Currently it actually seems faster for some maps to transform the raster 
+to vector and then run the latter. More tests are needed, though, to confirm
+this.
+
+<h2>TODO</h2>
+
+Add flag to only output half matrix with each relation only shown once.
+
+<h2>EXAMPLE</h2>
+
+Send the neighborhood matrix of the counties in the boundary_county map of the 
+North Carolina dataset to standard output:
+
+<div class="code"><pre>
+r.neighborhoodmatrix in=boundary_county_500m sep=comma
+</pre></div>
+
+Idem, but sending the output to a file:
+
+<div class="code"><pre>
+r.neighborhoodmatrix in=boundary_county_500m sep=comma output=county_neighbors.csv
+</pre></div>
+
+Transforming the raster to vector (without attribute table or topology) and the using
+<a href="v.neighborhoodmatrix.html">v.neighborhoodmatrix</a>:
+
+<div class="code"><pre>
+r.to.vect -tbv in=boundary_county_500m out=boundary_county_500m type=area
+v.neighborhoodmatrix in=boundary_county_500m sep=comma
+</pre></div>
+
+<h2>SEE ALSO</h2>
+
+<em>
+<a href="v.neighborhoodmatrix.html">v.neighborhoodmatrix</a>
+</em>
+
+<h2>AUTHOR</h2>
+ Moritz Lennert
+
+<p><i>Last changed: $Date: 2014-10-20 12:38:08 +0200 (lun 20 oct 2014) $</i>

Added: grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.py
===================================================================
--- grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.py	                        (rev 0)
+++ grass-addons/grass7/raster/r.neighborhoodmatrix/r.neighborhoodmatrix.py	2016-02-13 15:23:47 UTC (rev 67821)
@@ -0,0 +1,137 @@
+#!/usr/bin/env python
+#
+############################################################################
+#
+# MODULE:	r.neighborhoodmatrix
+# AUTHOR(S):	Moritz Lennert
+#
+# PURPOSE:	Calculates a neighborhood matrix for a raster map with regions
+#               (e.g. the output of r.clump or i.segment)
+# COPYRIGHT:	(C) 1997-2016 by 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.
+#
+
+#%Module
+#% description: Calculates a neighborhood matrix for a raster map with regions
+#% keyword: raster
+#% keyword: neighboorhood
+#% keyword: regions
+#%end
+#
+#%option G_OPT_R_INPUT
+#% description: Raster for which to calculate the neighboorhood matrix
+#% required: yes
+#%end
+#
+#%option G_OPT_F_OUTPUT
+#% description: Name for output file (- for standard output)
+#% required: yes
+#% answer: -
+#%end
+#
+#%option G_OPT_F_SEP
+#%end
+#
+#%flag
+#% key: d
+#% description: Also take into account diagonal neighbors
+#%end
+
+import grass.script as gscript
+import sys
+import os
+import atexit
+
+def cleanup():
+    for nmap in n_mapnames.values():
+        gscript.run_command('g.remove', flags='f', type='raster',
+                          pat=nmap, quiet=True)
+    gscript.run_command('g.remove', flags='f', type='raster',
+                      pat=temp_map, quiet=True)
+
+    if diag:
+        for nmap in n_diag_mapnames.values():
+            gscript.run_command('g.remove', flags='f', type='raster',
+                              pat=nmap, quiet=True)
+
+def main():
+    rinput = options['input']
+    output = options['output']
+    separator = gscript.separator(options['separator'])
+
+    neighbors = []
+
+    global pid, n_mapnames, diag, temp_map
+    diag = False
+    pid = os.getpid()
+    n_mapnames = {}
+    n_mapnames['nl'] = "temp_nl_map_%d" % pid
+    n_mapnames['nr'] = "temp_nr_map_%d" % pid
+    n_mapnames['nu'] = "temp_nu_map_%d" % pid
+    n_mapnames['nd'] = "temp_nd_map_%d" % pid
+    temp_map = "temp_rneighborhoodmatrix_map_%d" % pid
+
+    nbs = {'nl': '[0,-1]', 'nr': '[0,1]', 'nu': '[1,0]', 'nd': '[-1,0]'}
+    nbs_diag = {'nul': '[1,-1]', 'nur': '[1,1]', 'nll': '[-1,-1]', 'nlr': '[-1,1]'}
+    for n, modifier in nbs.items():
+        expression = "%s = (%s%s)" % (temp_map, rinput, modifier)
+        gscript.run_command('r.mapcalc',
+                            expression=expression,
+                            overwrite=True,
+                            quiet=True)
+        expression = "%s = if(%s!=%s, %s, null())" % (n_mapnames[n], temp_map,
+                rinput, temp_map)
+        gscript.run_command('r.mapcalc',
+                            expression=expression,
+                            quiet=True)
+        rstats_results  = gscript.read_command('r.stats',
+                             input_=[rinput, n_mapnames[n]],
+                             flags='n1',
+                             separator=separator,
+                             quiet=True)
+        results = rstats_results.splitlines()
+	neighbors += results
+
+
+    if flags['d']:
+        diag = True
+        global n_diag_mapnames
+        n_diag_mapnames = {}
+        n_diag_mapnames['nul'] = "temp_nul_map_%d" % pid
+        n_diag_mapnames['nur'] = "temp_nur_map_%d" % pid
+        n_diag_mapnames['nll'] = "temp_nll_map_%d" % pid
+        n_diag_mapnames['nlr'] = "temp_nlr_map_%d" % pid
+
+        for n, modifier in nbs_diag.items():
+            expression = "%s = if(%s%s!=%s, %s%s, null())" % (n_diag_mapnames[n], rinput,
+                    modifier, rinput, rinput, modifier)
+            gscript.run_command('r.mapcalc',
+                                expression=expression,
+                                quiet=True)
+	    rstats_results  = gscript.read_command('r.stats',
+				 input_=[rinput, n_diag_mapnames[n]],
+				 flags='n1',
+				 separator=separator,
+				 quiet=True)
+	    results = rstats_results.splitlines()
+	    neighbors += results
+
+    unique_neighbors = list(set(neighbors))
+    unique_neighbors_sorted = gscript.natural_sort(unique_neighbors)
+
+    if output == '-':
+        for line in unique_neighbors_sorted:
+            sys.stdout.write(line+"\n")	
+    else:
+	of = open(output, 'w')
+        for line in unique_neighbors_sorted:
+            of.write(line+"\n")
+        of.close()
+
+if __name__ == "__main__":
+    options, flags = gscript.parser()
+    atexit.register(cleanup)
+    main()



More information about the grass-commit mailing list